context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
///////////////////////////////////////////////////////////////////////////////
//File: Wrapper.cs
//
//Description: Contains the interface definitions for the MetaViewWrappers classes.
//
//References required:
// System.Drawing
//
//This file is Copyright (c) 2010 VirindiPlugins
//
//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.Runtime.InteropServices;
#if METAVIEW_PUBLIC_NS
namespace MetaViewWrappers
#else
namespace MyClasses.MetaViewWrappers
#endif
{
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
delegate void dClickedList(object sender, int row, int col);
#region EventArgs Classes
[ComVisible(false)]
internal class MVControlEventArgs : EventArgs
{
private int id;
internal MVControlEventArgs(int ID)
{
this.id = ID;
}
public int Id
{
get { return this.id; }
}
}
[ComVisible(false)]
internal class MVIndexChangeEventArgs : MVControlEventArgs
{
private int index;
internal MVIndexChangeEventArgs(int ID, int Index)
: base(ID)
{
this.index = Index;
}
public int Index
{
get { return this.index; }
}
}
[ComVisible(false)]
internal class MVListSelectEventArgs : MVControlEventArgs
{
private int row;
private int col;
internal MVListSelectEventArgs(int ID, int Row, int Column)
: base(ID)
{
this.row = Row;
this.col = Column;
}
public int Row
{
get { return this.row; }
}
public int Column
{
get { return this.col; }
}
}
[ComVisible(false)]
internal class MVCheckBoxChangeEventArgs : MVControlEventArgs
{
private bool check;
internal MVCheckBoxChangeEventArgs(int ID, bool Check)
: base(ID)
{
this.check = Check;
}
public bool Checked
{
get { return this.check; }
}
}
[ComVisible(false)]
internal class MVTextBoxChangeEventArgs : MVControlEventArgs
{
private string text;
internal MVTextBoxChangeEventArgs(int ID, string text)
: base(ID)
{
this.text = text;
}
public string Text
{
get { return this.text; }
}
}
[ComVisible(false)]
internal class MVTextBoxEndEventArgs : MVControlEventArgs
{
private bool success;
internal MVTextBoxEndEventArgs(int ID, bool success)
: base(ID)
{
this.success = success;
}
public bool Success
{
get { return this.success; }
}
}
#endregion EventArgs Classes
#region View
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IView: IDisposable
{
void Initialize(Decal.Adapter.Wrappers.PluginHost p, string pXML);
void InitializeRawXML(Decal.Adapter.Wrappers.PluginHost p, string pXML);
void SetIcon(int icon, int iconlibrary);
void SetIcon(int portalicon);
string Title { get; set; }
bool Visible { get; set; }
#if !VVS_WRAPPERS_PUBLIC
ViewSystemSelector.eViewSystem ViewType { get; }
#endif
System.Drawing.Point Location { get; set; }
System.Drawing.Rectangle Position { get; set; }
System.Drawing.Size Size { get; }
IControl this[string id] { get; }
void Activate();
void Deactivate();
bool Activated { get; set; }
}
#endregion View
#region Controls
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IControl : IDisposable
{
string Name { get; }
bool Visible { get; }
string TooltipText { get; set;}
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IButton : IControl
{
string Text { get; set; }
event EventHandler Hit;
event EventHandler<MVControlEventArgs> Click;
System.Drawing.Color TextColor { get; set; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface ICheckBox : IControl
{
string Text { get; set; }
bool Checked { get; set; }
event EventHandler<MVCheckBoxChangeEventArgs> Change;
event EventHandler Change_Old;
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface ITextBox : IControl
{
string Text { get; set; }
event EventHandler<MVTextBoxChangeEventArgs> Change;
event EventHandler Change_Old;
event EventHandler<MVTextBoxEndEventArgs> End;
int Caret { get; set; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface ICombo : IControl
{
IComboIndexer Text { get; }
IComboDataIndexer Data { get; }
int Count { get; }
int Selected { get; set; }
event EventHandler<MVIndexChangeEventArgs> Change;
event EventHandler Change_Old;
void Add(string text);
void Add(string text, object obj);
void Insert(int index, string text);
void RemoveAt(int index);
void Remove(int index);
void Clear();
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IComboIndexer
{
string this[int index] { get; set; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IComboDataIndexer
{
object this[int index] { get; set; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface ISlider : IControl
{
int Position { get; set; }
event EventHandler<MVIndexChangeEventArgs> Change;
event EventHandler Change_Old;
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IList : IControl
{
event EventHandler<MVListSelectEventArgs> Selected;
event dClickedList Click;
void Clear();
IListRow this[int row] { get; }
IListRow AddRow();
IListRow Add();
IListRow InsertRow(int pos);
IListRow Insert(int pos);
int RowCount { get; }
void RemoveRow(int index);
void Delete(int index);
int ColCount { get; }
int ScrollPosition { get; set;}
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IListRow
{
IListCell this[int col] { get; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IListCell
{
System.Drawing.Color Color { get; set; }
int Width { get; set; }
object this[int subval] { get; set; }
void ResetColor();
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IStaticText : IControl
{
string Text { get; set; }
event EventHandler<MVControlEventArgs> Click;
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface INotebook : IControl
{
event EventHandler<MVIndexChangeEventArgs> Change;
int ActiveTab { get; set; }
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
interface IProgressBar : IControl
{
int Position { get; set; }
int Value { get; set; }
string PreText { get; set; }
}
#endregion Controls
}
| |
// 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.Xml;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class ParamsObjectsCreation : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+ParamsObjectsCreation
// Test Case
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding Comment") { Param = "XComment", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, without decl") { Param = "Mix2", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding PI") { Param = "XPI", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding element") { Param = "XElement", Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding string/whitespace") { Param = "Whitespace", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order") { Param = "Mix1", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, cloned") { Param = "Mix1", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding string/whitespace") { Param = "Whitespace", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding Comment cloned") { Param = "XComment", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding element cloned") { Param = "XElement", Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, without decl; cloned") { Param = "Mix2", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding PI cloned") { Param = "XPI", Priority = 1 } });
AddChild(new TestVariation(CreateXDocumentMixNoArrayNotConnected) { Attribute = new VariationAttribute("XDocument - params no array") { Priority = 0 } });
AddChild(new TestVariation(CreateXDocumentMixNoArrayConnected) { Attribute = new VariationAttribute("XDocument - params no array - connected") { Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - XDocument node") { Param = "Document", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - Mix with attribute") { Param = "MixAttr", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - attribute node") { Param = "Attribute", Priority = 1 } });
AddChild(new TestVariation(XDocumentInvalidCloneSanity) { Attribute = new VariationAttribute("XDocument - Invalid case with clone - double root - sanity") { Priority = 1 } });
AddChild(new TestVariation(XDocumentTheSameReferenceSanity) { Attribute = new VariationAttribute("XDocument - the same node instance, connected - sanity") { Param = true, Priority = 1 } });
AddChild(new TestVariation(XDocumentTheSameReferenceSanity) { Attribute = new VariationAttribute("XDocument - the same node instance - sanity") { Param = false, Priority = 1 } });
AddChild(new TestVariation(XDocumentIEnumerable) { Attribute = new VariationAttribute("XDocument - IEnumerable - connected") { Param = true, Priority = 0 } });
AddChild(new TestVariation(XDocumentIEnumerable) { Attribute = new VariationAttribute("XDocument - IEnumerable - not connected") { Param = false, Priority = 0 } });
AddChild(new TestVariation(XDocument2xIEnumerable) { Attribute = new VariationAttribute("XDocument - 2 x IEnumerable - sanity") { Priority = 0 } });
}
// XDocument
// - from node without parent, from nodes with parent
// - allowed types
// - attributes
// - Document
// - doubled decl, root elem, doctype
// - the same valid object instance multiple times
// - array/IEnumerable of allowed types
// - array/IEnumerable including not allowed types
//[Variation(Priority = 0, Desc = "XDocument - adding element", Param = "XElement")]
//[Variation(Priority = 1, Desc = "XDocument - adding PI", Param = "XPI")]
//[Variation(Priority = 1, Desc = "XDocument - adding XmlDecl", Param = "XmlDecl")]
//[Variation (Priority=1, Desc="XDocument - adding dot type")]
//[Variation(Priority = 1, Desc = "XDocument - adding Comment", Param = "XComment")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order", Param = "Mix1")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, without decl", Param = "Mix2")]
//[Variation(Priority = 2, Desc = "XDocument - adding string/whitespace", Param = "Whitespace")]
public void CreateXDocumentMixNoArrayConnected()
{
var doc1 = new XDocument(new XProcessingInstruction("PI", "data"), new XComment("comm1"), new XElement("root", new XAttribute("id", "a1")), new XComment("comm2"));
var nodes = new XNode[4];
XNode nn = doc1.FirstNode;
for (int i = 0; i < nodes.Length; i++)
{
nodes[i] = nn;
nn = nn.NextNode;
}
var doc = new XDocument(nodes[0], nodes[1], nodes[2], nodes[3]);
int nodeCounter = 0;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
TestLog.Compare(n != nodes[nodeCounter], "identity");
TestLog.Compare(XNode.DeepEquals(n, nodes[nodeCounter]), "Equals");
TestLog.Compare(nodes[nodeCounter].Document == doc1, "orig Document");
TestLog.Compare(n.Document == doc, "new Document");
nodeCounter++;
}
TestLog.Compare(nodeCounter, nodes.Length, "All nodes added");
}
public void CreateXDocumentMixNoArrayNotConnected()
{
XNode[] nodes = { new XProcessingInstruction("PI", "data"), new XComment("comm1"), new XElement("root", new XAttribute("id", "a1")), new XComment("comm2") };
var doc = new XDocument(nodes[0], nodes[1], nodes[2], nodes[3]);
int nodeCounter = 0;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
TestLog.Compare(n == nodes[nodeCounter], "identity");
TestLog.Compare(XNode.DeepEquals(n, nodes[nodeCounter]), "Equals");
TestLog.Compare(n.Document == doc, "Document");
nodeCounter++;
}
TestLog.Compare(nodeCounter, nodes.Length, "All nodes added");
}
public void XDocument2xIEnumerable()
{
XDocument doc1 = null;
var paras = new object[2];
doc1 = new XDocument(new XProcessingInstruction("PI", "data"), new XElement("root"));
var list1 = new List<XNode>();
for (XNode n = doc1.FirstNode; n != null; n = n.NextNode)
{
list1.Add(n);
}
paras[0] = list1;
var list2 = new List<XNode>();
list2.Add(new XProcessingInstruction("PI2", "data"));
list2.Add(new XComment("como"));
paras[1] = list2;
var doc = new XDocument(paras);
IEnumerator ien = (paras[0] as IEnumerable).GetEnumerator();
bool enumerablesSwitched = false;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
if (!ien.MoveNext())
{
ien = (paras[1] as IEnumerable).GetEnumerator();
ien.MoveNext();
enumerablesSwitched = true;
}
var orig = ien.Current as XNode;
TestLog.Compare(XNode.DeepEquals(n, orig), "n.Equals(orig)");
if (!enumerablesSwitched)
{
TestLog.Compare(orig != n, "orig != n");
TestLog.Compare(orig.Document == doc1, "orig Document connected");
TestLog.Compare(n.Document == doc, "node Document connected");
}
else
{
TestLog.Compare(orig == n, "orig == n");
TestLog.Compare(orig.Document == doc, "orig Document NOT connected");
TestLog.Compare(n.Document == doc, "node Document NOT connected");
}
}
}
public void XDocumentAddParams()
{
object[] parameters = null;
var paramType = Variation.Param as string;
switch (paramType)
{
case "XElement":
parameters = new object[] { new XElement("root") };
break;
case "XPI":
parameters = new object[] { new XProcessingInstruction("Click", "data") };
break;
case "XComment":
parameters = new object[] { new XComment("comment") };
break;
case "Whitespace":
parameters = new object[] { new XText(" ") };
break;
case "Mix1":
parameters = new object[] { new XComment("comment"), new XProcessingInstruction("Click", "data"), new XElement("root"), new XProcessingInstruction("Click2", "data2") };
break;
case "Mix2":
parameters = new object[] { new XComment("comment"), new XProcessingInstruction("Click", "data"), new XElement("root"), new XProcessingInstruction("Click2", "data2") };
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
var doc = new XDocument(parameters);
TestLog.Compare(doc != null, "doc!=null");
TestLog.Compare(doc.Document == doc, "doc.Document property");
TestLog.Compare(doc.Parent == null, "doc.Parent property");
int counter = 0;
for (XNode node = doc.FirstNode; node.NextNode != null; node = node.NextNode)
{
TestLog.Compare(node != null, "node != null");
TestLog.Compare(node == parameters[counter], "Node identity");
TestLog.Compare(XNode.DeepEquals(node, parameters[counter] as XNode), "node equals param");
TestLog.Compare(node.Document, doc, "Document property");
counter++;
}
}
//[Variation(Priority = 0, Desc = "XDocument - adding element cloned", Param = "XElement")]
//[Variation(Priority = 1, Desc = "XDocument - adding PI cloned", Param = "XPI")]
//[Variation(Priority = 1, Desc = "XDocument - adding XmlDecl cloned", Param = "XmlDecl")]
//[Variation (Priority=1, Desc="XDocument - adding dot type")]
//[Variation(Priority = 1, Desc = "XDocument - adding Comment cloned", Param = "XComment")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, cloned", Param = "Mix1")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, without decl; cloned", Param = "Mix2")]
//[Variation(Priority = 2, Desc = "XDocument - adding string/whitespace", Param = "Whitespace")]
public void XDocumentAddParamsCloning()
{
object[] paras = null;
var paramType = Variation.Param as string;
var doc1 = new XDocument();
switch (paramType)
{
case "XElement":
var xe = new XElement("root");
doc1.Add(xe);
paras = new object[] { xe };
break;
case "XPI":
var pi = new XProcessingInstruction("Click", "data");
doc1.Add(pi);
paras = new object[] { pi };
break;
case "XComment":
var comm = new XComment("comment");
doc1.Add(comm);
paras = new object[] { comm };
break;
case "Whitespace":
var txt = new XText(" ");
doc1.Add(txt);
paras = new object[] { txt };
break;
case "Mix1":
{
var a2 = new XComment("comment");
doc1.Add(a2);
var a3 = new XProcessingInstruction("Click", "data");
doc1.Add(a3);
var a4 = new XElement("root");
doc1.Add(a4);
var a5 = new XProcessingInstruction("Click2", "data2");
doc1.Add(a5);
paras = new object[] { a2, a3, a4, a5 };
}
break;
case "Mix2":
{
var a2 = new XComment("comment");
doc1.Add(a2);
var a3 = new XProcessingInstruction("Click", "data");
doc1.Add(a3);
var a4 = new XElement("root");
doc1.Add(a4);
var a5 = new XProcessingInstruction("Click2", "data2");
doc1.Add(a5);
paras = new object[] { a2, a3, a4, a5 };
}
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
var doc = new XDocument(paras);
TestLog.Compare(doc != null, "doc!=null");
TestLog.Compare(doc.Document == doc, "doc.Document property");
int counter = 0;
for (XNode node = doc.FirstNode; node.NextNode != null; node = node.NextNode)
{
TestLog.Compare(node != null, "node != null");
var orig = paras[counter] as XNode;
TestLog.Compare(node != orig, "Not the same instance, cloned");
TestLog.Compare(orig.Document, doc1, "Orig Document");
TestLog.Compare(XNode.DeepEquals(node, orig), "node equals param");
TestLog.Compare(node.Document, doc, "Document property");
counter++;
}
}
//[Variation(Priority = 0, Desc = "XDocument - params no array")]
//[Variation(Priority = 1, Desc = "XDocument - Invalid case - attribute node", Param = "Attribute")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - XDocument node", Param = "Document")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Mix with attribute", Param = "MixAttr")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Double root element", Param = "DoubleRoot")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Double XmlDecl", Param = "DoubleDecl")]
//[Variation(Priority = 1, Desc = "XDocument - Invalid case - Invalid order ... Decl is not the first", Param = "InvalIdOrder")]
public void XDocumentAddParamsInvalid()
{
object[] paras = null;
var paramType = Variation.Param as string;
switch (paramType)
{
case "Attribute":
paras = new object[] { new XAttribute("mu", "hu") };
break;
case "Document":
paras = new object[] { new XDocument(), new XProcessingInstruction("Click", "data") };
break;
case "MixAttr":
paras = new object[] { new XElement("aloha"), new XProcessingInstruction("PI", "data"), new XAttribute("id", "a") };
break;
case "DoubleRoot":
paras = new object[] { new XElement("first"), new XElement("Second") };
break;
case "DoubleDocType":
paras = new object[] { new XDocumentType("root", "", "", ""), new XDocumentType("root", "", "", "") };
break;
case "InvalidOrder":
paras = new object[] { new XElement("first"), new XDocumentType("root", "", "", "") };
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
XDocument doc = null;
try
{
doc = new XDocument(paras);
TestLog.Compare(false, "Should throw exception");
}
catch (ArgumentException)
{
TestLog.Compare(doc == null, "Should be null if exception appears");
return;
}
throw new TestException(TestResult.Failed, "");
}
public void XDocumentIEnumerable()
{
var connected = (bool)Variation.Param;
XDocument doc1 = null;
object[] paras = null;
if (connected)
{
doc1 = new XDocument(
new XProcessingInstruction("PI", "data"), new XElement("root"));
var list = new List<XNode>();
for (XNode n = doc1.FirstNode; n != null; n = n.NextNode)
{
list.Add(n);
}
paras = new object[] { list };
}
else
{
var list = new List<XNode>();
list.Add(new XProcessingInstruction("PI", "data"));
list.Add(new XElement("root"));
paras = new object[] { list };
}
var doc = new XDocument(paras);
IEnumerator ien = (paras[0] as IEnumerable).GetEnumerator();
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
ien.MoveNext();
var orig = ien.Current as XNode;
TestLog.Compare(XNode.DeepEquals(n, orig), "XNode.DeepEquals(n,orig)");
if (connected)
{
TestLog.Compare(orig != n, "orig != n");
TestLog.Compare(orig.Document == doc1, "orig Document connected");
TestLog.Compare(n.Document == doc, "node Document connected");
}
else
{
TestLog.Compare(orig == n, "orig == n");
TestLog.Compare(orig.Document == doc, "orig Document NOT connected");
TestLog.Compare(n.Document == doc, "node Document NOT connected");
}
}
TestLog.Compare(!ien.MoveNext(), "enumerator should be exhausted");
}
//[Variation(Priority = 1, Desc = "XDocument - Invalid case with clone - double root - sanity")]
public void XDocumentInvalidCloneSanity()
{
var doc1 = new XDocument(new XElement("root", new XElement("A"), new XElement("B")));
string origXml = doc1.ToString(SaveOptions.DisableFormatting);
var paras = new object[] { doc1.Root.Element("A"), doc1.Root.Element("B") };
XDocument doc = null;
try
{
doc = new XDocument(paras);
TestLog.Compare(false, "should throw");
}
catch (Exception)
{
foreach (object o in paras)
{
var e = o as XElement;
TestLog.Compare(e.Parent, doc1.Root, "Orig Parent");
TestLog.Compare(e.Document, doc1, "Orig Document");
}
TestLog.Compare(doc1.ToString(SaveOptions.DisableFormatting), origXml, "Orig XML");
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 1, Desc = "XDocument - the same node instance, connected - sanity", Param = true)]
//[Variation(Priority = 1, Desc = "XDocument - the same node instance - sanity", Param = false)]
public void XDocumentTheSameReferenceSanity()
{
object[] paras = null;
var connected = (bool)Variation.Param;
XDocument doc1 = null;
if (connected)
{
doc1 = new XDocument(new XElement("root", new XElement("A"), new XProcessingInstruction("PI", "data")));
paras = new object[] { doc1.Root.LastNode, doc1.Root.LastNode, doc1.Root.Element("A") };
}
else
{
var e = new XElement("A");
var pi = new XProcessingInstruction("PI", "data");
paras = new object[] { pi, pi, e };
}
var doc = new XDocument(paras);
XNode firstPI = doc.FirstNode;
XNode secondPI = firstPI.NextNode;
XNode rootElem = secondPI.NextNode;
TestLog.Compare(firstPI != null, "firstPI != null");
TestLog.Compare(firstPI.NodeType, XmlNodeType.ProcessingInstruction, "firstPI nodetype");
TestLog.Compare(firstPI is XProcessingInstruction, "firstPI is XPI");
TestLog.Compare(secondPI != null, "secondPI != null");
TestLog.Compare(secondPI.NodeType, XmlNodeType.ProcessingInstruction, "secondPI nodetype");
TestLog.Compare(secondPI is XProcessingInstruction, "secondPI is XPI");
TestLog.Compare(rootElem != null, "rootElem != null");
TestLog.Compare(rootElem.NodeType, XmlNodeType.Element, "rootElem nodetype");
TestLog.Compare(rootElem is XElement, "rootElem is XElement");
TestLog.Compare(rootElem.NextNode == null, "rootElem NextNode");
TestLog.Compare(firstPI != secondPI, "firstPI != secondPI");
TestLog.Compare(XNode.DeepEquals(firstPI, secondPI), "XNode.DeepEquals(firstPI,secondPI)");
foreach (object o in paras)
{
var e = o as XNode;
if (connected)
{
TestLog.Compare(e.Parent, doc1.Root, "Orig Parent");
TestLog.Compare(e.Document, doc1, "Orig Document");
}
else
{
TestLog.Compare(e.Parent == null, "Orig Parent not connected");
TestLog.Compare(e.Document, doc, "Orig Document not connected");
}
}
}
#endregion
}
}
| |
namespace Projections
{
partial class GeoidPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label1 = new System.Windows.Forms.Label();
this.m_geoidFileNameTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.m_threadSafeCheckBox = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.m_dateTimeTextBox = new System.Windows.Forms.TextBox();
this.m_descriptionTextBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.m_equatorialRadiusTextBox = new System.Windows.Forms.TextBox();
this.m_flatteningTtextBox = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.m_northTextBox = new System.Windows.Forms.TextBox();
this.m_southTextBox = new System.Windows.Forms.TextBox();
this.m_eastTextBox = new System.Windows.Forms.TextBox();
this.m_westTextBox = new System.Windows.Forms.TextBox();
this.m_cacheButton = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.m_ellipsoidTextBox = new System.Windows.Forms.TextBox();
this.m_geoidTextBox = new System.Windows.Forms.TextBox();
this.m_convertEllipsodButton = new System.Windows.Forms.Button();
this.m_convertGeoidButton = new System.Windows.Forms.Button();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.m_latitudeTextBox = new System.Windows.Forms.TextBox();
this.m_longitudeTextBox = new System.Windows.Forms.TextBox();
this.m_toolTip = new System.Windows.Forms.ToolTip(this.components);
this.m_heightButton = new System.Windows.Forms.Button();
this.m_validateButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(54, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Geoid File";
//
// m_geoidFileNameTextBox
//
this.m_geoidFileNameTextBox.Location = new System.Drawing.Point(9, 21);
this.m_geoidFileNameTextBox.Name = "m_geoidFileNameTextBox";
this.m_geoidFileNameTextBox.Size = new System.Drawing.Size(388, 20);
this.m_geoidFileNameTextBox.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(404, 20);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(25, 23);
this.button1.TabIndex = 2;
this.button1.Text = "...";
this.m_toolTip.SetToolTip(this.button1, "Select Geoid File");
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.OnSelectFile);
//
// m_threadSafeCheckBox
//
this.m_threadSafeCheckBox.AutoSize = true;
this.m_threadSafeCheckBox.Location = new System.Drawing.Point(9, 48);
this.m_threadSafeCheckBox.Name = "m_threadSafeCheckBox";
this.m_threadSafeCheckBox.Size = new System.Drawing.Size(85, 17);
this.m_threadSafeCheckBox.TabIndex = 3;
this.m_threadSafeCheckBox.Text = "Thread Safe";
this.m_threadSafeCheckBox.UseVisualStyleBackColor = true;
this.m_threadSafeCheckBox.CheckedChanged += new System.EventHandler(this.OnThreadSafe);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 72);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(58, 13);
this.label2.TabIndex = 4;
this.label2.Text = "Date/Time";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(7, 101);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Description";
//
// m_dateTimeTextBox
//
this.m_dateTimeTextBox.Location = new System.Drawing.Point(80, 68);
this.m_dateTimeTextBox.Name = "m_dateTimeTextBox";
this.m_dateTimeTextBox.ReadOnly = true;
this.m_dateTimeTextBox.Size = new System.Drawing.Size(181, 20);
this.m_dateTimeTextBox.TabIndex = 6;
//
// m_descriptionTextBox
//
this.m_descriptionTextBox.Location = new System.Drawing.Point(80, 97);
this.m_descriptionTextBox.Name = "m_descriptionTextBox";
this.m_descriptionTextBox.ReadOnly = true;
this.m_descriptionTextBox.Size = new System.Drawing.Size(349, 20);
this.m_descriptionTextBox.TabIndex = 7;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(7, 130);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(69, 13);
this.label4.TabIndex = 8;
this.label4.Text = "Equatorial Radius";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(7, 159);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Flattening";
//
// m_equatorialRadiusTextBox
//
this.m_equatorialRadiusTextBox.Location = new System.Drawing.Point(83, 126);
this.m_equatorialRadiusTextBox.Name = "m_equatorialRadiusTextBox";
this.m_equatorialRadiusTextBox.ReadOnly = true;
this.m_equatorialRadiusTextBox.Size = new System.Drawing.Size(126, 20);
this.m_equatorialRadiusTextBox.TabIndex = 10;
//
// m_flatteningTtextBox
//
this.m_flatteningTtextBox.Location = new System.Drawing.Point(83, 155);
this.m_flatteningTtextBox.Name = "m_flatteningTtextBox";
this.m_flatteningTtextBox.ReadOnly = true;
this.m_flatteningTtextBox.Size = new System.Drawing.Size(126, 20);
this.m_flatteningTtextBox.TabIndex = 11;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(442, 12);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(33, 13);
this.label6.TabIndex = 12;
this.label6.Text = "North";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(442, 38);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(35, 13);
this.label7.TabIndex = 13;
this.label7.Text = "South";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(442, 64);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(28, 13);
this.label8.TabIndex = 14;
this.label8.Text = "East";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(442, 90);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(32, 13);
this.label9.TabIndex = 15;
this.label9.Text = "West";
//
// m_northTextBox
//
this.m_northTextBox.Location = new System.Drawing.Point(482, 8);
this.m_northTextBox.Name = "m_northTextBox";
this.m_northTextBox.Size = new System.Drawing.Size(100, 20);
this.m_northTextBox.TabIndex = 16;
//
// m_southTextBox
//
this.m_southTextBox.Location = new System.Drawing.Point(482, 34);
this.m_southTextBox.Name = "m_southTextBox";
this.m_southTextBox.Size = new System.Drawing.Size(100, 20);
this.m_southTextBox.TabIndex = 17;
//
// m_eastTextBox
//
this.m_eastTextBox.Location = new System.Drawing.Point(482, 60);
this.m_eastTextBox.Name = "m_eastTextBox";
this.m_eastTextBox.Size = new System.Drawing.Size(100, 20);
this.m_eastTextBox.TabIndex = 18;
//
// m_westTextBox
//
this.m_westTextBox.Location = new System.Drawing.Point(482, 86);
this.m_westTextBox.Name = "m_westTextBox";
this.m_westTextBox.Size = new System.Drawing.Size(100, 20);
this.m_westTextBox.TabIndex = 19;
//
// m_cacheButton
//
this.m_cacheButton.Location = new System.Drawing.Point(492, 113);
this.m_cacheButton.Name = "m_cacheButton";
this.m_cacheButton.Size = new System.Drawing.Size(75, 23);
this.m_cacheButton.TabIndex = 20;
this.m_cacheButton.Text = "Cache";
this.m_toolTip.SetToolTip(this.m_cacheButton, "Cache Geoid Data");
this.m_cacheButton.UseVisualStyleBackColor = true;
this.m_cacheButton.Click += new System.EventHandler(this.OnCache);
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(606, 63);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(113, 13);
this.label10.TabIndex = 21;
this.label10.Text = "Height Above Ellipsoid";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(754, 63);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(102, 13);
this.label11.TabIndex = 22;
this.label11.Text = "Height above Geoid";
//
// m_ellipsoidTextBox
//
this.m_ellipsoidTextBox.Location = new System.Drawing.Point(596, 85);
this.m_ellipsoidTextBox.Name = "m_ellipsoidTextBox";
this.m_ellipsoidTextBox.Size = new System.Drawing.Size(132, 20);
this.m_ellipsoidTextBox.TabIndex = 23;
//
// m_geoidTextBox
//
this.m_geoidTextBox.Location = new System.Drawing.Point(739, 85);
this.m_geoidTextBox.Name = "m_geoidTextBox";
this.m_geoidTextBox.Size = new System.Drawing.Size(132, 20);
this.m_geoidTextBox.TabIndex = 24;
//
// m_convertEllipsodButton
//
this.m_convertEllipsodButton.Enabled = false;
this.m_convertEllipsodButton.Location = new System.Drawing.Point(625, 109);
this.m_convertEllipsodButton.Name = "m_convertEllipsodButton";
this.m_convertEllipsodButton.Size = new System.Drawing.Size(75, 23);
this.m_convertEllipsodButton.TabIndex = 25;
this.m_convertEllipsodButton.Text = "Convert ->";
this.m_toolTip.SetToolTip(this.m_convertEllipsodButton, "Convert Ellipsod Height to Geoid Height");
this.m_convertEllipsodButton.UseVisualStyleBackColor = true;
this.m_convertEllipsodButton.Click += new System.EventHandler(this.OnConvertEllipsod);
//
// m_convertGeoidButton
//
this.m_convertGeoidButton.Enabled = false;
this.m_convertGeoidButton.Location = new System.Drawing.Point(768, 109);
this.m_convertGeoidButton.Name = "m_convertGeoidButton";
this.m_convertGeoidButton.Size = new System.Drawing.Size(75, 23);
this.m_convertGeoidButton.TabIndex = 26;
this.m_convertGeoidButton.Text = "<- Convert";
this.m_toolTip.SetToolTip(this.m_convertGeoidButton, "Convert Geoid Height to Ellipsoid Height");
this.m_convertGeoidButton.UseVisualStyleBackColor = true;
this.m_convertGeoidButton.Click += new System.EventHandler(this.OnConvertGeoid);
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(593, 12);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(45, 13);
this.label12.TabIndex = 27;
this.label12.Text = "Latitude";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(593, 38);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(54, 13);
this.label13.TabIndex = 28;
this.label13.Text = "Longitude";
//
// m_latitudeTextBox
//
this.m_latitudeTextBox.Location = new System.Drawing.Point(653, 8);
this.m_latitudeTextBox.Name = "m_latitudeTextBox";
this.m_latitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.m_latitudeTextBox.TabIndex = 29;
//
// m_longitudeTextBox
//
this.m_longitudeTextBox.Location = new System.Drawing.Point(653, 34);
this.m_longitudeTextBox.Name = "m_longitudeTextBox";
this.m_longitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.m_longitudeTextBox.TabIndex = 30;
//
// m_heightButton
//
this.m_heightButton.Enabled = false;
this.m_heightButton.Location = new System.Drawing.Point(768, 18);
this.m_heightButton.Name = "m_heightButton";
this.m_heightButton.Size = new System.Drawing.Size(75, 23);
this.m_heightButton.TabIndex = 31;
this.m_heightButton.Text = "Height";
this.m_toolTip.SetToolTip(this.m_heightButton, "Calculate Geoid Height at Longitude/Latitude");
this.m_heightButton.UseVisualStyleBackColor = true;
this.m_heightButton.Click += new System.EventHandler(this.OnHeight);
//
// m_validateButton
//
this.m_validateButton.Enabled = false;
this.m_validateButton.Location = new System.Drawing.Point(638, 148);
this.m_validateButton.Name = "m_validateButton";
this.m_validateButton.Size = new System.Drawing.Size(75, 23);
this.m_validateButton.TabIndex = 32;
this.m_validateButton.Text = "Validate";
this.m_validateButton.UseVisualStyleBackColor = true;
this.m_validateButton.Click += new System.EventHandler(this.OnValidate);
//
// GeoidPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.m_validateButton);
this.Controls.Add(this.m_heightButton);
this.Controls.Add(this.m_longitudeTextBox);
this.Controls.Add(this.m_latitudeTextBox);
this.Controls.Add(this.label13);
this.Controls.Add(this.label12);
this.Controls.Add(this.m_convertGeoidButton);
this.Controls.Add(this.m_convertEllipsodButton);
this.Controls.Add(this.m_geoidTextBox);
this.Controls.Add(this.m_ellipsoidTextBox);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.m_cacheButton);
this.Controls.Add(this.m_westTextBox);
this.Controls.Add(this.m_eastTextBox);
this.Controls.Add(this.m_southTextBox);
this.Controls.Add(this.m_northTextBox);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.m_flatteningTtextBox);
this.Controls.Add(this.m_equatorialRadiusTextBox);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.m_descriptionTextBox);
this.Controls.Add(this.m_dateTimeTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.m_threadSafeCheckBox);
this.Controls.Add(this.button1);
this.Controls.Add(this.m_geoidFileNameTextBox);
this.Controls.Add(this.label1);
this.Name = "GeoidPanel";
this.Size = new System.Drawing.Size(1002, 273);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox m_geoidFileNameTextBox;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.CheckBox m_threadSafeCheckBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox m_dateTimeTextBox;
private System.Windows.Forms.TextBox m_descriptionTextBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox m_equatorialRadiusTextBox;
private System.Windows.Forms.TextBox m_flatteningTtextBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox m_northTextBox;
private System.Windows.Forms.TextBox m_southTextBox;
private System.Windows.Forms.TextBox m_eastTextBox;
private System.Windows.Forms.TextBox m_westTextBox;
private System.Windows.Forms.Button m_cacheButton;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox m_ellipsoidTextBox;
private System.Windows.Forms.TextBox m_geoidTextBox;
private System.Windows.Forms.Button m_convertEllipsodButton;
private System.Windows.Forms.Button m_convertGeoidButton;
private System.Windows.Forms.ToolTip m_toolTip;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.TextBox m_latitudeTextBox;
private System.Windows.Forms.TextBox m_longitudeTextBox;
private System.Windows.Forms.Button m_heightButton;
private System.Windows.Forms.Button m_validateButton;
}
}
| |
#if UNITY_WEBPLAYER || UNITY_WEBGL
#define USE_PLAYER_PREFS
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;
public class PersistentData {
/*
Saves and loads persistent user data in a simple but safer fashion, with more features.
* Uses system file I/O when possible, or PlayerPrefs when running web version
* Uses singleton-ish access (based on ids), no instantiation or references necessary
Advantages over PlayerPrefs:
* Allow defaults when reading
* Also save/load bools, double, long
* Allow byte arrays (as base64 encoded data in PlayerPrefs, normal byte array when using file I/O)
* Allow serializable objects
* No collision of data when using across different objects (using own persistentdata instances)
* faster?
How to:
// Create/get instance
PersistentData pd = PersistentData.getInstance(); // global
PersistentData pd = PersistentData.getInstance("something"); // Custom name
// Read/write:
pd.SetString("name", "dude");
var str = pd.GetString("name");
pd.SetBytes("name", new byte[] {...});
byte[] bytes = pd.GetBytes("name");
pd.SetObject("name", myObject); // myObject must be Serializable
SomeType myObject = pd.GetObject("name") as SomeType;
// Options:
pd.cacheValues = true; // Save primitive values in memory for faster access (default true)
pd.cacheByteArrays = true; // Save byte array values in memory for faster access (default false) (untested)
// Good example of another solution (that tries to replace playerprefs): http://www.previewlabs.com/wp-content/uploads/2014/04/PlayerPrefs.cs
TODO/test:
* More secure/encrypted writing (use StringUtils.encodeRC4 ?)
* Save/load lists? test
* First read may be too slow. Test
* add date time objects?
* Use SystemInfo.deviceUniqueIdentifier.Substring for key? would not allow carrying data over devices though
* Make sure files are deleted on key removal/clear
* Use compression? System.IO.Compression.GZipStream
* Test WebGL, see if it works
*/
// Constant properties
private static Dictionary<string, PersistentData> dataGroups;
private const string SERIALIZATION_SEPARATOR = ",";
private const string FIELD_NAME_KEYS = "keys";
private const string FIELD_NAME_VALUES = "values";
private const string FIELD_NAME_TYPES = "types";
private const string FIELD_NAME_BYTE_ARRAY_KEYS = "byteArrayKeys";
private const string FIELD_TYPE_BOOLEAN = "b";
private const string FIELD_TYPE_FLOAT = "f";
private const string FIELD_TYPE_DOUBLE = "d";
private const string FIELD_TYPE_INT = "i";
private const string FIELD_TYPE_LONG = "l";
private const string FIELD_TYPE_STRING = "s";
private const string FIELD_TYPE_BYTE_ARRAY = "y";
//private static const string FIELD_TYPE_OBJECT = "o"; // Non-primitive
// Properties
private string namePrefix; // Unique prefix for field names
private string _name; // Instance name
private bool _cacheData; // Whether primitives (ints, floats, etc) should be cached
private bool _cacheByteArrays; // Whether serializable objects should be cached
private Hashtable dataToBeWritten; // Data that is waiting to be written: ints, floats, strings, and objects as serialized strings; key, value
private List<string> byteArraysToBeDeleted; // Data that is waiting to be deleted from the system
private Hashtable cachedData; // All items that have been cached
private List<string> dataKeys; // Keys of all ids used
private List<string> byteArrayKeys; // Keys of all byte array ids used
// ================================================================================================================
// STATIC ---------------------------------------------------------------------------------------------------------
static PersistentData() {
dataGroups = new Dictionary<string, PersistentData>();
}
// ================================================================================================================
// CONSTRUCTOR ----------------------------------------------------------------------------------------------------
public PersistentData(string name = "") {
_name = name;
namePrefix = getMD5("p_" + _name) + "_";
_cacheData = true;
_cacheByteArrays = false;
dataToBeWritten = new Hashtable();
byteArraysToBeDeleted = new List<String>();
cachedData = new Hashtable();
PersistentData.addInstance(this);
dataKeys = loadStringList(FIELD_NAME_KEYS);
byteArrayKeys = loadStringList(FIELD_NAME_BYTE_ARRAY_KEYS);
}
public void Debug_Log() {
// Temp!
Debug.Log("Primitive keys ==> (" + dataKeys.Count + ") " + string.Join(",", dataKeys.ToArray()));
Debug.Log("Byte array keys ==> (" + byteArrayKeys.Count + ") " + string.Join(",", byteArrayKeys.ToArray()));
//foreach (var item in dataKeys) Debug.Log(" [" + item + "]");
foreach (var key in byteArrayKeys) Debug.Log(" [" + key + "] = " + System.Text.Encoding.UTF8.GetString(GetBytes(key)));
}
// ================================================================================================================
// STATIC INTERFACE -----------------------------------------------------------------------------------------------
private static void addInstance(PersistentData dataGroup) {
dataGroups.Add(dataGroup.name, dataGroup);
}
public static PersistentData getInstance(string name = "") {
if (dataGroups.ContainsKey(name)) return dataGroups[name];
// Doesn't exist, create a new one and return it
return new PersistentData(name);
}
// ================================================================================================================
// PUBLIC INTERFACE -----------------------------------------------------------------------------------------------
// Get
public bool GetBool(string key, bool defaultValue = false) {
return dataKeys.Contains(key) ? getValue<bool>(key) : defaultValue;
}
public int GetInt(string key, int defaultValue = 0) {
return dataKeys.Contains(key) ? getValue<int>(key) : defaultValue;
}
public long GetLong(string key, long defaultValue = 0) {
return dataKeys.Contains(key) ? getValue<long>(key) : defaultValue;
}
public float GetFloat(string key, float defaultValue = 0.0f) {
return dataKeys.Contains(key) ? getValue<float>(key) : defaultValue;
}
public double GetDouble(string key, double defaultValue = 0.0) {
return dataKeys.Contains(key) ? getValue<double>(key) : defaultValue;
}
public string GetString(string key, string defaultValue = "") {
return dataKeys.Contains(key) ? getValue<string>(key) : defaultValue;
}
public byte[] GetBytes(string key) {
return byteArrayKeys.Contains(key) ? getValueBytes(key) : null;
}
public T GetObject<T>(string key) {
return byteArrayKeys.Contains(key) ? (T)deserializeObject(getValueBytes(key)) : default(T);
}
// Set
public void SetBool(string key, bool value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetInt(string key, int value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetLong(string key, long value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetFloat(string key, float value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetDouble(string key, double value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetString(string key, string value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetBytes(string key, byte[] value) {
dataToBeWritten[key] = value;
if (_cacheData) cachedData.Remove(key);
}
public void SetObject(string key, object serializableObject) {
SetBytes(key, serializeObject(serializableObject));
}
// Utils
public void Clear() {
dataKeys.Clear();
dataToBeWritten.Clear();
while (byteArrayKeys.Count > 0) {
byteArraysToBeDeleted.Add(byteArrayKeys[0]);
byteArrayKeys.RemoveAt(0);
}
ClearCache();
Save(true);
}
public void ClearCache() {
cachedData.Clear();
}
public void RemoveKey(string key) {
dataKeys.Remove(key);
dataToBeWritten.Remove(key);
cachedData.Remove(key);
if (byteArrayKeys.Contains(key)) {
byteArrayKeys.Remove(key);
byteArraysToBeDeleted.Add(key);
}
}
public bool HasKey(string key) {
return dataKeys.Contains(key) || byteArrayKeys.Contains(key) || dataToBeWritten.Contains(key);
}
public void Save(bool forced = false) {
if (dataToBeWritten.Count > 0 || byteArraysToBeDeleted.Count > 0 || forced) {
// Some fields need to be saved
// Read all existing values
List<string> dataValues = loadStringList(FIELD_NAME_VALUES);
List<string> dataTypes = loadStringList(FIELD_NAME_TYPES);
// Record new values
string fieldKey;
object fieldValue;
string fieldType;
int pos;
IDictionaryEnumerator enumerator = dataToBeWritten.GetEnumerator();
while (enumerator.MoveNext()) {
fieldKey = enumerator.Key.ToString();
fieldValue = enumerator.Value;
fieldType = getFieldType(fieldValue);
//Debug.Log("Saving => [" + fieldValue + "] of type [" + fieldType + "]");
if (fieldType == FIELD_TYPE_BYTE_ARRAY) {
//Debug.Log(" Saving as byte array");
// Byte array
if (!byteArrayKeys.Contains(fieldKey)) {
// Adding a key
byteArrayKeys.Add(fieldKey);
}
setSavedBytes(fieldKey, (byte[])fieldValue);
} else {
//Debug.Log(" Saving as native array");
// Primitive data
if (dataKeys.Contains(fieldKey)) {
// Replacing a key
pos = dataKeys.IndexOf(fieldKey);
dataValues[pos] = Convert.ToString(fieldValue);
dataTypes[pos] = fieldType;
} else {
// Adding a key
dataKeys.Add(fieldKey);
dataValues.Add(Convert.ToString(fieldValue));
dataTypes.Add(fieldType);
}
}
}
dataToBeWritten.Clear();
// Write primitives
StringBuilder builderFieldKeys = new StringBuilder();
StringBuilder builderFieldValues = new StringBuilder();
StringBuilder builderFieldTypes = new StringBuilder();
for (int i = 0; i < dataKeys.Count; i++) {
//Debug.Log("Adding data key [" + i + "] for [" + dataKeys[i] + "]");
if (i > 0) {
builderFieldKeys.Append(SERIALIZATION_SEPARATOR);
builderFieldValues.Append(SERIALIZATION_SEPARATOR);
builderFieldTypes.Append(SERIALIZATION_SEPARATOR);
}
builderFieldKeys.Append(encodeString(dataKeys[i]));
builderFieldValues.Append(encodeString(dataValues[i]));
builderFieldTypes.Append(encodeString(dataTypes[i]));
}
setSavedString(FIELD_NAME_KEYS, builderFieldKeys.ToString());
setSavedString(FIELD_NAME_VALUES, builderFieldValues.ToString());
setSavedString(FIELD_NAME_TYPES, builderFieldTypes.ToString());
// Write byte array keys
StringBuilder builderByteArrayKeys = new StringBuilder();
for (int i = 0; i < byteArrayKeys.Count; i++) {
if (i > 0) {
builderByteArrayKeys.Append(SERIALIZATION_SEPARATOR);
}
builderByteArrayKeys.Append(encodeString(byteArrayKeys[i]));
}
setSavedString(FIELD_NAME_BYTE_ARRAY_KEYS, builderByteArrayKeys.ToString());
// Clears deleted byte arrays
foreach (var key in byteArraysToBeDeleted) {
clearSavedStringsOrBytes(key);
}
byteArraysToBeDeleted.Clear();
}
}
// ================================================================================================================
// ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
public string name {
get { return _name; }
}
public bool cacheData {
get { return _cacheData; }
set {
if (_cacheData != value) {
_cacheData = value;
if (!_cacheData) {
foreach (var key in dataKeys) cachedData.Remove(key);
}
}
}
}
public bool cacheByteArrays {
get { return _cacheByteArrays; }
set {
if (_cacheByteArrays != value) {
_cacheByteArrays = value;
if (!_cacheByteArrays) {
foreach (var key in byteArrayKeys) cachedData.Remove(key);
}
}
}
}
// ================================================================================================================
// INTERNAL INTERFACE ---------------------------------------------------------------------------------------------
private List<string> loadStringList(string fieldName) {
// Loads a string list from a field
var encodedList = getSavedString(fieldName).Split(SERIALIZATION_SEPARATOR.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var decodedList = new List<string>(encodedList.Length);
foreach (string listItem in encodedList) {
decodedList.Add(decodeString(listItem));
}
//Debug.Log("Reading field [" + fieldName + "]; value as encoded = [" + getSavedString(fieldName) + "] with [" + encodedList.Length + "] items");
return decodedList;
}
/*
private string loadStringListItem(string fieldName, int pos) {
// Load just one position from the string list
var encodedList = getSavedString(fieldName).Split(SERIALIZATION_SEPARATOR.ToCharArray(), pos + 1);
Debug.Log("Reading field [" + fieldName + "] at position[" + pos + "]; value as encoded = [" + getSavedString(fieldName) + "] with [" + encodedList.Length + "] items");
return decodeString(encodedList[pos]);
}
*/
private byte[] serializeObject(object serializableObject) {
// Returns a serializable object as a byte array
using (var memoryStream = new MemoryStream()) {
var formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, serializableObject);
memoryStream.Flush();
memoryStream.Position = 0;
return memoryStream.ToArray();
}
}
private object deserializeObject(byte[] source) {
// Creates a serializable object from a byte array
using (var memoryStream = new MemoryStream(source)) {
var formatter = new BinaryFormatter();
memoryStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(memoryStream);
}
}
private string getKeyForName(string name) {
// Return a field name that is specific to this instance
return namePrefix + name.Replace(".", "_").Replace("/", "_").Replace("\\", "_");
}
private T getValue<T>(string key) {
// Returns the value of a given primitive field, cast to the required type
// If waiting to be saved, return it
if (dataToBeWritten.ContainsKey(key)) return (T)dataToBeWritten[key];
// If already cached, return it
if (_cacheData && cachedData.ContainsKey(key)) return (T)cachedData[key];
// Read previously saved data
var pos = dataKeys.IndexOf(key);
var fieldType = loadStringList(FIELD_NAME_TYPES)[pos];
T value = (T)getValueAsType(loadStringList(FIELD_NAME_VALUES)[pos], fieldType);
// Save to cache
if (_cacheData) cachedData[key] = value;
return value;
}
private byte[] getValueBytes(string key) {
// Returns the value of a given byte[] field
// If waiting to be saved, return it
if (dataToBeWritten.ContainsKey(key)) return (byte[])dataToBeWritten[key];
// If already cached, return it
if (_cacheData && cachedData.ContainsKey(key)) return (byte[])cachedData[key];
// Read previously saved data
byte[] value = getSavedBytes(key);
// Save to cache
if (_cacheByteArrays) cachedData[key] = value;
return value;
}
private string getMD5(string src) {
// Basic MD5 for short-ish name uniqueness
// Source: http://wiki.unity3d.com/index.php?title=MD5
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(src);
// Encrypt
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++) {
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
private string encodeString(string src) {
return src.Replace("\\", "\\\\").Replace(SERIALIZATION_SEPARATOR, "\\" + SERIALIZATION_SEPARATOR);
}
private string decodeString(string src) {
return src.Replace("\\" + SERIALIZATION_SEPARATOR, SERIALIZATION_SEPARATOR).Replace("\\\\", "\\");
}
private object getValueAsType(string fieldValue, string fieldType) {
if (fieldType == FIELD_TYPE_BOOLEAN) return Convert.ToBoolean(fieldValue);
if (fieldType == FIELD_TYPE_INT) return Convert.ToInt32(fieldValue);
if (fieldType == FIELD_TYPE_LONG) return Convert.ToInt64(fieldValue);
if (fieldType == FIELD_TYPE_FLOAT) return Convert.ToSingle(fieldValue);
if (fieldType == FIELD_TYPE_DOUBLE) return Convert.ToDouble(fieldValue);
if (fieldType == FIELD_TYPE_STRING) return (object)fieldValue.ToString();
//if (fieldType == FIELD_TYPE_BYTE_ARRAY) return (object)fieldValue.ToString();
//if (fieldType == FIELD_TYPE_OBJECT) return (object)fieldValue.ToString();
Debug.LogError("Unsupported type for conversion: [" + fieldType + "]");
return null;
}
private string getFieldType(object value) {
var realFieldType = value.GetType().ToString();
// TODO: use "is" ?
if (realFieldType == "System.Boolean") return FIELD_TYPE_BOOLEAN;
if (realFieldType == "System.Int32") return FIELD_TYPE_INT;
if (realFieldType == "System.Int64") return FIELD_TYPE_LONG;
if (realFieldType == "System.Single") return FIELD_TYPE_FLOAT;
if (realFieldType == "System.Double") return FIELD_TYPE_DOUBLE;
if (realFieldType == "System.String") return FIELD_TYPE_STRING;
if (realFieldType == "System.Byte[]") return FIELD_TYPE_BYTE_ARRAY;
return null;
}
private void clearSavedStringsOrBytes(string name) {
// Removes a byte array or string that has been saved previously
// Save a string to some persistent data system
#if USE_PLAYER_PREFS
// Using PlayerPrefs
PlayerPrefs.DeleteKey(getKeyForName(name));
#else
// Using a file
deleteFile(getKeyForName(name));
#endif
}
private byte[] getSavedBytes(string name) {
// Reads a byte array that has been saved previously
#if USE_PLAYER_PREFS
// Using PlayerPrefs
return Convert.FromBase64String(PlayerPrefs.GetString(getKeyForName(name)));
#else
// Using a file
return loadFileAsBytes(getKeyForName(name));
#endif
}
private void setSavedBytes(string name, byte[] value) {
// Save a string to some persistent data system
#if USE_PLAYER_PREFS
// Using PlayerPrefs
PlayerPrefs.SetString(getKeyForName(name), Convert.ToBase64String(value));
#else
// Using a file
saveBytesToFile(getKeyForName(name), value);
#endif
}
private string getSavedString(string name) {
// Reads a string that has been saved previously
#if USE_PLAYER_PREFS
// Using PlayerPrefs
return PlayerPrefs.GetString(getKeyForName(name));
#else
// Using a file
return loadFileAsString(getKeyForName(name));
#endif
}
private void setSavedString(string name, string value) {
// Save a string to some persistent data system
#if USE_PLAYER_PREFS
// Using PlayerPrefs
PlayerPrefs.SetString(getKeyForName(name), value);
#else
// Using a file
saveStringToFile(getKeyForName(name), value);
#endif
}
private void deleteFile(string filename) {
File.Delete(Application.persistentDataPath + "/" + filename);
}
private void saveStringToFile(string filename, string content) {
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/" + filename);
formatter.Serialize(file, content);
file.Close();
}
private void saveBytesToFile(string filename, byte[] content) {
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/" + filename);
formatter.Serialize(file, content);
file.Close();
}
private string loadFileAsString(string filename) {
object obj = loadFileAsObject(filename);
return obj == null ? "" : (string) obj;
}
private byte[] loadFileAsBytes(string filename) {
object obj = loadFileAsObject(filename);
return obj == null ? null : (byte[]) obj;
}
private object loadFileAsObject(string filename) {
string filePath = Application.persistentDataPath + "/" + filename;
if (File.Exists(filePath)) {
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Open(filePath, FileMode.Open);
object content = formatter.Deserialize(file);
file.Close();
return content;
}
return null;
}
}
| |
namespace AjTalk.Language
{
using System;
using System.Collections.Generic;
using System.Text;
using AjTalk.Compiler;
public class Block : IBlock
{
private byte[] bytecodes;
private short nextbytecode;
private List<object> constants = new List<object>();
private List<string> argnames = new List<string>();
private List<string> localnames = new List<string>();
private List<string> globalnames = new List<string>();
private string sourcecode;
private Block outer;
private ExecutionContext closure;
public Block()
{
}
public Block(string sourcecode)
: this(sourcecode, null)
{
}
public Block(string sourcecode, Block outer)
{
this.sourcecode = sourcecode;
this.outer = outer;
}
public string SourceCode { get { return this.sourcecode; } }
public int Arity { get { return this.argnames.Count; } }
public byte[] Bytecodes { get { return this.bytecodes; } }
public virtual bool IsMethod { get { return false; } }
public ICollection<string> ParameterNames { get { return this.argnames; } }
public ICollection<string> LocalNames { get { return this.localnames; } }
public ExecutionContext Closure { get { return this.closure; } }
public ExecutionContext TopClosure
{
get
{
if (this.closure == null)
return null;
var value = this.closure.Block.TopClosure;
if (value == null)
return this.closure;
return value;
}
}
public Block OuterBlock { get { return this.outer; } }
public IObject Receiver
{
get
{
if (this.Closure == null)
return null;
return this.Closure.Receiver;
}
}
public byte[] ByteCodes { get { return this.bytecodes; } }
public int NoLocals
{
get
{
if (this.localnames == null)
{
return 0;
}
return this.localnames.Count;
}
}
public int NoConstants
{
get
{
if (this.constants == null)
{
return 0;
}
return this.constants.Count;
}
}
public int NoGlobalNames
{
get
{
if (this.globalnames == null)
return 0;
return this.globalnames.Count;
}
}
public static byte MessageArity(string msgname)
{
if (!Char.IsLetter(msgname[0]))
return 1;
int p = msgname.IndexOf(':');
if (p < 0)
return 0;
byte n = 0;
foreach (char ch in msgname)
if (ch == ':')
n++;
return n;
}
public Block Clone(ExecutionContext closure)
{
Block newblock = (Block)this.MemberwiseClone();
newblock.closure = closure;
return newblock;
}
public void CompileArgument(string argname)
{
if (this.argnames.Contains(argname))
{
throw new Exception("Repeated Argument: " + argname);
}
this.argnames.Add(argname);
}
public void CompileLocal(string localname)
{
if (this.localnames.Contains(localname))
{
throw new Exception("Repeated Local: " + localname);
}
this.localnames.Add(localname);
}
public byte CompileConstant(object obj)
{
int p = this.constants.IndexOf(obj);
if (p >= 0)
{
return (byte)p;
}
this.constants.Add(obj);
return (byte)(this.constants.Count - 1);
}
public byte CompileGlobal(string globalname)
{
int p = this.globalnames.IndexOf(globalname);
if (p >= 0)
{
return (byte)p;
}
this.globalnames.Add(globalname);
return (byte)(this.globalnames.Count - 1);
}
public void CompileGetConstant(object obj)
{
this.CompileByteCode(ByteCode.GetConstant, this.CompileConstant(obj));
}
public void CompileGetBlock(object obj)
{
this.CompileByteCode(ByteCode.GetBlock, this.CompileConstant(obj));
}
public void CompileByteCode(ByteCode b)
{
this.CompileByte((byte)b);
}
public void CompileByteCodeAt(ByteCode b, int position)
{
this.bytecodes[position] = (byte)b;
}
public void CompileJumpByteCode(ByteCode b, short jump)
{
this.CompileByte((byte)b);
this.CompileByte((byte)(jump >> 8));
this.CompileByte((byte)(jump & 0xff));
}
public void CompileJumpByteCodeAt(ByteCode b, short jump, int position)
{
this.bytecodes[position] = (byte)b;
this.bytecodes[position + 1] = (byte)(jump >> 8);
this.bytecodes[position + 2] = (byte)(jump & 0xff);
}
public void CompileBlockJumpByteCodeAt(ByteCode b, short jump, int position)
{
this.bytecodes[position] = (byte)ByteCode.Value;
this.bytecodes[position + 1] = (byte)b;
this.bytecodes[position + 2] = (byte)(jump >> 8);
this.bytecodes[position + 3] = (byte)(jump & 0xff);
}
public void CompileInsert(int position, int count)
{
byte[] aux = new byte[this.bytecodes.Length + count];
Array.Copy(this.bytecodes, aux, position);
Array.Copy(this.bytecodes, position, aux, position + count, this.bytecodes.Length - position);
this.bytecodes = aux;
this.nextbytecode += (short)count;
}
public void CompileByteCode(ByteCode b, byte arg)
{
this.CompileByteCode(b);
this.CompileByte(arg);
}
public void CompileByteCode(ByteCode b, byte arg1, byte arg2)
{
this.CompileByteCode(b);
this.CompileByte(arg1);
this.CompileByte(arg2);
}
public void CompileInvokeDotNet(string msgname)
{
msgname = msgname.Substring(1);
int p = msgname.IndexOf(':');
string mthname;
if (p >= 0)
{
string rest = msgname.Substring(p + 1);
if (string.IsNullOrEmpty(rest) || rest.StartsWith("with:"))
mthname = msgname.Substring(0, p);
else
mthname = msgname.Replace(":", string.Empty);
}
else
{
mthname = msgname;
}
if (mthname == "new")
{
this.CompileByteCode(ByteCode.NewDotNetObject, MessageArity(msgname));
}
else
{
this.CompileByteCode(ByteCode.InvokeDotNetMethod, this.CompileConstant(mthname), MessageArity(msgname));
}
}
public void CompileSend(string msgname)
{
if (msgname[0] == Lexer.SpecialDotNetInvokeMark)
{
this.CompileInvokeDotNet(msgname);
return;
}
if (msgname == "basicInstSize")
this.CompileByteCode(ByteCode.BasicInstSize);
else if (msgname == "basicInstVarAt:")
this.CompileByteCode(ByteCode.BasicInstVarAt);
else if (msgname == "basicInstVarAt:put:")
this.CompileByteCode(ByteCode.BasicInstVarAtPut);
else if (msgname == "basicNew")
this.CompileByteCode(ByteCode.NewObject);
else if (msgname == "basicSize")
this.CompileByteCode(ByteCode.BasicSize);
else if (msgname == "basicAt:")
this.CompileByteCode(ByteCode.BasicAt);
else if (msgname == "basicAt:put:")
this.CompileByteCode(ByteCode.BasicAtPut);
else if (msgname == "value")
this.CompileByteCode(ByteCode.Value);
else if (msgname.StartsWith("value:") && IsValueMessage(msgname))
this.CompileByteCode(ByteCode.MultiValue, MessageArity(msgname));
else if (msgname == "class")
this.CompileByteCode(ByteCode.GetClass);
else if (msgname == "raise")
this.CompileByteCode(ByteCode.RaiseException);
else
this.CompileByteCode(ByteCode.Send, this.CompileConstant(msgname), MessageArity(msgname));
}
public void CompileBinarySend(string msgname)
{
this.CompileByteCode(ByteCode.Send, this.CompileConstant(msgname), 1);
}
public ExecutionContext CreateContext(Machine machine, object[] args)
{
return new ExecutionContext(machine, this.Receiver, this, args);
}
// TODO how to implements super, sender
public virtual object Execute(Machine machine, object[] args)
{
return new Interpreter(this.CreateContext(machine, args)).Execute();
}
public virtual object ExecuteInInterpreter(Interpreter interpreter, object[] args)
{
interpreter.PushContext(this.CreateContext(interpreter.Machine, args));
return interpreter;
}
public virtual void CompileGet(string name)
{
if (this.TryCompileGet(name))
{
return;
}
this.CompileByteCode(ByteCode.GetGlobalVariable, this.CompileGlobal(name));
}
public virtual void CompileGetDotNetType(string name)
{
this.CompileByteCode(ByteCode.GetDotNetType, this.CompileGlobal(name));
}
public virtual void CompileSet(string name)
{
if (this.TryCompileSet(name))
{
return;
}
this.CompileByteCode(ByteCode.SetGlobalVariable, this.CompileGlobal(name));
}
public object GetConstant(int nc)
{
return this.constants[nc];
}
public string GetGlobalName(int ng)
{
return this.globalnames[ng];
}
public string GetLocalName(int nl)
{
return this.localnames[nl];
}
public string GetArgumentName(int na)
{
return this.argnames[na];
}
public virtual string GetInstanceVariableName(int n)
{
if (this.outer != null)
return this.outer.GetInstanceVariableName(n);
throw new NotSupportedException();
}
public virtual string GetClassVariableName(int n)
{
if (this.outer != null)
return this.outer.GetClassVariableName(n);
throw new NotSupportedException();
}
public virtual int GetInstanceVariableOffset(string name)
{
if (this.outer != null)
return this.outer.GetInstanceVariableOffset(name);
return -1;
}
protected virtual bool TryCompileGet(string name)
{
if (name.Equals("false"))
{
this.CompileGetConstant(false);
return true;
}
if (name.Equals("true"))
{
this.CompileGetConstant(true);
return true;
}
if (name[0] == Lexer.SpecialDotNetTypeMark)
{
this.CompileGetDotNetType(name.Substring(1));
return true;
}
if (name == "self")
{
this.CompileByteCode(ByteCode.GetSelf);
return true;
}
if (name == "super")
{
this.CompileByteCode(ByteCode.GetSuper);
return true;
}
if (name == "nil" || name == "null")
{
this.CompileByteCode(ByteCode.GetNil);
return true;
}
int p;
if (this.localnames != null)
{
p = this.localnames.IndexOf(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.GetLocal, (byte)p);
return true;
}
}
if (this.argnames != null)
{
p = this.argnames.IndexOf(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.GetArgument, (byte)p);
return true;
}
}
p = this.GetInstanceVariableOffset(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.GetInstanceVariable, (byte)p);
return true;
}
return false;
}
protected virtual bool TryCompileSet(string name)
{
int p;
if (this.localnames != null)
{
p = this.localnames.IndexOf(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.SetLocal, (byte)p);
return true;
}
}
if (this.argnames != null)
{
p = this.argnames.IndexOf(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.SetArgument, (byte)p);
return true;
}
}
p = this.GetInstanceVariableOffset(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.SetInstanceVariable, (byte)p);
return true;
}
return false;
}
private static bool IsValueMessage(string msgname)
{
if (msgname == "value:")
return true;
if (msgname.StartsWith("value:"))
return IsValueMessage(msgname.Substring(6));
return false;
}
private void CompileByte(byte b)
{
if (this.bytecodes == null)
{
this.bytecodes = new byte[] { b };
this.nextbytecode = 1;
return;
}
if (this.nextbytecode >= this.bytecodes.Length)
{
byte[] aux = new byte[this.bytecodes.Length + 1];
Array.Copy(this.bytecodes, aux, this.bytecodes.Length);
this.bytecodes = aux;
}
this.bytecodes[this.nextbytecode++] = b;
}
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Batch.Tests.Helpers;
using Microsoft.Azure.Management.Batch;
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Azure.Batch.Tests
{
public class InMemoryAccountTests
{
[Fact]
public void AccountCreateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.Create(null, "bar", new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", null, new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("foo", "bar", null));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("invalid+", "account", new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "invalid%", new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "/invalid", new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "s", new BatchAccountCreateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Create("rg", "account_name_that_is_too_long", new BatchAccountCreateParameters()));
}
[Fact]
public void AccountCreateAsyncValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var okResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse });
var client = BatchTestHelper.GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = Task.Factory.StartNew(() => client.BatchAccount.CreateWithHttpMessagesAsync(
"foo",
"acctName",
new BatchAccountCreateParameters
{
Location = "South Central US",
Tags = tags
})).Unwrap().GetAwaiter().GetResult();
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Put, handler.Requests[0].Method);
Assert.NotNull(handler.Requests[0].Headers.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Body.Location);
Assert.NotEmpty(result.Body.AccountEndpoint);
Assert.Equal(ProvisioningState.Succeeded, result.Body.ProvisioningState);
Assert.Equal(2, result.Body.Tags.Count);
}
[Fact]
public void CreateAccountWithAutoStorageAsyncValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var utcNow = DateTime.UtcNow;
var okResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'autoStorage' :{
'storageAccountId' : '//storageAccount1',
'lastKeySync': '" + utcNow.ToString("o") + @"',
}
},
}")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { okResponse });
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = client.BatchAccount.Create("resourceGroupName", "acctName", new BatchAccountCreateParameters
{
Location = "South Central US",
AutoStorage = new AutoStorageBaseProperties()
{
StorageAccountId = "//storageAccount1"
}
});
// Validate result
Assert.Equal("//storageAccount1", result.AutoStorage.StorageAccountId);
Assert.Equal(utcNow, result.AutoStorage.LastKeySync);
}
[Fact]
public void AccountUpdateWithAutoStorageValidateMessage()
{
var utcNow = DateTime.UtcNow;
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'autoStorage' : {
'storageAccountId' : '//StorageAccountId',
'lastKeySync': '" + utcNow.ToString("o") + @"',
}
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(response);
var client = BatchTestHelper.GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.BatchAccount.Update("foo", "acctName", new BatchAccountUpdateParameters
{
Tags = tags,
});
// Validate headers - User-Agent for certs, Authorization for tokens
//Assert.Equal(HttpMethod.Patch, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Location);
Assert.NotEmpty(result.AccountEndpoint);
Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState);
Assert.Equal("//StorageAccountId", result.AutoStorage.StorageAccountId);
Assert.Equal(utcNow, result.AutoStorage.LastKeySync);
Assert.Equal(2, result.Tags.Count);
}
[Fact]
public void AccountCreateSyncValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(response);
var client = BatchTestHelper.GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.BatchAccount.Create("foo", "acctName", new BatchAccountCreateParameters("westus")
{
Tags = tags,
AutoStorage = new AutoStorageBaseProperties()
{
StorageAccountId = "//storageAccount1"
}
});
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Location);
Assert.NotEmpty(result.AccountEndpoint);
Assert.Equal(result.ProvisioningState, ProvisioningState.Succeeded);
Assert.Equal(2, result.Tags.Count);
}
[Fact]
public void AccountUpdateValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(response);
var client = BatchTestHelper.GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.BatchAccount.Update("foo", "acctName", new BatchAccountUpdateParameters
{
Tags = tags,
AutoStorage = new AutoStorageBaseProperties()
{
StorageAccountId = "//StorageAccountId"
}
});
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Location);
Assert.NotEmpty(result.AccountEndpoint);
Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState);
Assert.Equal(2, result.Tags.Count);
}
[Fact]
public void AccountUpdateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.Update(null, null, new BatchAccountUpdateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", null, new BatchAccountUpdateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Update("foo", "bar", null));
Assert.Throws<ValidationException>(() => client.BatchAccount.Update("invalid+", "account", new BatchAccountUpdateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "invalid%", new BatchAccountUpdateParameters()));
Assert.Throws<ValidationException>(() => client.BatchAccount.Update("rg", "/invalid", new BatchAccountUpdateParameters()));
}
[Fact]
public void AccountDeleteValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var okResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse });
var client = BatchTestHelper.GetBatchManagementClient(handler);
client.BatchAccount.Delete("resGroup", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
}
[Fact]
public void AccountDeleteNotFoundValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(@"")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, notFoundResponse });
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = Assert.Throws<CloudException>(() => Task.Factory.StartNew(() =>
client.BatchAccount.DeleteWithHttpMessagesAsync(
"resGroup",
"acctName")).Unwrap().GetAwaiter().GetResult());
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
Assert.Equal(HttpStatusCode.NotFound, result.Response.StatusCode);
}
[Fact]
public void AccountDeleteNoContentValidateMessage()
{
var noContentResponse = new HttpResponseMessage(HttpStatusCode.NoContent)
{
Content = new StringContent(@"")
};
noContentResponse.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(noContentResponse);
var client = BatchTestHelper.GetBatchManagementClient(handler);
client.BatchAccount.Delete("resGroup", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
}
[Fact]
public void AccountDeleteThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("foo", null));
Assert.Throws<ValidationException>(() => client.BatchAccount.Delete(null, "bar"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("invalid+", "account"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "invalid%"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Delete("rg", "/invalid"));
}
[Fact]
public void AccountGetValidateResponse()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = client.BatchAccount.Get("foo", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Location);
Assert.Equal("acctName", result.Name);
Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Id);
Assert.NotEmpty(result.AccountEndpoint);
Assert.Equal(20, result.CoreQuota);
Assert.Equal(100, result.PoolQuota);
Assert.Equal(200, result.ActiveJobAndJobScheduleQuota);
Assert.True(result.Tags.ContainsKey("tag1"));
}
[Fact]
public void AccountGetThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.Get("foo", null));
Assert.Throws<ValidationException>(() => client.BatchAccount.Get(null, "bar"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Get("invalid+", "account"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "invalid%"));
Assert.Throws<ValidationException>(() => client.BatchAccount.Get("rg", "/invalid"));
}
[Fact]
public void AccountListValidateMessage()
{
var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : ''
}")
};
var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack'
}
")
};
var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack'
}
")
};
allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1");
allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1");
allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1");
// all accounts under sub and empty next link
var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK };
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = Task.Factory.StartNew(() => client.BatchAccount.ListWithHttpMessagesAsync())
.Unwrap()
.GetAwaiter()
.GetResult();
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode);
// Validate result
Assert.Equal(2, result.Body.Count());
var account1 = result.Body.ElementAt(0);
var account2 = result.Body.ElementAt(1);
Assert.Equal("West US", account1.Location);
Assert.Equal("acctName", account1.Name);
Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", account1.Id);
Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1", account2.Id);
Assert.NotEmpty(account1.AccountEndpoint);
Assert.Equal(20, account1.CoreQuota);
Assert.Equal(100, account1.PoolQuota);
Assert.Equal(200, account2.ActiveJobAndJobScheduleQuota);
Assert.True(account1.Tags.ContainsKey("tag1"));
// all accounts under sub and a non-empty nextLink
handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK };
client = BatchTestHelper.GetBatchManagementClient(handler);
var result1 = client.BatchAccount.List();
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// all accounts under sub with a non-empty nextLink response
handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1) { StatusCodeToReturn = HttpStatusCode.OK };
client = BatchTestHelper.GetBatchManagementClient(handler);
result1 = client.BatchAccount.ListNext(result1.NextPageLink);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
}
[Fact]
public void AccountListByResourceGroupValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Failed',
'coreQuota' : '10',
'poolQuota' : '50',
'activeJobAndJobScheduleQuota' : '100'
},
'tags' : {
'tag1' : 'value for tag1'
}
}
],
'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack'
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = client.BatchAccount.List();
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal(2, result.Count());
var account1 = result.ElementAt(0);
var account2 = result.ElementAt(1);
Assert.Equal("West US", account1.Location);
Assert.Equal("acctName", account1.Name);
Assert.Equal( @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", account1.Id);
Assert.Equal(@"http://acctName.batch.core.windows.net/", account1.AccountEndpoint);
Assert.Equal(ProvisioningState.Succeeded, account1.ProvisioningState);
Assert.Equal(20, account1.CoreQuota);
Assert.Equal(100, account1.PoolQuota);
Assert.Equal(200, account1.ActiveJobAndJobScheduleQuota);
Assert.Equal("South Central US", account2.Location);
Assert.Equal("acctName1", account2.Name);
Assert.Equal(@"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1", account2.Id);
Assert.Equal(@"http://acctName1.batch.core.windows.net/", account2.AccountEndpoint);
Assert.Equal(ProvisioningState.Failed, account2.ProvisioningState);
Assert.Equal(10, account2.CoreQuota);
Assert.Equal(50, account2.PoolQuota);
Assert.Equal(100, account2.ActiveJobAndJobScheduleQuota);
Assert.Equal(2, account1.Tags.Count);
Assert.True(account1.Tags.ContainsKey("tag2"));
Assert.Equal(1, account2.Tags.Count);
Assert.True(account2.Tags.ContainsKey("tag1"));
Assert.Equal(@"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack", result.NextPageLink);
}
[Fact]
public void AccountListNextThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.BatchAccount.ListNext(null));
}
[Fact]
public void AccountKeysListValidateMessage()
{
var primaryKeyString = "primary key string which is alot longer than this";
var secondaryKeyString = "secondary key string which is alot longer than this";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'primary' : 'primary key string which is alot longer than this',
'secondary' : 'secondary key string which is alot longer than this',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = client.BatchAccount.GetKeys("foo", "acctName");
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.NotEmpty(result.Primary);
Assert.Equal(primaryKeyString, result.Primary);
Assert.NotEmpty(result.Secondary);
Assert.Equal(secondaryKeyString, result.Secondary);
}
[Fact]
public void AccountKeysListThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys("foo", null));
Assert.Throws<ValidationException>(() => client.BatchAccount.GetKeys(null, "bar"));
}
[Fact]
public void AccountKeysRegenerateValidateMessage()
{
var primaryKeyString = "primary key string which is alot longer than this";
var secondaryKeyString = "secondary key string which is alot longer than this";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'primary' : 'primary key string which is alot longer than this',
'secondary' : 'secondary key string which is alot longer than this',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = BatchTestHelper.GetBatchManagementClient(handler);
var result = client.BatchAccount.RegenerateKey(
"foo",
"acctName",
AccountKeyType.Primary);
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.NotEmpty(result.Primary);
Assert.Equal(primaryKeyString, result.Primary);
Assert.NotEmpty(result.Secondary);
Assert.Equal(secondaryKeyString, result.Secondary);
}
[Fact]
public void AccountKeysRegenerateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = BatchTestHelper.GetBatchManagementClient(handler);
Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey(null, "bar", AccountKeyType.Primary));
Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("foo", null, AccountKeyType.Primary));
Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("invalid+", "account", AccountKeyType.Primary));
Assert.Throws<ValidationException>(() => client.BatchAccount.RegenerateKey("rg", "invalid%", AccountKeyType.Primary));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RangeBasedReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
internal abstract class RangeBasedReader : TransferReaderWriterBase
{
/// <summary>
/// Minimum size of empty range, the empty ranges which is smaller than this size will be merged to the adjacent range with data.
/// </summary>
const int MinimumNoDataRangeSize = 8 * 1024;
private volatile State state;
private TransferJob transferJob;
private CountdownEvent getRangesCountDownEvent;
private CountdownEvent toDownloadItemsCountdownEvent;
private int getRangesSpanIndex = 0;
private List<Utils.RangesSpan> rangesSpanList;
private List<Utils.Range> rangeList;
private int nextDownloadIndex = 0;
private long lastTransferOffset;
private TransferDownloadBuffer currentDownloadBuffer = null;
private volatile bool hasWork;
public RangeBasedReader(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.transferJob = this.SharedTransferData.TransferJob;
this.Location = this.transferJob.Source;
this.hasWork = true;
}
private enum State
{
FetchAttributes,
GetRanges,
Download,
Error,
Finished
};
public override async Task DoWorkInternalAsync()
{
try
{
switch (this.state)
{
case State.FetchAttributes:
await this.FetchAttributesAsync();
break;
case State.GetRanges:
await this.GetRangesAsync();
break;
case State.Download:
await this.DownloadRangeAsync();
break;
default:
break;
}
}
catch
{
this.state = State.Error;
throw;
}
}
public override bool HasWork
{
get
{
return this.hasWork;
}
}
public override bool IsFinished
{
get
{
return State.Error == this.state || State.Finished == this.state;
}
}
protected TransferLocation Location
{
get;
private set;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.getRangesCountDownEvent)
{
this.getRangesCountDownEvent.Dispose();
this.getRangesCountDownEvent = null;
}
if (null != this.toDownloadItemsCountdownEvent)
{
this.toDownloadItemsCountdownEvent.Dispose();
this.toDownloadItemsCountdownEvent = null;
}
}
}
private async Task FetchAttributesAsync()
{
Debug.Assert(
this.state == State.FetchAttributes,
"FetchAttributesAsync called, but state isn't FetchAttributes");
this.hasWork = false;
this.NotifyStarting();
try
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.DoFetchAttributesAsync(),
this.CancellationToken);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception ex) when (ex is StorageException || (ex is AggregateException && ex.InnerException is StorageException))
{
var e = ex as StorageException ?? ex.InnerException as StorageException;
#else
catch (StorageException e)
{
#endif
// Getting a storage exception is expected if the blob doesn't
// exist. For those cases that indicate the blob doesn't exist
// we will set a specific error state.
if (null != e.RequestInformation &&
e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Resources.SourceBlobDoesNotExistException, e);
}
else
{
throw;
}
}
if (this.Location.Type == TransferLocationType.AzureBlob)
{
(this.Location as AzureBlobLocation).CheckedAccessCondition = true;
}
else if (this.Location.Type == TransferLocationType.AzureFile)
{
(this.Location as AzureFileLocation).CheckedAccessCondition = true;
}
this.Controller.CheckCancellation();
this.state = State.GetRanges;
this.PrepareToGetRanges();
if (!this.rangesSpanList.Any())
{
// InitDownloadInfo will set hasWork.
this.InitDownloadInfo();
this.PreProcessed = true;
return;
}
this.PreProcessed = true;
this.hasWork = true;
}
private async Task GetRangesAsync()
{
Debug.Assert(
(this.state == State.GetRanges) || (this.state == State.Error),
"GetRangesAsync called, but state isn't GetRanges or Error");
this.hasWork = false;
this.lastTransferOffset = this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset;
int spanIndex = Interlocked.Increment(ref this.getRangesSpanIndex);
this.hasWork = spanIndex < (this.rangesSpanList.Count - 1);
Utils.RangesSpan rangesSpan = this.rangesSpanList[spanIndex];
rangesSpan.Ranges = await this.DoGetRangesAsync(rangesSpan);
List<Utils.Range> ranges = new List<Utils.Range>();
Utils.Range currentRange = null;
long currentStartOffset = rangesSpan.StartOffset;
foreach (var range in rangesSpan.Ranges)
{
long emptySize = range.StartOffset - currentStartOffset;
if (emptySize > 0 && emptySize < MinimumNoDataRangeSize)
{
// There is empty range which size is smaller than MinimumNoDataRangeSize
// merge it to the adjacent data range.
if (null == currentRange)
{
currentRange = new Utils.Range()
{
StartOffset = currentStartOffset,
EndOffset = range.EndOffset,
HasData = range.HasData
};
}
else
{
currentRange.EndOffset = range.EndOffset;
}
}
else
{
// Empty range size is larger than MinimumNoDataRangeSize
// put current data range in list and start to deal with the next data range.
if (null != currentRange)
{
ranges.Add(currentRange);
}
currentRange = new Utils.Range
{
StartOffset = range.StartOffset,
EndOffset = range.EndOffset,
HasData = range.HasData
};
}
currentStartOffset = range.EndOffset + 1;
}
if (null != currentRange)
{
ranges.Add(currentRange);
}
rangesSpan.Ranges = ranges;
if (this.getRangesCountDownEvent.Signal())
{
this.ArrangeRanges();
// Don't call CallFinish here, InitDownloadInfo will call it.
this.InitDownloadInfo();
}
}
private async Task DownloadRangeAsync()
{
Debug.Assert(
this.state == State.Error || this.state == State.Download,
"DownloadRangeAsync called, but state isn't Download or Error");
this.hasWork = false;
if (State.Error == this.state)
{
// Some thread has set error message, just return here.
return;
}
if (this.nextDownloadIndex < this.rangeList.Count)
{
Utils.Range rangeData = this.rangeList[this.nextDownloadIndex];
int blockSize = this.SharedTransferData.BlockSize;
long blockStartOffset = (rangeData.StartOffset / blockSize) * blockSize;
long nextBlockStartOffset = Math.Min(blockStartOffset + blockSize, this.SharedTransferData.TotalLength);
TransferDownloadStream downloadStream = null;
if ((rangeData.StartOffset > blockStartOffset) && (rangeData.EndOffset < nextBlockStartOffset))
{
Debug.Assert(null != this.currentDownloadBuffer, "Download buffer should have been allocated when range start offset is not block size aligned");
downloadStream = new TransferDownloadStream(this.Scheduler.MemoryManager, this.currentDownloadBuffer, (int)(rangeData.StartOffset - blockStartOffset), (int)(rangeData.EndOffset + 1 - rangeData.StartOffset));
}
else
{
// Attempt to reserve memory. If none available we'll
// retry some time later.
byte[][] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffers(this.SharedTransferData.MemoryChunksRequiredEachTime);
if (null == memoryBuffer)
{
this.SetRangeDownloadHasWork();
return;
}
if (rangeData.EndOffset >= this.lastTransferOffset)
{
bool canRead = true;
lock (this.transferJob.CheckPoint.TransferWindowLock)
{
if (this.transferJob.CheckPoint.TransferWindow.Count >= Constants.MaxCountInTransferWindow)
{
canRead = false;
}
else
{
if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.transferJob.CheckPoint.TransferWindow.Add(this.transferJob.CheckPoint.EntryTransferOffset);
this.transferJob.CheckPoint.EntryTransferOffset = Math.Min(this.transferJob.CheckPoint.EntryTransferOffset + blockSize, this.SharedTransferData.TotalLength);
}
}
}
if (!canRead)
{
this.Scheduler.MemoryManager.ReleaseBuffers(memoryBuffer);
this.SetRangeDownloadHasWork();
return;
}
}
if (rangeData.StartOffset == blockStartOffset)
{
this.currentDownloadBuffer = new TransferDownloadBuffer(blockStartOffset, (int)Math.Min(blockSize, this.SharedTransferData.TotalLength - blockStartOffset), memoryBuffer);
downloadStream = new TransferDownloadStream(this.Scheduler.MemoryManager, this.currentDownloadBuffer, 0, (int)(rangeData.EndOffset + 1 - rangeData.StartOffset));
}
else
{
Debug.Assert(null != this.currentDownloadBuffer, "Download buffer should have been allocated when range start offset is not block size aligned");
TransferDownloadBuffer nextBuffer = new TransferDownloadBuffer(nextBlockStartOffset, (int)Math.Min(blockSize, this.SharedTransferData.TotalLength - nextBlockStartOffset), memoryBuffer);
downloadStream = new TransferDownloadStream(
this.Scheduler.MemoryManager,
this.currentDownloadBuffer,
(int)(rangeData.StartOffset - blockStartOffset),
(int)(nextBlockStartOffset - rangeData.StartOffset),
nextBuffer,
0,
(int)(rangeData.EndOffset + 1 - nextBlockStartOffset));
this.currentDownloadBuffer = nextBuffer;
}
}
using (downloadStream)
{
this.nextDownloadIndex++;
this.SetRangeDownloadHasWork();
RangeBasedDownloadState rangeBasedDownloadState = new RangeBasedDownloadState
{
Range = rangeData,
DownloadStream = downloadStream
};
await this.DownloadRangeAsync(rangeBasedDownloadState);
}
this.SetChunkFinish();
return;
}
this.SetRangeDownloadHasWork();
}
private void SetRangeDownloadHasWork()
{
if (this.HasWork)
{
return;
}
// Check if we have ranges available to download.
if (this.nextDownloadIndex < this.rangeList.Count)
{
this.hasWork = true;
return;
}
}
private async Task DownloadRangeAsync(RangeBasedDownloadState asyncState)
{
Debug.Assert(null != asyncState, "asyncState object expected");
Debug.Assert(
this.state == State.Download || this.state == State.Error,
"DownloadRangeAsync called, but state isn't Download or Error");
// If a parallel operation caused the controller to be placed in
// error state exit early to avoid unnecessary I/O.
if (this.state == State.Error)
{
return;
}
if (asyncState.Range.HasData)
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.DoDownloadRangeToStreamAsync(asyncState),
this.CancellationToken);
}
else
{
// Zero memory buffer.
asyncState.DownloadStream.SetAllZero();
}
asyncState.DownloadStream.FinishWrite();
asyncState.DownloadStream.ReserveBuffer = true;
foreach (var buffer in asyncState.DownloadStream.GetBuffers())
{
// Two download streams can refer to the same download buffer instance. It may cause the download
// buffer be added into shared transfer data twice if only buffer.Finished is checked here:
// Thread A: FinishedWrite()
// Thread B: FinishedWrite(), buffer.Finished is true now
// Thread A: Check buffer.Finished
// Thread B: Check buffer.Finished
// Thread A: Add buffer into sharedTransferData
// Thread C: Writer remove buffer from sharedTransferData
// Thread B: Add buffer into sharedTransferData again
// So call MarkAsProcessed to make sure buffer is added exactly once.
if (buffer.Finished && buffer.MarkAsProcessed())
{
TransferData transferData = new TransferData(this.Scheduler.MemoryManager)
{
StartOffset = buffer.StartOffset,
Length = buffer.Length,
MemoryBuffer = buffer.MemoryBuffer
};
this.SharedTransferData.AvailableData.TryAdd(buffer.StartOffset, transferData);
}
}
}
/// <summary>
/// It might fail to get large ranges list from storage. This method is to split the whole file to spans of 148MB to get ranges.
/// In restartable, we only need to get ranges for chunks in TransferWindow and after TransferEntryOffset in check point.
/// In TransferWindow, there might be some chunks adjacent to TransferEntryOffset, so this method will first merge these chunks into TransferEntryOffset;
/// Then in remained chunks in the TransferWindow, it's very possible that ranges of several chunks can be got in one 148MB span.
/// To avoid sending too many get ranges requests, this method will merge the chunks to 148MB spans.
/// </summary>
private void PrepareToGetRanges()
{
this.getRangesSpanIndex = -1;
this.rangesSpanList = new List<Utils.RangesSpan>();
this.rangeList = new List<Utils.Range>();
this.nextDownloadIndex = 0;
SingleObjectCheckpoint checkpoint = this.transferJob.CheckPoint;
int blockSize = this.SharedTransferData.BlockSize;
Utils.RangesSpan rangesSpan = null;
if ((null != checkpoint.TransferWindow)
&& (checkpoint.TransferWindow.Any()))
{
checkpoint.TransferWindow.Sort();
long lastOffset = 0;
if (checkpoint.EntryTransferOffset == this.SharedTransferData.TotalLength)
{
long lengthBeforeLastChunk = checkpoint.EntryTransferOffset % blockSize;
lastOffset = 0 == lengthBeforeLastChunk ?
checkpoint.EntryTransferOffset - blockSize :
checkpoint.EntryTransferOffset - lengthBeforeLastChunk;
}
else
{
lastOffset = checkpoint.EntryTransferOffset - blockSize;
}
for (int i = checkpoint.TransferWindow.Count - 1; i >= 0; i--)
{
if (lastOffset == checkpoint.TransferWindow[i])
{
checkpoint.TransferWindow.RemoveAt(i);
checkpoint.EntryTransferOffset = lastOffset;
}
else if (lastOffset < checkpoint.TransferWindow[i])
{
throw new FormatException(Resources.RestartableInfoCorruptedException);
}
else
{
break;
}
lastOffset = checkpoint.EntryTransferOffset - blockSize;
}
if (this.transferJob.CheckPoint.TransferWindow.Any())
{
rangesSpan = new Utils.RangesSpan();
rangesSpan.StartOffset = checkpoint.TransferWindow[0];
rangesSpan.EndOffset = Math.Min(rangesSpan.StartOffset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1;
for (int i = 1; i < checkpoint.TransferWindow.Count; ++i )
{
if (checkpoint.TransferWindow[i] + blockSize > rangesSpan.EndOffset)
{
long lastEndOffset = rangesSpan.EndOffset;
this.rangesSpanList.Add(rangesSpan);
rangesSpan = new Utils.RangesSpan();
rangesSpan.StartOffset = checkpoint.TransferWindow[i] > lastEndOffset ? checkpoint.TransferWindow[i] : lastEndOffset + 1;
rangesSpan.EndOffset = Math.Min(rangesSpan.StartOffset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1;
}
}
this.rangesSpanList.Add(rangesSpan);
}
}
long offset = null != rangesSpan ?
rangesSpan.EndOffset > checkpoint.EntryTransferOffset ?
rangesSpan.EndOffset + 1 :
checkpoint.EntryTransferOffset :
checkpoint.EntryTransferOffset;
while (offset < this.SharedTransferData.TotalLength)
{
rangesSpan = new Utils.RangesSpan()
{
StartOffset = offset,
EndOffset = Math.Min(offset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1
};
this.rangesSpanList.Add(rangesSpan);
offset = rangesSpan.EndOffset + 1;
}
if (!this.rangesSpanList.Any())
{
return;
}
else if (this.rangesSpanList.Count == 1)
{
if (this.rangesSpanList[0].EndOffset - this.rangesSpanList[0].StartOffset < blockSize)
{
this.rangeList.Add(new Utils.Range()
{
StartOffset = this.rangesSpanList[0].StartOffset,
EndOffset = this.rangesSpanList[0].EndOffset,
HasData = true
});
this.rangesSpanList.Clear();
return;
}
}
this.getRangesCountDownEvent = new CountdownEvent(this.rangesSpanList.Count);
}
private void ClearForGetRanges()
{
this.rangesSpanList = null;
if (null != this.getRangesCountDownEvent)
{
this.getRangesCountDownEvent.Dispose();
this.getRangesCountDownEvent = null;
}
}
/// <summary>
/// Turn raw ranges get from Azure Storage in rangesSpanList
/// into list of Range.
/// </summary>
private void ArrangeRanges()
{
long currentEndOffset = -1;
// 1st RangesSpan (148MB)
IEnumerator<Utils.RangesSpan> enumerator = this.rangesSpanList.GetEnumerator();
bool hasValue = enumerator.MoveNext();
bool reachLastTransferOffset = false;
int lastTransferWindowIndex = 0;
Utils.RangesSpan current;
Utils.RangesSpan next;
if (hasValue)
{
// 1st 148MB
current = enumerator.Current;
while (hasValue)
{
hasValue = enumerator.MoveNext();
// 1st 148MB doesn't have any data
if (!current.Ranges.Any())
{
// 2nd 148MB
current = enumerator.Current;
continue;
}
if (hasValue)
{
// 2nd 148MB
next = enumerator.Current;
Debug.Assert(
current.EndOffset < this.transferJob.CheckPoint.EntryTransferOffset
|| ((current.EndOffset + 1) == next.StartOffset),
"Something wrong with ranges list.");
// Both 1st 148MB & 2nd 148MB has data
if (next.Ranges.Any())
{
// They are connected, merge the range
if ((current.Ranges.Last().EndOffset + 1) == next.Ranges.First().StartOffset)
{
Utils.Range mergedRange = new Utils.Range()
{
StartOffset = current.Ranges.Last().StartOffset,
EndOffset = next.Ranges.First().EndOffset,
HasData = true
};
// Remove the last range in 1st 148MB and first range in 2nd 148MB
current.Ranges.RemoveAt(current.Ranges.Count - 1);
next.Ranges.RemoveAt(0);
// Add the merged range to 1st *148MB* (not 148MB anymore)
current.Ranges.Add(mergedRange);
current.EndOffset = mergedRange.EndOffset;
next.StartOffset = mergedRange.EndOffset + 1;
if (next.EndOffset == mergedRange.EndOffset)
{
continue;
}
}
}
}
foreach (Utils.Range range in current.Ranges)
{
// Check if we have a gap before the current range.
// If so we'll generate a range with HasData = false.
if (currentEndOffset != range.StartOffset - 1)
{
// Add empty ranges based on gaps
this.AddRangesByCheckPoint(
currentEndOffset + 1,
range.StartOffset - 1,
false,
ref reachLastTransferOffset,
ref lastTransferWindowIndex);
}
this.AddRangesByCheckPoint(
range.StartOffset,
range.EndOffset,
true,
ref reachLastTransferOffset,
ref lastTransferWindowIndex);
currentEndOffset = range.EndOffset;
}
current = enumerator.Current;
}
}
if (currentEndOffset < this.SharedTransferData.TotalLength - 1)
{
this.AddRangesByCheckPoint(
currentEndOffset + 1,
this.SharedTransferData.TotalLength - 1,
false,
ref reachLastTransferOffset,
ref lastTransferWindowIndex);
}
}
private void AddRangesByCheckPoint(long startOffset, long endOffset, bool hasData, ref bool reachLastTransferOffset, ref int lastTransferWindowIndex)
{
SingleObjectCheckpoint checkpoint = this.transferJob.CheckPoint;
if (reachLastTransferOffset)
{
this.rangeList.AddRange(
new Utils.Range
{
StartOffset = startOffset,
EndOffset = endOffset,
HasData = hasData,
}.SplitRanges(Constants.DefaultTransferChunkSize));
}
else
{
Utils.Range range = new Utils.Range()
{
StartOffset = -1,
HasData = hasData
};
while (lastTransferWindowIndex < checkpoint.TransferWindow.Count)
{
long lastTransferWindowStart = checkpoint.TransferWindow[lastTransferWindowIndex];
long lastTransferWindowEnd = Math.Min(checkpoint.TransferWindow[lastTransferWindowIndex] + this.SharedTransferData.BlockSize - 1, this.SharedTransferData.TotalLength);
if (lastTransferWindowStart <= endOffset)
{
if (-1 == range.StartOffset)
{
// New range
range.StartOffset = Math.Max(lastTransferWindowStart, startOffset);
range.EndOffset = Math.Min(lastTransferWindowEnd, endOffset);
}
else
{
if (range.EndOffset != lastTransferWindowStart - 1)
{
// Store the previous range and create a new one
this.rangeList.AddRange(range.SplitRanges(Constants.DefaultTransferChunkSize));
range = new Utils.Range()
{
StartOffset = Math.Max(lastTransferWindowStart, startOffset),
HasData = hasData
};
}
range.EndOffset = Math.Min(lastTransferWindowEnd, endOffset);
}
if (range.EndOffset == lastTransferWindowEnd)
{
// Reach the end of transfer window, move to next
++lastTransferWindowIndex;
continue;
}
}
break;
}
if (-1 != range.StartOffset)
{
this.rangeList.AddRange(range.SplitRanges(Constants.DefaultTransferChunkSize));
}
if (checkpoint.EntryTransferOffset <= endOffset + 1)
{
reachLastTransferOffset = true;
if (checkpoint.EntryTransferOffset <= endOffset)
{
this.rangeList.AddRange(new Utils.Range()
{
StartOffset = checkpoint.EntryTransferOffset,
EndOffset = endOffset,
HasData = hasData,
}.SplitRanges(Constants.DefaultTransferChunkSize));
}
}
}
}
/// <summary>
/// To initialize range based object download related information in the controller.
/// This method will call CallFinish.
/// </summary>
private void InitDownloadInfo()
{
this.ClearForGetRanges();
this.state = State.Download;
if (this.rangeList.Count == this.nextDownloadIndex)
{
this.toDownloadItemsCountdownEvent = new CountdownEvent(1);
this.SetChunkFinish();
}
else
{
this.toDownloadItemsCountdownEvent = new CountdownEvent(this.rangeList.Count);
this.hasWork = true;
}
}
private void SetChunkFinish()
{
if (this.toDownloadItemsCountdownEvent.Signal())
{
this.state = State.Finished;
this.hasWork = false;
}
}
protected class RangeBasedDownloadState
{
private Utils.Range range;
public Utils.Range Range
{
get
{
return this.range;
}
set
{
this.range = value;
this.StartOffset = value.StartOffset;
this.Length = (int)(value.EndOffset - value.StartOffset + 1);
}
}
/// <summary>
/// Gets or sets a handle to the memory buffer to ensure the
/// memory buffer remains in memory during the entire operation.
/// </summary>
public TransferDownloadStream DownloadStream
{
get;
set;
}
/// <summary>
/// Gets or sets the starting offset of this part of data.
/// </summary>
public long StartOffset
{
get;
set;
}
/// <summary>
/// Gets or sets the length of this part of data.
/// </summary>
public int Length
{
get;
set;
}
}
protected abstract Task DoFetchAttributesAsync();
protected abstract Task DoDownloadRangeToStreamAsync(RangeBasedDownloadState asyncState);
protected abstract Task<List<Utils.Range>> DoGetRangesAsync(Utils.RangesSpan rangesSpan);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Claims
{
public partial class Claim
{
public Claim(System.IO.BinaryReader reader) { }
public Claim(System.IO.BinaryReader reader, System.Security.Claims.ClaimsIdentity subject) { }
protected Claim(System.Security.Claims.Claim other) { }
protected Claim(System.Security.Claims.Claim other, System.Security.Claims.ClaimsIdentity subject) { }
public Claim(string type, string value) { }
public Claim(string type, string value, string valueType) { }
public Claim(string type, string value, string valueType, string issuer) { }
public Claim(string type, string value, string valueType, string issuer, string originalIssuer) { }
public Claim(string type, string value, string valueType, string issuer, string originalIssuer, System.Security.Claims.ClaimsIdentity subject) { }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public string Issuer { get { return default(string); } }
public string OriginalIssuer { get { return default(string); } }
public System.Collections.Generic.IDictionary<string, string> Properties { get { return default(System.Collections.Generic.IDictionary<string, string>); } }
public System.Security.Claims.ClaimsIdentity Subject { get { return default(System.Security.Claims.ClaimsIdentity); } }
public string Type { get { return default(string); } }
public string Value { get { return default(string); } }
public string ValueType { get { return default(string); } }
public virtual System.Security.Claims.Claim Clone() { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim Clone(System.Security.Claims.ClaimsIdentity identity) { return default(System.Security.Claims.Claim); }
public override string ToString() { return default(string); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public partial class ClaimsIdentity : System.Security.Principal.IIdentity
{
public const string DefaultIssuer = "LOCAL AUTHORITY";
public const string DefaultNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
public const string DefaultRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
public ClaimsIdentity() { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType) { }
public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { }
public ClaimsIdentity(System.IO.BinaryReader reader) { }
protected ClaimsIdentity(System.Security.Claims.ClaimsIdentity other) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { }
public ClaimsIdentity(string authenticationType) { }
public ClaimsIdentity(string authenticationType, string nameType, string roleType) { }
public System.Security.Claims.ClaimsIdentity Actor { get { return default(System.Security.Claims.ClaimsIdentity); } set { } }
public virtual string AuthenticationType { get { return default(string); } }
public object BootstrapContext { get { return default(object); }[System.Security.SecurityCriticalAttribute]set { } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public virtual bool IsAuthenticated { get { return default(bool); } }
public string Label { get { return default(string); } set { } }
public virtual string Name { get { return default(string); } }
public string NameClaimType { get { return default(string); } }
public string RoleClaimType { get { return default(string); } }
[System.Security.SecurityCriticalAttribute]
public virtual void AddClaim(System.Security.Claims.Claim claim) { }
[System.Security.SecurityCriticalAttribute]
public virtual void AddClaims(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { }
public virtual System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); }
protected virtual System.Security.Claims.Claim CreateClaim(System.IO.BinaryReader reader) { return default(System.Security.Claims.Claim); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); }
public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); }
public virtual bool HasClaim(string type, string value) { return default(bool); }
[System.Security.SecurityCriticalAttribute]
public virtual void RemoveClaim(System.Security.Claims.Claim claim) { }
[System.Security.SecurityCriticalAttribute]
public virtual bool TryRemoveClaim(System.Security.Claims.Claim claim) { return default(bool); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public partial class ClaimsPrincipal : System.Security.Principal.IPrincipal
{
public ClaimsPrincipal() { }
public ClaimsPrincipal(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { }
public ClaimsPrincipal(System.IO.BinaryReader reader) { }
public ClaimsPrincipal(System.Security.Principal.IIdentity identity) { }
public ClaimsPrincipal(System.Security.Principal.IPrincipal principal) { }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
public static System.Func<System.Security.Claims.ClaimsPrincipal> ClaimsPrincipalSelector { get { return default(System.Func<System.Security.Claims.ClaimsPrincipal>); }[System.Security.SecurityCriticalAttribute]set { } }
public static System.Security.Claims.ClaimsPrincipal Current { get { return default(System.Security.Claims.ClaimsPrincipal); } }
protected virtual byte[] CustomSerializationData { get { return default(byte[]); } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> Identities { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>); } }
public virtual System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } }
public static System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity> PrimaryIdentitySelector { get { return default(System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity>); }[System.Security.SecurityCriticalAttribute]set { } }
[System.Security.SecurityCriticalAttribute]
public virtual void AddIdentities(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { }
[System.Security.SecurityCriticalAttribute]
public virtual void AddIdentity(System.Security.Claims.ClaimsIdentity identity) { }
public virtual System.Security.Claims.ClaimsPrincipal Clone() { return default(System.Security.Claims.ClaimsPrincipal); }
protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader) { return default(System.Security.Claims.ClaimsIdentity); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); }
public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); }
public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); }
public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); }
public virtual bool HasClaim(string type, string value) { return default(bool); }
public virtual bool IsInRole(string role) { return default(bool); }
public virtual void WriteTo(System.IO.BinaryWriter writer) { }
protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { }
}
public static partial class ClaimTypes
{
public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor";
public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous";
public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication";
public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant";
public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod";
public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision";
public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath";
public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country";
public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth";
public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid";
public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid";
public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid";
public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup";
public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns";
public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa";
public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration";
public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired";
public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender";
public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname";
public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid";
public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash";
public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone";
public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent";
public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality";
public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone";
public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone";
public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode";
public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid";
public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid";
public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa";
public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber";
public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid";
public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn";
public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince";
public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress";
public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname";
public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system";
public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint";
public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn";
public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri";
public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata";
public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version";
public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage";
public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname";
public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim";
public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup";
public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion";
public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority";
public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim";
public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname";
}
public static partial class ClaimValueTypes
{
public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary";
public const string Base64Octet = "http://www.w3.org/2001/XMLSchema#base64Octet";
public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean";
public const string Date = "http://www.w3.org/2001/XMLSchema#date";
public const string DateTime = "http://www.w3.org/2001/XMLSchema#dateTime";
public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration";
public const string DnsName = "http://schemas.xmlsoap.org/claims/dns";
public const string Double = "http://www.w3.org/2001/XMLSchema#double";
public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue";
public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
public const string Fqbn = "http://www.w3.org/2001/XMLSchema#fqbn";
public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary";
public const string Integer = "http://www.w3.org/2001/XMLSchema#integer";
public const string Integer32 = "http://www.w3.org/2001/XMLSchema#integer32";
public const string Integer64 = "http://www.w3.org/2001/XMLSchema#integer64";
public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo";
public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name";
public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa";
public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue";
public const string Sid = "http://www.w3.org/2001/XMLSchema#sid";
public const string String = "http://www.w3.org/2001/XMLSchema#string";
public const string Time = "http://www.w3.org/2001/XMLSchema#time";
public const string UInteger32 = "http://www.w3.org/2001/XMLSchema#uinteger32";
public const string UInteger64 = "http://www.w3.org/2001/XMLSchema#uinteger64";
public const string UpnName = "http://schemas.xmlsoap.org/claims/UPN";
public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name";
public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration";
}
}
namespace System.Security.Principal
{
public partial class GenericIdentity : System.Security.Claims.ClaimsIdentity
{
protected GenericIdentity(System.Security.Principal.GenericIdentity identity) { }
public GenericIdentity(string name) { }
public GenericIdentity(string name, string type) { }
public override string AuthenticationType { get { return default(string); } }
public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } }
public override bool IsAuthenticated { get { return default(bool); } }
public override string Name { get { return default(string); } }
public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); }
}
public partial class GenericPrincipal : System.Security.Claims.ClaimsPrincipal
{
public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles) { }
public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } }
public override bool IsInRole(string role) { return default(bool); }
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDegradedDataPersistenceRulesSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private DataIsolationLevel? _isolationLevel;
public DataIsolationLevel? IsolationLevel
{
get { return _isolationLevel; }
set { WithIsolationLevel(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private DataPersistenceRuleState? _state;
public DataPersistenceRuleState? State
{
get { return _state; }
set { WithState(value); }
}
private string _storageDomainId;
public string StorageDomainId
{
get { return _storageDomainId; }
set { WithStorageDomainId(value); }
}
private DataPersistenceRuleType? _type;
public DataPersistenceRuleType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithIsolationLevel(DataIsolationLevel? isolationLevel)
{
this._isolationLevel = isolationLevel;
if (isolationLevel != null)
{
this.QueryParams.Add("isolation_level", isolationLevel.ToString());
}
else
{
this.QueryParams.Remove("isolation_level");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithState(DataPersistenceRuleState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
{
this._storageDomainId = storageDomainId.ToString();
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithStorageDomainId(string storageDomainId)
{
this._storageDomainId = storageDomainId;
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId);
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request WithType(DataPersistenceRuleType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetDegradedDataPersistenceRulesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/degraded_data_persistence_rule";
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.CompletionProviders.XmlDocCommentCompletion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Completion.CompletionProviders.XmlDocCommentCompletion
{
[ExportCompletionProvider("DocCommentCompletionProvider", LanguageNames.CSharp)]
internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider
{
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return text[characterPosition] == '<';
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
if (triggerInfo.IsDebugger)
{
return null;
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>();
if (parentTrivia == null)
{
return null;
}
var items = new List<CompletionItem>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var span = CompletionUtilities.GetTextChangeSpan(text, position);
var attachedToken = parentTrivia.ParentTrivia.Token;
if (attachedToken.Kind() == SyntaxKind.None)
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false);
ISymbol declaredSymbol = null;
var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken);
}
else
{
var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>();
if (typeDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
}
}
if (declaredSymbol != null)
{
items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token));
}
if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText ||
(token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) ||
(token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement)))
{
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement)
{
items.AddRange(GetNestedTags(span));
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
var element = (XmlElementSyntax)token.Parent.Parent.Parent;
if (element.StartTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "listheader")
{
items.AddRange(GetListHeaderItems(span));
}
if (token.Parent.Parent is DocumentationCommentTriviaSyntax)
{
items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span));
items.AddRange(GetTopLevelRepeatableItems(span));
}
}
if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag)
{
var startTag = (XmlElementStartTagSyntax)token.Parent;
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "listheader")
{
items.AddRange(GetListHeaderItems(span));
}
}
items.AddRange(GetAlwaysVisibleItems(span));
return items;
}
private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span)
{
var names = new HashSet<string>(new[] { "summary", "remarks", "example", "completionlist" });
RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText);
return names.Select(n => GetItem(n, span));
}
private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector)
{
if (parentTrivia != null)
{
foreach (var node in parentTrivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null)
{
names.Remove(selector(element));
}
}
}
}
private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token)
{
if (symbol is IMethodSymbol)
{
return GetTagsForMethod((IMethodSymbol)symbol, filterSpan, trivia, token);
}
if (symbol is IPropertySymbol)
{
return GetTagsForProperty((IPropertySymbol)symbol, filterSpan, trivia, token);
}
if (symbol is INamedTypeSymbol)
{
return GetTagsForType((INamedTypeSymbol)symbol, filterSpan, trivia);
}
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet();
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam"));
items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this,
filterSpan,
FormatParameter("typeparam", t), GetCompletionItemRules())));
return items;
}
private string AttributeSelector(XmlElementSyntax element, string attribute)
{
if (!element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == "name");
if (nameAttribute != null)
{
if (startTag.Name.LocalName.ValueText == attribute)
{
return nameAttribute.Identifier.Identifier.ValueText;
}
}
}
return null;
}
private IEnumerable<XmlDocCommentCompletionItem> GetTagsForProperty(IPropertySymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token)
{
var items = new List<XmlDocCommentCompletionItem>();
if (symbol.IsIndexer)
{
var parameters = symbol.GetParameters().Select(p => p.Name).ToSet();
// User is trying to write a name, try to suggest only names.
if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) ||
(token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute)))
{
string parentElementName = null;
var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
parentElementName = emptyElement.Name.LocalName.Text;
}
// We're writing the name of a paramref
if (parentElementName == "paramref")
{
items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules())));
}
return items;
}
RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, "param"));
items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("param", p), GetCompletionItemRules())));
}
var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet();
items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, "typeparam", "name", t, GetCompletionItemRules())));
items.Add(new XmlDocCommentCompletionItem(this, filterSpan, "value", GetCompletionItemRules()));
return items;
}
private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token)
{
var items = new List<CompletionItem>();
var parameters = symbol.GetParameters().Select(p => p.Name).ToSet();
var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet();
// User is trying to write a name, try to suggest only names.
if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) ||
(token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute)))
{
string parentElementName = null;
var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
parentElementName = emptyElement.Name.LocalName.Text;
}
// We're writing the name of a paramref or typeparamref
if (parentElementName == "paramref")
{
items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules())));
}
else if (parentElementName == "typeparamref")
{
items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, t, GetCompletionItemRules())));
}
return items;
}
var returns = true;
RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, "param"));
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam"));
foreach (var node in trivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
if (startTag.Name.LocalName.ValueText == "returns")
{
returns = false;
break;
}
}
}
items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("param", p), GetCompletionItemRules())));
items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter("typeparam", t), GetCompletionItemRules())));
if (returns && !symbol.ReturnsVoid)
{
items.Add(new XmlDocCommentCompletionItem(this, filterSpan, "returns", GetCompletionItemRules()));
}
return items;
}
protected override AbstractXmlDocCommentCompletionItemRules GetCompletionItemRules()
{
return XmlDocCommentCompletionItemRules.Instance;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public partial class ZipFileTestBase : FileCleanupTestBase
{
public static string bad(string filename) => Path.Combine("ZipTestData", "badzipfiles", filename);
public static string compat(string filename) => Path.Combine("ZipTestData", "compat", filename);
public static string strange(string filename) => Path.Combine("ZipTestData", "StrangeZipFiles", filename);
public static string zfile(string filename) => Path.Combine("ZipTestData", "refzipfiles", filename);
public static string zfolder(string filename) => Path.Combine("ZipTestData", "refzipfolders", filename);
public static string zmodified(string filename) => Path.Combine("ZipTestData", "modified", filename);
protected TempFile CreateTempCopyFile(string path, string newPath)
{
TempFile newfile = new TempFile(newPath);
File.Copy(path, newPath, overwrite: true);
return newfile;
}
public static long LengthOfUnseekableStream(Stream s)
{
long totalBytes = 0;
const int bufSize = 4096;
byte[] buf = new byte[bufSize];
long bytesRead = 0;
do
{
bytesRead = s.Read(buf, 0, bufSize);
totalBytes += bytesRead;
} while (bytesRead > 0);
return totalBytes;
}
// reads exactly bytesToRead out of stream, unless it is out of bytes
public static void ReadBytes(Stream stream, byte[] buffer, long bytesToRead)
{
int bytesLeftToRead;
if (bytesToRead > int.MaxValue)
{
throw new NotImplementedException("64 bit addresses");
}
else
{
bytesLeftToRead = (int)bytesToRead;
}
int totalBytesRead = 0;
while (bytesLeftToRead > 0)
{
int bytesRead = stream.Read(buffer, totalBytesRead, bytesLeftToRead);
if (bytesRead == 0) throw new IOException("Unexpected end of stream");
totalBytesRead += bytesRead;
bytesLeftToRead -= bytesRead;
}
}
public static bool ArraysEqual<T>(T[] a, T[] b) where T : IComparable<T>
{
if (a.Length != b.Length) return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i].CompareTo(b[i]) != 0) return false;
}
return true;
}
public static bool ArraysEqual<T>(T[] a, T[] b, int length) where T : IComparable<T>
{
for (int i = 0; i < length; i++)
{
if (a[i].CompareTo(b[i]) != 0) return false;
}
return true;
}
public static void StreamsEqual(Stream ast, Stream bst)
{
StreamsEqual(ast, bst, -1);
}
public static void StreamsEqual(Stream ast, Stream bst, int blocksToRead)
{
if (ast.CanSeek)
ast.Seek(0, SeekOrigin.Begin);
if (bst.CanSeek)
bst.Seek(0, SeekOrigin.Begin);
const int bufSize = 4096;
byte[] ad = new byte[bufSize];
byte[] bd = new byte[bufSize];
int ac = 0;
int bc = 0;
int blocksRead = 0;
//assume read doesn't do weird things
do
{
if (blocksToRead != -1 && blocksRead >= blocksToRead)
break;
ac = ast.Read(ad, 0, 4096);
bc = bst.Read(bd, 0, 4096);
if (ac != bc)
{
bd = NormalizeLineEndings(bd);
}
Assert.True(ArraysEqual<byte>(ad, bd, ac), "Stream contents not equal: " + ast.ToString() + ", " + bst.ToString());
blocksRead++;
} while (ac == 4096);
}
public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode)
{
await IsZipSameAsDirAsync(archiveFile, directory, mode, requireExplicit: false, checkTimes: false);
}
public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
{
var s = await StreamHelpers.CreateTempCopyStream(archiveFile);
IsZipSameAsDir(s, directory, mode, requireExplicit, checkTimes);
}
public static byte[] NormalizeLineEndings(byte[] str)
{
string rep = Text.Encoding.Default.GetString(str);
rep = rep.Replace("\r\n", "\n");
rep = rep.Replace("\n", "\r\n");
return Text.Encoding.Default.GetBytes(rep);
}
public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
{
int count = 0;
using (ZipArchive archive = new ZipArchive(archiveFile, mode))
{
List<FileData> files = FileData.InPath(directory);
Assert.All<FileData>(files, (file) => {
count++;
string entryName = file.FullName;
if (file.IsFolder)
entryName += Path.DirectorySeparatorChar;
ZipArchiveEntry entry = archive.GetEntry(entryName);
if (entry == null)
{
entryName = FlipSlashes(entryName);
entry = archive.GetEntry(entryName);
}
if (file.IsFile)
{
Assert.NotNull(entry);
long givenLength = entry.Length;
var buffer = new byte[entry.Length];
using (Stream entrystream = entry.Open())
{
entrystream.Read(buffer, 0, buffer.Length);
#if netcoreapp || uap
uint zipcrc = entry.Crc32;
Assert.Equal(CRC.CalculateCRC(buffer), zipcrc.ToString());
#endif
if (file.Length != givenLength)
{
buffer = NormalizeLineEndings(buffer);
}
Assert.Equal(file.Length, buffer.Length);
string crc = CRC.CalculateCRC(buffer);
Assert.Equal(file.CRC, crc);
}
if (checkTimes)
{
const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records
DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution);
DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution);
Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks);
}
Assert.Equal(file.Name, entry.Name);
Assert.Equal(entryName, entry.FullName);
Assert.Equal(entryName, entry.ToString());
Assert.Equal(archive, entry.Archive);
}
else if (file.IsFolder)
{
if (entry == null) //entry not found
{
string entryNameOtherSlash = FlipSlashes(entryName);
bool isEmtpy = !files.Any(
f => f.IsFile &&
(f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) ||
f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase)));
if (requireExplicit || isEmtpy)
{
Assert.Contains("emptydir", entryName);
}
if ((!requireExplicit && !isEmtpy) || entryName.Contains("emptydir"))
count--; //discount this entry
}
else
{
using (Stream es = entry.Open())
{
try
{
Assert.Equal(0, es.Length);
}
catch (NotSupportedException)
{
try
{
Assert.Equal(-1, es.ReadByte());
}
catch (Exception)
{
Console.WriteLine("Didn't return EOF");
throw;
}
}
}
}
}
});
Assert.Equal(count, archive.Entries.Count);
}
}
private static string FlipSlashes(string name)
{
Debug.Assert(!(name.Contains("\\") && name.Contains("/")));
return
name.Contains("\\") ? name.Replace("\\", "/") :
name.Contains("/") ? name.Replace("/", "\\") :
name;
}
public static void DirsEqual(string actual, string expected)
{
var expectedList = FileData.InPath(expected);
var actualList = Directory.GetFiles(actual, "*.*", SearchOption.AllDirectories);
var actualFolders = Directory.GetDirectories(actual, "*.*", SearchOption.AllDirectories);
var actualCount = actualList.Length + actualFolders.Length;
Assert.Equal(expectedList.Count, actualCount);
ItemEqual(actualList, expectedList, isFile: true);
ItemEqual(actualFolders, expectedList, isFile: false);
}
public static void DirFileNamesEqual(string actual, string expected)
{
IEnumerable<string> actualEntries = Directory.EnumerateFileSystemEntries(actual, "*", SearchOption.AllDirectories);
IEnumerable<string> expectedEntries = Directory.EnumerateFileSystemEntries(expected, "*", SearchOption.AllDirectories);
Assert.True(Enumerable.SequenceEqual(expectedEntries.Select(i => Path.GetFileName(i)), actualEntries.Select(i => Path.GetFileName(i))));
}
private static void ItemEqual(string[] actualList, List<FileData> expectedList, bool isFile)
{
for (int i = 0; i < actualList.Length; i++)
{
var actualFile = actualList[i];
string aEntry = Path.GetFullPath(actualFile);
string aName = Path.GetFileName(aEntry);
var bData = expectedList.Where(f => string.Equals(f.Name, aName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
string bEntry = Path.GetFullPath(Path.Combine(bData.OrigFolder, bData.FullName));
string bName = Path.GetFileName(bEntry);
// expected 'emptydir' folder doesn't exist because MSBuild doesn't copy empty dir
if (!isFile && aName.Contains("emptydir") && bName.Contains("emptydir"))
continue;
//we want it to be false that one of them is a directory and the other isn't
Assert.False(Directory.Exists(aEntry) ^ Directory.Exists(bEntry), "Directory in one is file in other");
//contents same
if (isFile)
{
Stream sa = StreamHelpers.CreateTempCopyStream(aEntry).Result;
Stream sb = StreamHelpers.CreateTempCopyStream(bEntry).Result;
StreamsEqual(sa, sb);
}
}
}
/// <param name="useSpansForWriting">Tests the Span overloads of Write</param>
/// <param name="writeInChunks">Writes in chunks of 5 to test Write with a nonzero offset</param>
public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode, bool useSpansForWriting = false, bool writeInChunks = false)
{
var files = FileData.InPath(directory);
using (ZipArchive archive = new ZipArchive(archiveStream, mode, true))
{
foreach (var i in files)
{
if (i.IsFolder)
{
string entryName = i.FullName;
ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/");
e.LastWriteTime = i.LastModifiedDate;
}
}
foreach (var i in files)
{
if (i.IsFile)
{
string entryName = i.FullName;
var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName));
if (installStream != null)
{
ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/'));
e.LastWriteTime = i.LastModifiedDate;
using (Stream entryStream = e.Open())
{
int bytesRead;
var buffer = new byte[1024];
if (useSpansForWriting)
{
while ((bytesRead = installStream.Read(new Span<byte>(buffer))) != 0)
{
entryStream.Write(new ReadOnlySpan<byte>(buffer, 0, bytesRead));
}
}
else if (writeInChunks)
{
while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
{
for (int k = 0; k < bytesRead; k += 5)
entryStream.Write(buffer, k, Math.Min(5, bytesRead - k));
}
}
else
{
while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
{
entryStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
}
internal static void AddEntry(ZipArchive archive, string name, string contents, DateTimeOffset lastWrite)
{
ZipArchiveEntry e = archive.CreateEntry(name);
e.LastWriteTime = lastWrite;
using (StreamWriter w = new StreamWriter(e.Open()))
{
w.WriteLine(contents);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead>
{
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
protected readonly CompletionCallbackDelegate sendFinishedHandler;
protected readonly CompletionCallbackDelegate readFinishedHandler;
protected readonly CompletionCallbackDelegate halfclosedHandler;
protected readonly object myLock = new object();
protected GCHandle gchandle;
protected CallSafeHandle call;
protected bool disposed;
protected bool started;
protected bool errorOccured;
protected bool cancelRequested;
protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected bool readingDone;
protected bool halfcloseRequested;
protected bool halfclosed;
protected bool finished; // True if close has been received from the peer.
public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer)
{
this.serializer = Preconditions.CheckNotNull(serializer);
this.deserializer = Preconditions.CheckNotNull(deserializer);
this.sendFinishedHandler = CreateBatchCompletionCallback(HandleSendFinished);
this.readFinishedHandler = CreateBatchCompletionCallback(HandleReadFinished);
this.halfclosedHandler = CreateBatchCompletionCallback(HandleHalfclosed);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
public void CancelWithStatus(Status status)
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(CallSafeHandle call)
{
lock (myLock)
{
// Make sure this object and the delegated held by it will not be garbage collected
// before we release this handle.
gchandle = GCHandle.Alloc(this);
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartSendMessageInternal(TWrite msg, AsyncCompletionDelegate<object> completionDelegate)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendMessage(payload, sendFinishedHandler);
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckReadingAllowed();
call.StartReceiveMessage(readFinishedHandler);
readCompletionDelegate = completionDelegate;
}
}
// TODO(jtattermusch): find more fitting name for this method.
/// <summary>
/// Default behavior just completes the read observer, but more sofisticated behavior might be required
/// by subclasses.
/// </summary>
protected virtual void ProcessLastRead(AsyncCompletionDelegate<TRead> completionDelegate)
{
FireCompletion(completionDelegate, default(TRead), null);
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = halfclosed || (cancelRequested && sendCompletionDelegate == null);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
private void ReleaseResources()
{
OnReleaseResources();
if (call != null)
{
call.Dispose();
}
gchandle.Free();
disposed = true;
}
protected virtual void OnReleaseResources()
{
}
protected void CheckSendingAllowed()
{
Preconditions.CheckState(started);
Preconditions.CheckState(!errorOccured);
CheckNotCancelled();
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!halfcloseRequested, "Already halfclosed.");
Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time");
}
protected void CheckReadingAllowed()
{
Preconditions.CheckState(started);
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!errorOccured);
Preconditions.CheckState(!readingDone, "Stream has already been closed.");
Preconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time");
}
protected void CheckNotCancelled()
{
if (cancelRequested)
{
throw new OperationCanceledException("Remote call has been cancelled.");
}
}
protected byte[] UnsafeSerialize(TWrite msg)
{
return serializer(msg);
}
protected bool TrySerialize(TWrite msg, out byte[] payload)
{
try
{
payload = serializer(msg);
return true;
}
catch (Exception)
{
Console.WriteLine("Exception occured while trying to serialize message");
payload = null;
return false;
}
}
protected bool TryDeserialize(byte[] payload, out TRead msg)
{
try
{
msg = deserializer(payload);
return true;
}
catch (Exception)
{
Console.WriteLine("Exception occured while trying to deserialize message");
msg = default(TRead);
return false;
}
}
protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error)
{
try
{
completionDelegate(value, error);
}
catch (Exception e)
{
Console.WriteLine("Exception occured while invoking completion delegate: " + e);
}
}
/// <summary>
/// Creates completion callback delegate that wraps the batch completion handler in a try catch block to
/// prevent propagating exceptions accross managed/unmanaged boundary.
/// </summary>
protected CompletionCallbackDelegate CreateBatchCompletionCallback(Action<bool, BatchContextSafeHandleNotOwned> handler)
{
return new CompletionCallbackDelegate((success, batchContextPtr) =>
{
try
{
var ctx = new BatchContextSafeHandleNotOwned(batchContextPtr);
handler(success, ctx);
}
catch (Exception e)
{
Console.WriteLine("Caught exception in a native handler: " + e);
}
});
}
/// <summary>
/// Handles send completion.
/// </summary>
private void HandleSendFinished(bool success, BatchContextSafeHandleNotOwned ctx)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new OperationFailedException("Send failed"));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles halfclose completion.
/// </summary>
private void HandleHalfclosed(bool success, BatchContextSafeHandleNotOwned ctx)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
halfclosed = true;
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new OperationFailedException("Halfclose failed"));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
private void HandleReadFinished(bool success, BatchContextSafeHandleNotOwned ctx)
{
var payload = ctx.GetReceivedMessage();
AsyncCompletionDelegate<TRead> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = readCompletionDelegate;
if (payload != null)
{
readCompletionDelegate = null;
}
else
{
// This was the last read. Keeping the readCompletionDelegate
// to be either fired by this handler or by client-side finished
// handler.
readingDone = true;
}
ReleaseResourcesIfPossible();
}
// TODO: handle the case when error occured...
if (payload != null)
{
// TODO: handle deserialization error
TRead msg;
TryDeserialize(payload, out msg);
FireCompletion(origCompletionDelegate, msg, null);
}
else
{
ProcessLastRead(origCompletionDelegate);
}
}
}
}
| |
//
// NodeTypeAttribute.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Collections.Specialized;
using Mono.Addins.Serialization;
namespace Mono.Addins.Description
{
/// <summary>
/// Description of the attribute of a node type.
/// </summary>
public sealed class NodeTypeAttribute: ObjectDescription
{
string name;
string type;
bool required;
bool localizable;
string description;
/// <summary>
/// Initializes a new instance of the <see cref="Mono.Addins.Description.NodeTypeAttribute"/> class.
/// </summary>
public NodeTypeAttribute()
{
}
/// <summary>
/// Copies data from another node attribute.
/// </summary>
/// <param name='att'>
/// The attribute from which to copy.
/// </param>
public void CopyFrom (NodeTypeAttribute att)
{
name = att.name;
type = att.type;
required = att.required;
localizable = att.localizable;
description = att.description;
}
/// <summary>
/// Gets or sets the name of the attribute.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name {
get { return name != null ? name : string.Empty; }
set { name = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Mono.Addins.Description.NodeTypeAttribute"/> is required.
/// </summary>
/// <value>
/// <c>true</c> if required; otherwise, <c>false</c>.
/// </value>
public bool Required {
get { return required; }
set { required = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Mono.Addins.Description.NodeTypeAttribute"/> is localizable.
/// </summary>
/// <value>
/// <c>true</c> if localizable; otherwise, <c>false</c>.
/// </value>
public bool Localizable {
get { return localizable; }
set { localizable = value; }
}
/// <summary>
/// Gets or sets the type of the attribute.
/// </summary>
/// <value>
/// The type.
/// </value>
public string Type {
get { return type != null ? type : string.Empty; }
set { type = value; }
}
/// <summary>
/// Gets or sets the description of the attribute.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description {
get { return description != null ? description : string.Empty; }
set { description = value; }
}
/// <summary>
/// Gets or sets the type of the content.
/// </summary>
/// <remarks>
/// Allows specifying the type of the content of a string attribute.
/// The value of this property is only informative, and it doesn't
/// have any effect on how add-ins are packaged or loaded.
/// </remarks>
public ContentType ContentType { get; set; }
internal override void Verify (string location, StringCollection errors)
{
VerifyNotEmpty (location + "Attribute", errors, Name, "name");
}
internal NodeTypeAttribute (XmlElement elem): base (elem)
{
name = elem.GetAttribute ("name");
type = elem.GetAttribute ("type");
required = elem.GetAttribute ("required").ToLower () == "true";
localizable = elem.GetAttribute ("localizable").ToLower () == "true";
string ct = elem.GetAttribute ("contentType");
if (!string.IsNullOrEmpty (ct))
ContentType = (ContentType) Enum.Parse (typeof(ContentType), ct);
description = ReadXmlDescription ();
}
internal override void SaveXml (XmlElement parent)
{
CreateElement (parent, "Attribute");
Element.SetAttribute ("name", name);
if (Type.Length > 0)
Element.SetAttribute ("type", Type);
else
Element.RemoveAttribute ("type");
if (required)
Element.SetAttribute ("required", "True");
else
Element.RemoveAttribute ("required");
if (localizable)
Element.SetAttribute ("localizable", "True");
else
Element.RemoveAttribute ("localizable");
if (ContentType != ContentType.Text)
Element.SetAttribute ("contentType", ContentType.ToString ());
else
Element.RemoveAttribute ("contentType");
SaveXmlDescription (description);
}
internal override void Write (BinaryXmlWriter writer)
{
writer.WriteValue ("name", name);
writer.WriteValue ("type", type);
writer.WriteValue ("required", required);
writer.WriteValue ("description", description);
writer.WriteValue ("localizable", localizable);
writer.WriteValue ("contentType", ContentType.ToString ());
}
internal override void Read (BinaryXmlReader reader)
{
name = reader.ReadStringValue ("name");
type = reader.ReadStringValue ("type");
required = reader.ReadBooleanValue ("required");
if (!reader.IgnoreDescriptionData)
description = reader.ReadStringValue ("description");
localizable = reader.ReadBooleanValue ("localizable");
string ct = reader.ReadStringValue ("contentType");
try {
ContentType = (ContentType) Enum.Parse (typeof(ContentType), ct);
} catch {
ContentType = ContentType.Text;
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
using System.Linq;
using System.Reflection;
namespace MsgPack
{
internal static class ReflectionAbstractions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate", Justification = "Same as FCL" )]
public static readonly char TypeDelimiter = '.';
public static readonly Type[] EmptyTypes = new Type[ 0 ];
public static bool GetIsValueType( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsValueType;
#else
return source.IsValueType;
#endif
}
public static bool GetIsEnum( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsEnum;
#else
return source.IsEnum;
#endif
}
public static bool GetIsInterface( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsInterface;
#else
return source.IsInterface;
#endif
}
public static bool GetIsAbstract( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsAbstract;
#else
return source.IsAbstract;
#endif
}
public static bool GetIsGenericType( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsGenericType;
#else
return source.IsGenericType;
#endif
}
public static bool GetIsGenericTypeDefinition( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsGenericTypeDefinition;
#else
return source.IsGenericTypeDefinition;
#endif
}
#if DEBUG
public static bool GetContainsGenericParameters( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().ContainsGenericParameters;
#else
return source.ContainsGenericParameters;
#endif
}
#endif // DEBUG
public static Assembly GetAssembly( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().Assembly;
#else
return source.Assembly;
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Wrong detection" )]
public static bool GetIsPublic( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().IsPublic;
#else
return source.IsPublic;
#endif
}
public static Type GetBaseType( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().BaseType;
#else
return source.BaseType;
#endif
}
public static Type[] GetGenericTypeParameters( this Type source )
{
#if NETFX_CORE
return source.GetTypeInfo().GenericTypeParameters;
#else
return source.GetGenericArguments().Where( t => t.IsGenericParameter ).ToArray();
#endif
}
#if NETFX_CORE
public static MethodInfo GetMethod( this Type source, string name )
{
return source.GetRuntimeMethods().SingleOrDefault( m => m.Name == name );
}
public static MethodInfo GetMethod( this Type source, string name, Type[] parameters )
{
return source.GetRuntimeMethod( name, parameters );
}
public static IEnumerable<MethodInfo> GetMethods( this Type source )
{
return source.GetRuntimeMethods();
}
public static PropertyInfo GetProperty( this Type source, string name )
{
return source.GetRuntimeProperty( name );
}
#if DEBUG
public static IEnumerable<PropertyInfo> GetProperties( this Type source )
{
return source.GetRuntimeProperties();
}
public static FieldInfo GetField( this Type source, string name )
{
return source.GetRuntimeField( name );
}
#endif
public static ConstructorInfo GetConstructor( this Type source, Type[] parameteres )
{
return source.GetTypeInfo().DeclaredConstructors.SingleOrDefault( c => c.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameteres ) );
}
public static IEnumerable<ConstructorInfo> GetConstructors( this Type source )
{
return source.GetTypeInfo().DeclaredConstructors.Where( c => c.IsPublic );
}
public static Type[] GetGenericArguments( this Type source )
{
return source.GenericTypeArguments;
}
public static bool IsAssignableFrom( this Type source, Type target )
{
return source.GetTypeInfo().IsAssignableFrom( target.GetTypeInfo() );
}
public static IEnumerable<Type> GetInterfaces( this Type source )
{
return source.GetTypeInfo().ImplementedInterfaces;
}
public static MethodInfo GetGetMethod( this PropertyInfo source )
{
return GetGetMethod( source, false );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "containsNonPublic", Justification = "For API compabitility" )]
public static MethodInfo GetGetMethod( this PropertyInfo source, bool containsNonPublic )
{
var getter = source.GetMethod;
return ( containsNonPublic || getter.IsPublic ) ? getter : null;
}
public static MethodInfo GetSetMethod( this PropertyInfo source )
{
return GetSetMethod( source, false );
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "containsNonPublic", Justification = "For API compabitility" )]
public static MethodInfo GetSetMethod( this PropertyInfo source, bool containsNonPublic )
{
var setter = source.SetMethod;
return ( containsNonPublic || setter.IsPublic ) ? setter : null;
}
public static IEnumerable<Type> FindInterfaces( this Type source, Func<Type, object, bool> filter, object filterCriteria )
{
return source.GetTypeInfo().ImplementedInterfaces.Where( t => filter( t, filterCriteria ) );
}
public static InterfaceMapping GetInterfaceMap( this Type source, Type interfaceType )
{
return source.GetTypeInfo().GetRuntimeInterfaceMap( interfaceType );
}
public static IEnumerable<CustomAttributeData> GetCustomAttributesData( this Type source )
{
return source.GetTypeInfo().CustomAttributes;
}
public static IEnumerable<CustomAttributeData> GetCustomAttributesData( this MemberInfo source )
{
return source.CustomAttributes;
}
public static Type GetAttributeType( this CustomAttributeData source )
{
return source.AttributeType;
}
public static string GetMemberName( this CustomAttributeNamedArgument source )
{
return source.MemberName;
}
#else
public static T GetCustomAttribute<T>( this MemberInfo source )
where T : Attribute
{
return Attribute.GetCustomAttribute( source, typeof( T ) ) as T;
}
#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
public static bool IsDefined( this MemberInfo source, Type attributeType )
{
return Attribute.IsDefined( source, attributeType );
}
#endif // NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
#if !SILVERLIGHT
public static Type GetAttributeType( this CustomAttributeData source )
{
return source.Constructor.DeclaringType;
}
public static string GetMemberName( this CustomAttributeNamedArgument source )
{
return source.MemberInfo.Name;
}
#else
public static Type GetAttributeType( this Attribute source )
{
return source.GetType();
}
#endif // !SILVERLIGHT
#endif // NETFX_CORE
public static string GetCultureName( this AssemblyName source )
{
#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
return source.CultureInfo.Name;
#else
return source.CultureName;
#endif
}
#if NETFX_35 || UNITY
public static IEnumerable<CustomAttributeData> GetCustomAttributesData( this MemberInfo source )
{
return CustomAttributeData.GetCustomAttributes( source );
}
public static IEnumerable<CustomAttributeData> GetCustomAttributesData( this ParameterInfo source )
{
return CustomAttributeData.GetCustomAttributes( source );
}
#endif // NETFX_35 || UNITY
#if NETFX_CORE
public static IEnumerable<CustomAttributeData> GetCustomAttributesData( this ParameterInfo source )
{
return source.CustomAttributes;
}
#endif // NETFX_CORE
#if SILVERLIGHT
public static IEnumerable<Attribute> GetCustomAttributesData( this MemberInfo source )
{
return source.GetCustomAttributes( false ).OfType<Attribute>();
}
public static IEnumerable<NamedArgument> GetNamedArguments( this Attribute attribute )
{
return
attribute.GetType()
.GetMembers( BindingFlags.Public | BindingFlags.Instance )
.Where( m => m.MemberType == MemberTypes.Field || m.MemberType == MemberTypes.Property )
.Select( m => new NamedArgument( attribute, m ) );
}
#else
public static IEnumerable<CustomAttributeNamedArgument> GetNamedArguments( this CustomAttributeData source )
{
return source.NamedArguments;
}
public static CustomAttributeTypedArgument GetTypedValue( this CustomAttributeNamedArgument source )
{
return source.TypedValue;
}
#endif // SILVERLIGHT
#if SILVERLIGHT
public struct NamedArgument
{
private object _instance;
private MemberInfo _memberInfo;
public NamedArgument( object instance, MemberInfo memberInfo )
{
this._instance = instance;
this._memberInfo = memberInfo;
}
public string GetMemberName()
{
return this._memberInfo.Name;
}
public KeyValuePair<Type, object> GetTypedValue()
{
Type type;
object value;
PropertyInfo asProperty;
if ( ( asProperty = this._memberInfo as PropertyInfo ) != null )
{
type = asProperty.PropertyType;
value = asProperty.GetValue( this._instance, null );
}
else
{
var asField = this._memberInfo as FieldInfo;
#if DEBUG
Contract.Assert( asField != null );
#endif
type = asField.FieldType;
value = asField.GetValue( this._instance );
}
return new KeyValuePair<Type, object>( type, value );
}
}
#endif // SILVERLIGHT
#if NETFX_35 || NETFX_40 || UNITY
public static Delegate CreateDelegate( this MethodInfo source, Type delegateType )
{
return Delegate.CreateDelegate( delegateType, source );
}
#endif // NETFX_35 || NETFX_40 || UNITY
public static bool GetHasDefaultValue( this ParameterInfo source )
{
#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
return source.DefaultValue != DBNull.Value;
#else
return source.HasDefaultValue;
#endif
}
}
}
| |
// <copyright file="IDictionaryExtensions.StandardTypes.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using IX.StandardExtensions.Contracts;
namespace IX.StandardExtensions.Extensions;
/// <summary>
/// Extensions for IDictionary.
/// </summary>
[SuppressMessage(
"ReSharper",
"InconsistentNaming",
Justification = "We're just doing IDictionary extensions.")]
public static partial class IDictionaryExtensions
{
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, byte> DeepClone<TKey>(this Dictionary<TKey, byte> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, byte>();
foreach (KeyValuePair<TKey, byte> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, sbyte> DeepClone<TKey>(this Dictionary<TKey, sbyte> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, sbyte>();
foreach (KeyValuePair<TKey, sbyte> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, short> DeepClone<TKey>(this Dictionary<TKey, short> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, short>();
foreach (KeyValuePair<TKey, short> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, ushort> DeepClone<TKey>(this Dictionary<TKey, ushort> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, ushort>();
foreach (KeyValuePair<TKey, ushort> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, char> DeepClone<TKey>(this Dictionary<TKey, char> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, char>();
foreach (KeyValuePair<TKey, char> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, int> DeepClone<TKey>(this Dictionary<TKey, int> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, int>();
foreach (KeyValuePair<TKey, int> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, uint> DeepClone<TKey>(this Dictionary<TKey, uint> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, uint>();
foreach (KeyValuePair<TKey, uint> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, long> DeepClone<TKey>(this Dictionary<TKey, long> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, long>();
foreach (KeyValuePair<TKey, long> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, ulong> DeepClone<TKey>(this Dictionary<TKey, ulong> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, ulong>();
foreach (KeyValuePair<TKey, ulong> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, float> DeepClone<TKey>(this Dictionary<TKey, float> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, float>();
foreach (KeyValuePair<TKey, float> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, double> DeepClone<TKey>(this Dictionary<TKey, double> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, double>();
foreach (KeyValuePair<TKey, double> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, decimal> DeepClone<TKey>(this Dictionary<TKey, decimal> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, decimal>();
foreach (KeyValuePair<TKey, decimal> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, DateTime> DeepClone<TKey>(this Dictionary<TKey, DateTime> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, DateTime>();
foreach (KeyValuePair<TKey, DateTime> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, bool> DeepClone<TKey>(this Dictionary<TKey, bool> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, bool>();
foreach (KeyValuePair<TKey, bool> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, TimeSpan> DeepClone<TKey>(this Dictionary<TKey, TimeSpan> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, TimeSpan>();
foreach (KeyValuePair<TKey, TimeSpan> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
/// <summary>
/// Creates a deep clone of a dictionary, with deep clones of its values.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <returns>A deeply-cloned dictionary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/> (<see langword="Nothing"/> in Visual Basic).</exception>
public static Dictionary<TKey, string> DeepClone<TKey>(this Dictionary<TKey, string> source)
where TKey : notnull
{
var localSource = Requires.NotNull(source);
var destination = new Dictionary<TKey, string>();
foreach (KeyValuePair<TKey, string> p in localSource)
{
destination.Add(p.Key, p.Value);
}
return destination;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
namespace StackCommitTest
{
public unsafe class WinApi
{
#pragma warning disable 618
[DllImport("kernel32.dll")]
public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo);
#pragma warning restore 618
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
internal PROCESSOR_INFO_UNION uProcessorInfo;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort dwProcessorLevel;
public ushort dwProcessorRevision;
}
[StructLayout(LayoutKind.Explicit)]
public struct PROCESSOR_INFO_UNION
{
[FieldOffset(0)]
internal uint dwOemId;
[FieldOffset(0)]
internal ushort wProcessorArchitecture;
[FieldOffset(2)]
internal ushort wReserved;
}
[DllImport("kernel32")]
public static extern IntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, IntPtr length);
public struct MEMORY_BASIC_INFORMATION
{
public byte* BaseAddress;
public byte* AllocationBase;
public int AllocationProtect;
public IntPtr RegionSize;
public MemState State;
public int Protect;
public int Type;
}
[Flags]
public enum MemState
{
MEM_COMMIT = 0x1000,
MEM_RESERVE = 0x2000,
MEM_FREE = 0x10000,
}
public const int PAGE_GUARD = 0x100;
}
unsafe public static class Utility
{
public static Int64 PageSize { get; private set; }
static Utility()
{
WinApi.SYSTEM_INFO sysInfo = new WinApi.SYSTEM_INFO();
WinApi.GetSystemInfo(ref sysInfo);
PageSize = (Int64)sysInfo.dwPageSize;
}
public static void GetStackExtents(out byte* stackBase, out long stackSize)
{
WinApi.MEMORY_BASIC_INFORMATION info = new WinApi.MEMORY_BASIC_INFORMATION();
WinApi.VirtualQuery(&info, ref info, new IntPtr(sizeof(WinApi.MEMORY_BASIC_INFORMATION)));
stackBase = info.AllocationBase;
stackSize = (info.BaseAddress - info.AllocationBase) + info.RegionSize.ToInt64();
}
public static List<WinApi.MEMORY_BASIC_INFORMATION> GetRegionsOfStack()
{
byte* stackBase;
long stackSize;
GetStackExtents(out stackBase, out stackSize);
List<WinApi.MEMORY_BASIC_INFORMATION> result = new List<WinApi.MEMORY_BASIC_INFORMATION>();
byte* current = stackBase;
while (current < stackBase + stackSize)
{
WinApi.MEMORY_BASIC_INFORMATION info = new WinApi.MEMORY_BASIC_INFORMATION();
WinApi.VirtualQuery(current, ref info, new IntPtr(sizeof(WinApi.MEMORY_BASIC_INFORMATION)));
result.Add(info);
current = info.BaseAddress + info.RegionSize.ToInt64();
}
result.Reverse();
return result;
}
public static bool ValidateStack(string threadName, bool shouldBePreCommitted, Int32 expectedStackSize)
{
bool result = true;
byte* stackBase;
long stackSize;
GetStackExtents(out stackBase, out stackSize);
Console.WriteLine("{2} -- Base: {0:x}, Size: {1}kb", new IntPtr(stackBase).ToInt64(), stackSize / 1024, threadName);
//
// Start at the highest addresses, which should be committed (because that's where we're currently running).
// The next region should be committed, but marked as a guard page.
// After that, we'll either find committed pages, or reserved pages, depending on whether the runtime
// is pre-committing stacks.
//
bool foundGuardRegion = false;
foreach (var info in GetRegionsOfStack())
{
string regionType = string.Empty;
if (!foundGuardRegion)
{
if ((info.Protect & WinApi.PAGE_GUARD) != 0)
{
foundGuardRegion = true;
regionType = "guard region";
}
else
{
regionType = "active region";
}
}
else
{
if (shouldBePreCommitted)
{
if (!info.State.HasFlag(WinApi.MemState.MEM_COMMIT))
{
// If we pre-commit the stack, the last 1 or 2 pages are left "reserved" (they are the "hard guard region")
// ??? How to decide whether it is 1 or 2 pages?
if ((info.BaseAddress != stackBase || info.RegionSize.ToInt64() > PageSize))
{
result = false;
regionType = "<---- should be pre-committed";
}
}
}
else
{
if (info.State.HasFlag(WinApi.MemState.MEM_COMMIT))
{
result = false;
regionType = "<---- should not be pre-committed";
}
}
}
Console.WriteLine(
"{0:x8}-{1:x8} {2,5:g}kb {3,-11:g} {4}",
new IntPtr(info.BaseAddress).ToInt64(),
new IntPtr(info.BaseAddress + info.RegionSize.ToInt64()).ToInt64(),
info.RegionSize.ToInt64() / 1024,
info.State,
regionType);
}
if (!foundGuardRegion)
{
result = false;
Console.WriteLine("Did not find GuardRegion for the whole stack");
}
if (expectedStackSize != -1 && stackSize != expectedStackSize)
{
result = false;
Console.WriteLine("Stack size is not as expected: actual -- {0}, expected -- {1}", stackSize, expectedStackSize);
}
Console.WriteLine();
return result;
}
static private bool RunTestItem(string threadName, bool shouldBePreCommitted, Int32 expectedThreadSize, Action<Action> runOnThread)
{
bool result = false;
ManualResetEventSlim mre = new ManualResetEventSlim();
runOnThread(() =>
{
result = Utility.ValidateStack(threadName, shouldBePreCommitted, expectedThreadSize);
mre.Set();
});
mre.Wait();
return result;
}
static public bool RunTest(bool shouldBePreCommitted)
{
if (RunTestItem("Main", shouldBePreCommitted, -1, action => action()) &
RunTestItem("ThreadPool", shouldBePreCommitted, -1, action => ThreadPool.QueueUserWorkItem(state => action())) &
RunTestItem("new Thread()", shouldBePreCommitted, -1, action => new Thread(() => action()).Start()) &
//RunTestItem("new Thread(512kb)", true, 512 * 1024, action => new Thread(() => action(), 512 * 1024).Start()) &
RunTestItem("Finalizer", shouldBePreCommitted, -1, action => Finalizer.Run(action)))
{
return true;
}
return false;
}
}
public class Finalizer
{
Action m_action;
private Finalizer(Action action) { m_action = action; }
~Finalizer() { m_action(); }
public static void Run(Action action)
{
//We need to allocate the object inside of a seperate method to ensure that
//the reference will be eliminated before GC.Collect is called. Technically
//even across methods we probably don't make any formal guarantees but this
//is sufficient for current runtime implementations.
CreateUnreferencedObject(action);
GC.Collect();
GC.WaitForPendingFinalizers();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void CreateUnreferencedObject(Action action)
{
new Finalizer(action);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace ClosedXML.Excel
{
using System.Linq;
using System.Text.RegularExpressions;
using System.Drawing;
/// <summary>
/// Common methods
/// </summary>
public static class XLHelper
{
public const int MinRowNumber = 1;
public const int MinColumnNumber = 1;
public const int MaxRowNumber = 1048576;
public const int MaxColumnNumber = 16384;
public const String MaxColumnLetter = "XFD";
public const Double Epsilon = 1e-10;
private const Int32 TwoT26 = 26*26;
internal static readonly Graphics Graphic = Graphics.FromImage(new Bitmap(200, 200));
internal static readonly Double DpiX = Graphic.DpiX;
internal static readonly NumberStyles NumberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowExponent;
internal static readonly CultureInfo ParseCulture = CultureInfo.InvariantCulture;
internal static readonly Regex A1SimpleRegex = new Regex(
@"\A"
+ @"(?<Reference>" // Start Group to pick
+ @"(?<Sheet>" // Start Sheet Name, optional
+ @"("
+ @"\'([^\[\]\*/\\\?:\']+|\'\')\'"
// Sheet name with special characters, surrounding apostrophes are required
+ @"|"
+ @"\'?\w+\'?" // Sheet name with letters and numbers, surrounding apostrophes are optional
+ @")"
+ @"!)?" // End Sheet Name, optional
+ @"(?<Range>" // Start range
+ @"\$?[a-zA-Z]{1,3}\$?\d{1,7}" // A1 Address 1
+ @"(?<RangeEnd>:\$?[a-zA-Z]{1,3}\$?\d{1,7})?" // A1 Address 2, optional
+ @"|"
+ @"(?<ColumnNumbers>\$?\d{1,7}:\$?\d{1,7})" // 1:1
+ @"|"
+ @"(?<ColumnLetters>\$?[a-zA-Z]{1,3}:\$?[a-zA-Z]{1,3})" // A:A
+ @")" // End Range
+ @")" // End Group to pick
+ @"\Z"
, RegexOptions.Compiled);
internal static readonly Regex NamedRangeReferenceRegex =
new Regex(@"^('?(?<Sheet>[^'!]+)'?!(?<Range>.+))|((?<Table>[^\[]+)\[(?<Column>[^\]]+)\])$",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture
);
/// <summary>
/// Gets the column number of a given column letter.
/// </summary>
/// <param name="columnLetter"> The column letter to translate into a column number. </param>
public static int GetColumnNumberFromLetter(string columnLetter)
{
if (string.IsNullOrEmpty(columnLetter)) throw new ArgumentNullException("columnLetter");
int retVal;
columnLetter = columnLetter.ToUpper();
//Extra check because we allow users to pass row col positions in as strings
if (columnLetter[0] <= '9')
{
retVal = Int32.Parse(columnLetter, XLHelper.NumberStyle, XLHelper.ParseCulture);
return retVal;
}
int sum = 0;
for (int i = 0; i < columnLetter.Length; i++)
{
sum *= 26;
sum += (columnLetter[i] - 'A' + 1);
}
return sum;
}
private static readonly string[] letters = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
/// <summary>
/// Gets the column letter of a given column number.
/// </summary>
/// <param name="columnNumber"> The column number to translate into a column letter. </param>
public static string GetColumnLetterFromNumber(int columnNumber)
{
columnNumber--; // Adjust for start on column 1
if (columnNumber <= 25)
{
return letters[columnNumber];
}
var firstPart = (columnNumber) / 26;
var remainder = ((columnNumber) % 26) + 1;
return GetColumnLetterFromNumber(firstPart) + GetColumnLetterFromNumber(remainder);
}
public static bool IsValidColumn(string column)
{
var length = column.Length;
if (IsNullOrWhiteSpace(column) || length > 3)
return false;
var theColumn = column.ToUpper();
var isValid = theColumn[0] >= 'A' && theColumn[0] <= 'Z';
if (length == 1)
return isValid;
if (length == 2)
return isValid && theColumn[1] >= 'A' && theColumn[1] <= 'Z';
if (theColumn[0] >= 'A' && theColumn[0] < 'X')
return theColumn[1] >= 'A' && theColumn[1] <= 'Z'
&& theColumn[2] >= 'A' && theColumn[2] <= 'Z';
if (theColumn[0] != 'X') return false;
if (theColumn[1] < 'F')
return theColumn[2] >= 'A' && theColumn[2] <= 'Z';
if (theColumn[1] != 'F') return false;
return theColumn[2] >= 'A' && theColumn[2] <= 'D';
}
public static bool IsValidRow(string rowString)
{
Int32 row;
if (Int32.TryParse(rowString, out row))
return row > 0 && row <= MaxRowNumber;
return false;
}
public static bool IsValidA1Address(string address)
{
if (IsNullOrWhiteSpace(address))
return false;
address = address.Replace("$", "");
var rowPos = 0;
var addressLength = address.Length;
while (rowPos < addressLength && (address[rowPos] > '9' || address[rowPos] < '0'))
rowPos++;
return
rowPos < addressLength
&& IsValidRow(address.Substring(rowPos))
&& IsValidColumn(address.Substring(0, rowPos));
}
public static Boolean IsValidRangeAddress(String rangeAddress)
{
return A1SimpleRegex.IsMatch(rangeAddress);
}
public static Boolean IsValidRangeAddress(IXLRangeAddress rangeAddress)
{
return !rangeAddress.IsInvalid
&& rangeAddress.FirstAddress.RowNumber >= 1 && rangeAddress.LastAddress.RowNumber <= MaxRowNumber
&& rangeAddress.FirstAddress.ColumnNumber >= 1 && rangeAddress.LastAddress.ColumnNumber <= MaxColumnNumber
&& rangeAddress.FirstAddress.RowNumber <= rangeAddress.LastAddress.RowNumber
&& rangeAddress.FirstAddress.ColumnNumber <= rangeAddress.LastAddress.ColumnNumber;
}
public static int GetColumnNumberFromAddress(string cellAddressString)
{
var rowPos = 0;
while (cellAddressString[rowPos] > '9')
rowPos++;
return GetColumnNumberFromLetter(cellAddressString.Substring(0, rowPos));
}
internal static string[] SplitRange(string range)
{
return range.Contains('-') ? range.Replace('-', ':').Split(':') : range.Split(':');
}
public static Int32 GetPtFromPx(Double px)
{
return Convert.ToInt32(px*72.0/DpiX);
}
public static Double GetPxFromPt(Int32 pt)
{
return Convert.ToDouble(pt)*DpiX/72.0;
}
internal static IXLTableRows InsertRowsWithoutEvents(Func<int, bool, IXLRangeRows> insertFunc,
XLTableRange tableRange, Int32 numberOfRows,
Boolean expandTable)
{
var ws = tableRange.Worksheet;
var tracking = ws.EventTrackingEnabled;
ws.EventTrackingEnabled = false;
var rows = new XLTableRows(ws.Style);
var inserted = insertFunc(numberOfRows, false);
inserted.ForEach(r => rows.Add(new XLTableRow(tableRange, r as XLRangeRow)));
if (expandTable)
tableRange.Table.ExpandTableRows(numberOfRows);
ws.EventTrackingEnabled = tracking;
return rows;
}
public static bool IsNullOrWhiteSpace(string value)
{
#if NET4
return String.IsNullOrWhiteSpace(value);
#else
if (value != null)
{
var length = value.Length;
for (int i = 0; i < length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
#endif
}
private static readonly Regex A1RegexRelative = new Regex(
@"(?<=\W)(?<one>\$?[a-zA-Z]{1,3}\$?\d{1,7})(?=\W)" // A1
+ @"|(?<=\W)(?<two>\$?\d{1,7}:\$?\d{1,7})(?=\W)" // 1:1
+ @"|(?<=\W)(?<three>\$?[a-zA-Z]{1,3}:\$?[a-zA-Z]{1,3})(?=\W)", RegexOptions.Compiled); // A:A
private static string Evaluator(Match match, Int32 row, String column)
{
if (match.Groups["one"].Success)
{
var split = match.Groups["one"].Value.Split('$');
if (split.Length == 1) return column + row; // A1
if (split.Length == 3) return match.Groups["one"].Value; // $A$1
var a = XLAddress.Create(match.Groups["one"].Value);
if (split[0] == String.Empty) return "$" + a.ColumnLetter + row; // $A1
return column + "$" + a.RowNumber;
}
if (match.Groups["two"].Success)
return ReplaceGroup(match.Groups["two"].Value, row.ToString());
return ReplaceGroup(match.Groups["three"].Value, column);
}
private static String ReplaceGroup(String value, String item)
{
var split = value.Split(':');
String ret1 = split[0].StartsWith("$") ? split[0] : item;
String ret2 = split[1].StartsWith("$") ? split[1] : item;
return ret1 + ":" + ret2;
}
internal static String ReplaceRelative(String value, Int32 row, String column)
{
var oldValue = ">" + value + "<";
var newVal = A1RegexRelative.Replace(oldValue, m => Evaluator(m, row, column));
return newVal.Substring(1, newVal.Length - 2);
}
public static Boolean AreEqual(Double d1, Double d2)
{
return Math.Abs(d1 - d2) < Epsilon;
}
public static DateTime GetDate(Object v)
{
// handle dates
if (v is DateTime)
{
return (DateTime)v;
}
// handle doubles
if (v is double && ((double)v).IsValidOADateNumber())
{
return DateTime.FromOADate((double)v);
}
// handle everything else
return (DateTime)Convert.ChangeType(v, typeof(DateTime));
}
internal static bool IsValidOADateNumber(this double d)
{
return -657435 <= d && d < 2958466;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using WaterOneFlow.Schema.v1_1;
using WaterOneFlowImpl;
using log4net;
using WaterOneFlowImpl.geom;
namespace WaterOneFlow.odws
{
//using WaterOneFlow.odm.v1_1;
using WaterOneFlowImpl.v1_1;
namespace v1_1
{
public class CustomService : IDisposable
{
private Cache appCache;
private HttpContext appContext;
//private VariablesDataset vds;
/* This is now done in the global.asax file
// this got cached, which cause the name to be localhost
*/
private string serviceUrl;
private string serviceName;
private static readonly ILog log = LogManager.GetLogger(typeof(CustomService));
private static readonly ILog queryLog = LogManager.GetLogger("QueryLog");
private static readonly CustomLogging queryLog2 = new CustomLogging();
public CustomService(HttpContext aContext)
{
log.Debug("Starting " + System.Configuration.ConfigurationManager.AppSettings["network"]);
appContext = aContext;
// This is now done in the global.asax file
// this got cached, which cause the name to be localhost
serviceName = ConfigurationManager.AppSettings["GetValuesName"];
Boolean odValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]);
if (odValues)
{
string Port = aContext.Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
string Protocol = aContext.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
// *** Figure out the base Url which points at the application's root
serviceUrl = Protocol + aContext.Request.ServerVariables["SERVER_NAME"] +
Port +
aContext.Request.ApplicationPath
+ "/" + ConfigurationManager.AppSettings["asmxPage_1_1"] + "?WSDL";
}
else
{
serviceUrl = ConfigurationManager.AppSettings["externalGetValuesService"];
}
}
#region Site Information
public SiteInfoResponseType GetSiteInfo(string locationParameter)
{
string siteId = locationParameter.Substring(locationParameter.LastIndexOf(":")+1);
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = new SiteInfoResponseTypeSite[1];
resp.site[0] = new SiteInfoResponseTypeSite();
resp.site[0] = WebServiceUtils.GetSiteFromDb(siteId, true);
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSiteInfo", new string[] { locationParameter }, null, null, null, null);
return resp;
}
public SiteInfoResponseType GetSiteInfo(string[] locationParameter, Boolean IncludeSeries)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
if (locationParameter != null)
{
queryLog2.LogStart(CustomLogging.Methods.GetSiteInfo, locationParameter.ToString(),
appContext.Request.UserHostName);
}
else
{
queryLog2.LogStart(CustomLogging.Methods.GetSiteInfo, "NULL",
appContext.Request.UserHostName);
}
List<locationParam> lpList = new List<locationParam>();
try
{
foreach (string s in locationParameter)
{
locationParam l = new locationParam(s);
if (l.isGeometry)
{
String error = "Location by Geometry not accepted: " + locationParameter;
log.Debug(error);
throw new WaterOneFlowException(error);
}
else
{
lpList.Add(l);
}
}
}
catch (WaterOneFlowException we)
{
log.Error(we.Message);
throw;
}
catch (Exception e)
{
String error =
"Sorry. Your submitted site ID for this getSiteInfo request caused an problem that we failed to catch programmatically: " +
e.Message;
log.Error(error);
throw new WaterOneFlowException(error);
}
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = new SiteInfoResponseTypeSite[locationParameter.Length];
for (int i = 0; i < locationParameter.Length; i++)
{
resp.site[i] = WebServiceUtils.GetSiteFromDb(locationParameter[0], true);
}
foreach (SiteInfoResponseTypeSite site in resp.site)
{
foreach (seriesCatalogType catalog in site.seriesCatalog)
{
catalog.menuGroupName = serviceName;
catalog.serviceWsdl = serviceUrl;
}
}
if (locationParameter != null)
{
queryLog2.LogEnd(CustomLogging.Methods.GetSiteInfo,
locationParameter.ToString(),
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
}
else
{
queryLog2.LogEnd(CustomLogging.Methods.GetSiteInfo,
"NULL",
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
}
return resp;
}
public SiteInfoResponseType GetSites(string[] locationIDs)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
queryLog2.LogStart(CustomLogging.Methods.GetSites, locationIDs.ToString(),
appContext.Request.UserHostName);
SiteInfoResponseType result = new SiteInfoResponseType();
result.site = WebServiceUtils.GetSitesFromDb();
//set query info
result.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSites");
NoteType note = CuahsiBuilder.createNote("ALL Sites(empty request)");
result.queryInfo.note = CuahsiBuilder.addNote(null, note);
queryLog2.LogEnd(CustomLogging.Methods.GetSites,
locationIDs.ToString(),
timer.ElapsedMilliseconds.ToString(),
result.site.Length.ToString(),
appContext.Request.UserHostName);
return result;
}
public SiteInfoResponseType GetSitesInBox(
float west, float south, float east, float north,
Boolean IncludeSeries
)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
box queryBox = new box(west, south, east, north);
queryLog2.LogStart(CustomLogging.Methods.GetSitesInBoxObject, queryBox.ToString(),
appContext.Request.UserHostName);
SiteInfoResponseType resp = new SiteInfoResponseType();
resp.site = WebServiceUtils.GetSitesByBox(queryBox, IncludeSeries);
//set query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetSitesInBox");
NoteType note = CuahsiBuilder.createNote("box");
resp.queryInfo.note = CuahsiBuilder.addNote(null, note);
queryLog2.LogEnd(CustomLogging.Methods.GetSitesInBoxObject,
queryBox.ToString(),
timer.ElapsedMilliseconds.ToString(),
resp.site.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
#endregion
#region variable
/// <summary>
/// GetVariableInfo
/// </summary>
/// <param name="VariableParameter">full variable code in format vocabulary:VariableCode</param>
/// <returns>the VariableInfo object</returns>
public VariablesResponseType GetVariableInfo(String VariableParameter)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
queryLog2.LogStart(CustomLogging.Methods.GetVariables, VariableParameter,
appContext.Request.UserHostName);
VariablesResponseType resp;
if(string.IsNullOrEmpty(VariableParameter))
{
resp = new VariablesResponseType();
resp.variables = WebServiceUtils.GetVariablesFromDb();
//setup query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType
("GetVariableInfo", null, null, new string[] { string.Empty }, null, null);
CuahsiBuilder.addNote(resp.queryInfo.note,
CuahsiBuilder.createNote("(Request for all variables"));
}
else
{
resp = new VariablesResponseType();
resp.variables = new VariableInfoType[1];
resp.variables[0] = WebServiceUtils.GetVariableInfoFromDb(VariableParameter);
//setup query info
resp.queryInfo = CuahsiBuilder.CreateQueryInfoType
("GetVariableInfo", null, null, new string[] { VariableParameter }, null, null);
}
queryLog2.LogEnd(CustomLogging.Methods.GetVariables,
VariableParameter,
timer.ElapsedMilliseconds.ToString(),
resp.variables.Length.ToString(),
appContext.Request.UserHostName);
return resp;
}
#endregion
#region values
/// <summary>
/// GetValues custom implementation
/// </summary>
/// <param name="SiteNumber">network:SiteCode</param>
/// <param name="Variable">vocabulary:VariableCode</param>
/// <param name="StartDate">yyyy-MM-dd</param>
/// <param name="EndDate">yyyy-MM-dd</param>
/// <returns></returns>
public TimeSeriesResponseType GetValues(string SiteNumber,
string Variable,
string StartDate,
string EndDate)
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
// queryLog.Info("GetValues|" + SiteNumber + "|" + Variable + "|" + StartDate + "|" + EndDate);
//String network,method,location, variable, start, end, , processing time,count
queryLog2.LogValuesStart(CustomLogging.Methods.GetValues, // method
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
EndDate, //enddate
appContext.Request.UserHostName);
//get siteId, variableId
string siteId = SiteNumber.Substring(SiteNumber.LastIndexOf(":") + 1);
string variableCode = Variable.Substring(Variable.LastIndexOf(":") + 1);
//get startDateTime, endDateTime
DateTime startDateTime = new DateTime(2000, 1, 1);
DateTime endDateTime = DateTime.Now.AddYears(1);
if (StartDate != string.Empty)
{
startDateTime = DateTime.Parse(StartDate);
}
if (EndDate != string.Empty)
{
endDateTime = DateTime.Parse(EndDate);
}
//TimeSeriesResponseType resp = obj.getValues(SiteNumber, Variable, StartDate, EndDate);
TimeSeriesResponseType resp = new TimeSeriesResponseType();
resp.timeSeries = new TimeSeriesType[1];
resp.timeSeries[0] = new TimeSeriesType();
resp.timeSeries[0].sourceInfo = WebServiceUtils.GetSiteFromDb2(siteId);
resp.timeSeries[0].variable = WebServiceUtils.GetVariableInfoFromDb(variableCode);
resp.timeSeries[0].values = new TsValuesSingleVariableType[1];
resp.timeSeries[0].values[0] = WebServiceUtils.GetValuesFromDb(siteId, variableCode, startDateTime, endDateTime);
//set the query info
resp.queryInfo = new QueryInfoType();
resp.queryInfo.criteria = new QueryInfoTypeCriteria();
resp.queryInfo.creationTime = DateTime.UtcNow;
resp.queryInfo.creationTimeSpecified = true;
resp.queryInfo.criteria.locationParam = SiteNumber;
resp.queryInfo.criteria.variableParam = Variable;
resp.queryInfo.criteria.timeParam = CuahsiBuilder.createQueryInfoTimeCriteria(StartDate, EndDate);
queryLog2.LogValuesEnd(CustomLogging.Methods.GetValues,
SiteNumber, //locaiton
Variable, //variable
StartDate, // startdate
EndDate, //enddate
timer.ElapsedMilliseconds, // processing time
// assume one for now
resp.timeSeries[0].values[0].value.Length, // count
appContext.Request.UserHostName);
return resp;
}
//TODO implement this function
public TimeSeriesResponseType GetValuesForASite(string site, string startDate, string endDate)
{
{
Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
//String network,method,location, variable, start, end, , processing time,count
queryLog2.LogValuesStart(CustomLogging.Methods.GetValuesForSiteObject, // method
site, //locaiton
"ALL", //variable
startDate, // startdate
endDate, //enddate
appContext.Request.UserHostName);
//TimeSeriesResponseType resp = obj.GetValuesForSiteVariable(site, startDate, endDate);
TimeSeriesResponseType resp = new TimeSeriesResponseType();
// //String network,method,location, variable, start, end, , processing time,count
// queryLog.InfoFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
//System.Configuration.ConfigurationManager.AppSettings["network"], // network
//"GetValues", // method
//SiteNumber, //locaiton
//Variable, //variable
//StartDate, // startdate
//StartDate, //enddate
//timer.ElapsedMilliseconds, // processing time
//resp.timeSeries.values.value.Length // count
//,
// appContext.Request.UserHostName);
queryLog2.LogValuesEnd(CustomLogging.Methods.GetValuesForSiteObject,
site, //locaiton
"ALL", //variable
startDate, // startdate
endDate, //enddate
timer.ElapsedMilliseconds, // processing time
// assume one for now
-9999, // May need to count all.
appContext.Request.UserHostName);
return resp;
}
}
#endregion
#region token
public AuthTokenResponseType GetAuthToken(string userName, string password)
{
string validUser = "admin";
string validPassword = "1234";
string validToken = "QwCcA13Ux47ZdwpyX8j";
AuthTokenResponseType resp = new AuthTokenResponseType();
if (userName == validUser && password == validPassword)
{
resp.Token = validToken;
resp.IsValid = true;
resp.Expires = DateTime.Now.Date.AddDays(10).ToString("yyyy-mm-dd");
resp.Message = "the user is valid";
}
else
{
resp.IsValid = false;
resp.Token = null;
resp.Expires = null;
resp.Message = "Invalid userName or password";
}
return resp;
}
private bool isValidToken(string token)
{
string validToken = "QwCcA13Ux47ZdwpyX8j";
return (token == validToken);
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposeOf)
{
// waterLog.Dispose();
}
#endregion
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using Epi;
using Epi.Windows;
using Epi.Windows.Dialogs;
using Epi.Data;
using Epi.Fields;
using Epi.Collections;
namespace Epi.Windows.MakeView.Dialogs
{
/// <summary>
/// The Code Dialog
/// </summary>
public partial class ListDialog : LegalValuesDialog
{
#region Public Interface
#region Constructors
/// <summary>
/// Default Constructor - Design mode only
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public ListDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor of the Codes dialog
/// </summary>
/// <param name="frm">The main form</param>
/// <param name="name">The field's name</param>
/// <param name="currentPage">The current page</param>
public ListDialog(MainForm frm, string name, Page currentPage)
: base(frm, name, currentPage)
{
InitializeComponent();
fieldName = name;
page = currentPage;
ddlField = new DDListField(page);
ddlField.Name = fieldName;
selectedFields = new NamedObjectCollection<Field>();
SetDataSource(ddlField);
SetDgCodes(dgCodes, fieldName);
}
/// <summary>
/// Constructor of the Codes dialog
/// </summary>
/// <param name="frm">The main form</param>
/// <param name="field">The field</param>
/// <param name="currentPage">The current page</param>
public ListDialog(MainForm frm, RenderableField field, Page currentPage)
: base(frm, field, currentPage)
{
InitializeComponent();
page = currentPage;
ddlField = (DDListField)field;
codeTable = ddlField.GetSourceData();
this.Text = "List Field";
//cbxSort.Checked = ddlField.ShouldSort;
fieldName = ddlField.Name;
SetDataSource(ddlField);
SetDgCodes(dgCodes, fieldName);
}
/// <summary>
/// Contructor of the CodesDialog
/// </summary>
/// <param name="field">The field</param>
/// <param name="frm">The main form</param>
/// <param name="name">The field name</param>
/// <param name="currentPage">The current page</param>
/// <param name="selectedItems">The names of the fields from the Code Field Definition dialog</param>
public ListDialog(TableBasedDropDownField field, MainForm frm, string name, Page currentPage, NamedObjectCollection<Field> selectedItems)
: base(frm, name, currentPage)
{
InitializeComponent();
fieldName = name;
page = currentPage;
ddlField = (DDListField)field;
this.Text = "List Field";
//if (!(string.IsNullOrEmpty(sourceTableName)))
//{
// codeTable = ddlField.GetSourceData();
//}
selectedFields = selectedItems;
SetDataSource(ddlField);
SetDgCodes(dgCodes, fieldName);
}
#endregion Constructors
#region Public Enums and Constants
#endregion Public Enums and Constants
#region Public Properties
/// <summary>
/// The source table name
/// </summary>
public new string SourceTableName
{
get
{
return (sourceTableName);
}
set
{
sourceTableName = value;
}
}
/// <summary>
/// Text Column Name
/// </summary>
public new string TextColumnName
{
get
{
return (textColumnName);
}
}
/// <summary>
/// A collection of selected fields
/// </summary>
public NamedObjectCollection<Field> SelectedFields
{
get
{
return (selectedFields);
}
}
#endregion Public Properties
#region Public Methods
#endregion Public Methods
#endregion Public Interface
#region Protected Interface
#region Protected Properties
#endregion Protected Properties
#region Protected Methods
#endregion Protected Methods
#region Protected Events
/// <summary>
/// Handles click event of Create button
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnCreate_Click(object sender, System.EventArgs e)
{
CreateCodes();
// don't necessarily want to do this for the user
//foreach (Field field in SelectedFields)
//{
// ((SingleLineTextField)field).IsReadOnly = true;
// field.SaveToDb();
//}
btnCreate.Enabled = false;
btnUseExisting.Enabled = false;
dgCodes.Visible = true;
btnOK.Enabled = true;
}
/// <summary>
/// Handles click event of OK button
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnOK_Click(object sender, System.EventArgs e)
{
SaveShouldSort();
if (codeTable == null)
{
//new code table
SaveCodeTableToField();
}
else
{
//else, you are using an existing table
if ((DataTable)dgCodes.DataSource != null)
{
DataTable dataTables = page.GetProject().CodeData.GetCodeTableNamesForProject(page.GetProject());
// def 1471 -- commented the foreach block
// bool doesExist = false;
//foreach (DataRow row in dataTables.Rows)
//{
// if ((codeTable.TableName).Equals(row[0]))
// {
// doesExist = true;
// }
//}
// Added this condition -- Def 1471
//if (page.GetProject().CollectedData.TableExists(codeTable.TableName))
//{
// if (!(page.GetProject().CollectedData.TableExists(codeTable.TableName + fieldName.ToLowerInvariant())))
// {
// //to handle use existing, and the new column
// codeTable.TableName = codeTable.TableName + fieldName.ToLowerInvariant();
// dgCodes.DataSource = codeTable;
// }
//}
this.sourceTableName = codeTable.TableName;
int index = 0;
string[] columnsToSave = new string[codeTable.Columns.Count];
foreach (DataColumn column in codeTable.Columns)
{
columnsToSave[index] = codeTable.Columns[index].ColumnName;
index = index + 1;
}
page.GetProject().CreateCodeTable(codeTable.TableName, columnsToSave);
//page.GetProject().SaveCodeTableData(codeTable, codeTable.TableName, columnsToSave);
page.GetProject().InsertCodeTableData(codeTable, codeTable.TableName, columnsToSave);
}
}
this.DialogResult = DialogResult.OK;
this.Hide();
}
#endregion Protected Events
#endregion Protected Interface
#region Private Members
#region Private Enums and Constants
private double MULTICOLUMN_WIDTH_MULTIPLE = .4;
#endregion Private Enums and Constants
#region Private Properties
private string fieldName = string.Empty;
private DataTable codeTable;
private DataTable valueTable;
private DataTable fieldSetupTable;
private DataTable fieldValueSetupTable;
private DataTable finalTable;
private Page page;
private string sourceTableName = string.Empty;
private string textColumnName = string.Empty;
private NamedObjectCollection<Field> selectedFields;
private new DDListField ddlField;
#endregion Private Properties
#region Private Methods
private void SetDgCodes(DataGridView dgCodes, string fieldName)
{
//dgCodes.CaptionText = "List for: " + fieldName.ToLowerInvariant();
//dgCodes.PreferredColumnWidth = Convert.ToInt32(dgCodes.Width * MULTICOLUMN_WIDTH_MULTIPLE);
}
private void SetDataSource(DDListField ddlField)
{
if (!string.IsNullOrEmpty(ddlField.SourceTableName))
{
codeTable = ddlField.GetSourceData();
sourceTableName = ddlField.SourceTableName;
textColumnName = ddlField.TextColumnName;
}
}
private void DisplayData()
{
if (codeTable != null)
{
dgCodes.Visible = true;
btnOK.Enabled = true;
btnCreate.Enabled = false;
btnUseExisting.Enabled = false;
btnDelete.Enabled = false;
codeTable.TableName = sourceTableName;
dgCodes.DataSource = codeTable;
cbxSort.Checked = !ddlField.ShouldSort;
btnOK.Visible = true;
btnCreate.Enabled = false;
btnUseExisting.Enabled = false;
btnDelete.Visible = true;
}
}
private void CreateCodes()
{
dgCodes.Visible = true;
DataTable bindingTable = page.GetProject().CodeData.GetCodeTableNamesForProject(page.GetProject());
DataView dataView = bindingTable.DefaultView;
//if (dgCodes.AllowSorting)
//{
// dataView.Sort = GetDisplayString(page);
//}
string cleanedCodeTableName = CleanCodeTableName(fieldName, dataView);
if (SelectedFields.Count >= 1)
{
int i = 1;
string[] selectedFieldsForCodeColumns = new string[SelectedFields.Count + 1];
selectedFieldsForCodeColumns[0] = fieldName;
foreach (Field field in SelectedFields)
{
selectedFieldsForCodeColumns[i] = field.Name;
i += 1;
}
//dgCodes.PreferredColumnWidth = Convert.ToInt32(dgCodes.Width * MULTICOLUMN_WIDTH_MULTIPLE);
page.GetProject().CreateCodeTable(cleanedCodeTableName, selectedFieldsForCodeColumns);
}
else
{
page.GetProject().CreateCodeTable(cleanedCodeTableName, fieldName.ToLowerInvariant());
}
codeTable = page.GetProject().GetTableData(cleanedCodeTableName);
codeTable.TableName = cleanedCodeTableName;
dgCodes.DataSource = codeTable;
sourceTableName = codeTable.TableName;
textColumnName = fieldName;
}
/// <summary>
/// Link the code table up to the field and save
/// </summary>
private void SaveCodeTableToField()
{
DataTable dataTable = (DataTable)dgCodes.DataSource;
if (dataTable != null)
{
if (dataTable.Columns.Count > 1)
{
int index = 0;
string[] columnsToSave = new string[dataTable.Columns.Count];
foreach (DataColumn column in dataTable.Columns)
{
columnsToSave[index] = dataTable.Columns[index].ColumnName;
index = index + 1;
}
page.GetProject().SaveCodeTableData(dataTable, dataTable.TableName, columnsToSave);
}
else
{
page.GetProject().SaveCodeTableData(dataTable, dataTable.TableName, dataTable.Columns[0].ColumnName);
}
this.sourceTableName = dataTable.TableName;
this.textColumnName = dataTable.Columns[0].ColumnName;
}
}
private NamedObjectCollection<Field> ConvertToLowerInvariant(NamedObjectCollection<Field> columnNames)
{
if (columnNames != null)
{
NamedObjectCollection<Field> columnNamesInLower = new NamedObjectCollection<Field>();
columnNamesInLower = columnNames;
int selectedIndex = 1;
DataRowView item;
string[] selectedViewFields = new string[lbxFields.SelectedItems.Count + 1];
selectedViewFields[0] = fieldName;
for (int i = 0; i < lbxFields.Items.Count; i++)
{
item = (DataRowView)lbxFields.Items[i];
if (lbxFields.GetSelected(i))
{
selectedViewFields[selectedIndex] = item[lbxFields.DisplayMember].ToString();
DataRow selectRow = item.Row;
selectedFields.Add(page.GetView().GetFieldById(int.Parse((selectRow[ColumnNames.FIELD_ID].ToString()))));
selectedIndex++;
}
}
return columnNamesInLower;
}
return columnNames;
}
/// <summary>
/// Set ShouldSort based on if the checkbox is checked
/// </summary>
private void SaveShouldSort()
{
if (ddlField != null)
{
ddlField.ShouldSort = !cbxSort.Checked;
}
}
#endregion Private Methods
#region Private Events
/// <summary>
/// Handles load event of the form
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void Codes_Load(object sender, System.EventArgs e)
{
DisplayData();
if (dgCodes.DataSource != null)
{
btnOK.Enabled = true;
}
dgCodes.Focus();
}
#endregion Private Events
#endregion Private Members
}
}
| |
//
// PlayerInterface.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright 2007-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Gui;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Database;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.MediaEngine;
using Banshee.Configuration;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Gui.Dialogs;
using Banshee.Widgets;
using Banshee.Collection.Gui;
using Banshee.Sources.Gui;
namespace Nereid
{
public class PlayerInterface : BaseClientWindow, IClientWindow, IDBusObjectName, IService, IDisposable, IHasSourceView
{
const string CONFIG_NAMESPACE = "player_window";
static readonly SchemaEntry<int> WidthSchema = WindowConfiguration.NewWidthSchema (CONFIG_NAMESPACE, 1024);
static readonly SchemaEntry<int> HeightSchema = WindowConfiguration.NewHeightSchema (CONFIG_NAMESPACE, 700);
static readonly SchemaEntry<int> XPosSchema = WindowConfiguration.NewXPosSchema (CONFIG_NAMESPACE);
static readonly SchemaEntry<int> YPosSchema = WindowConfiguration.NewYPosSchema (CONFIG_NAMESPACE);
static readonly SchemaEntry<bool> MaximizedSchema = WindowConfiguration.NewMaximizedSchema (CONFIG_NAMESPACE);
// Major Layout Components
private VBox primary_vbox;
private Table header_table;
private MainMenu main_menu;
private Toolbar header_toolbar;
private HBox footer_toolbar;
private HPaned views_pane;
private ViewContainer view_container;
private VBox source_box;
private Widget track_info_container;
private CoverArtDisplay cover_art_display;
private Widget cover_art_container;
private ConnectedSeekSlider seek_slider;
private TaskStatusIcon task_status;
private Alignment search_entry_align;
// Major Interaction Components
private SourceView source_view;
private CompositeTrackSourceContents composite_view;
private ObjectListSourceContents object_view;
private Label status_label;
public MainMenu MainMenu {
get { return main_menu; }
}
public Toolbar HeaderToolbar {
get { return header_toolbar; }
}
public Table HeaderTable {
get { return header_table; }
}
protected PlayerInterface (IntPtr ptr) : base (ptr)
{
}
private void SetSimple (bool simple)
{
var widgets = new Widget [] { main_menu, source_box, footer_toolbar, track_info_container };
foreach (var w in widgets.Where (w => w != null)) {
w.Visible = !simple;
}
}
public PlayerInterface () :
base (Catalog.GetString ("Banshee Media Player"),
new WindowConfiguration (WidthSchema, HeightSchema, XPosSchema, YPosSchema, MaximizedSchema))
{
}
protected override void Initialize ()
{
InitialShowPresent ();
}
private bool interface_constructed;
protected override void OnShown ()
{
if (interface_constructed) {
base.OnShown ();
return;
}
interface_constructed = true;
uint timer = Log.DebugTimerStart ();
BuildPrimaryLayout ();
ConnectEvents ();
ActionService.SourceActions.SourceView = this;
composite_view.TrackView.HasFocus = true;
Log.DebugTimerPrint (timer, "Constructed Nereid interface: {0}");
base.OnShown ();
}
#region System Overrides
protected override void Dispose (bool disposing)
{
lock (this) {
ServiceManager.SourceManager.ActiveSourceChanged -= OnActiveSourceChanged;
ServiceManager.SourceManager.SourceUpdated -= OnSourceUpdated;
if (disposing) {
Hide ();
}
base.Dispose (disposing);
}
}
#endregion
#region Interface Construction
private void BuildPrimaryLayout ()
{
primary_vbox = new VBox ();
BuildHeader ();
BuildViews ();
BuildFooter ();
search_entry_align = new Alignment (1.0f, 0.5f, 0f, 0f);
var box = new HBox () { Spacing = 2 };
var grabber = new GrabHandle ();
var search_entry = view_container.SearchEntry;
grabber.ControlWidthOf (search_entry, 150, 350, false);
int search_entry_width = SearchEntryWidth.Get ();
// -1 indicates that height should be preserved
search_entry.SetSizeRequest (search_entry_width, -1);
search_entry.SizeAllocated += (o, a) => {
SearchEntryWidth.Set (search_entry.Allocation.Width);
};
box.PackStart (grabber, false, false, 0);
box.PackStart (view_container.SearchEntry, false, false, 0);
search_entry_align.Child = box;
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/SearchEntry", search_entry_align);
search_entry_align.Visible = view_container.SearchSensitive = true;
search_entry_align.ShowAll ();
primary_vbox.Show ();
Add (primary_vbox);
}
private void BuildHeader ()
{
header_table = new Table (2, 2, false);
header_table.Show ();
header_table.Vexpand = false;
primary_vbox.PackStart (header_table, false, false, 0);
main_menu = new MainMenu ();
if (!PlatformDetection.IsMac) {
main_menu.Show ();
header_table.Attach (main_menu, 0, 1, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Shrink, 0, 0);
}
Alignment toolbar_alignment = new Alignment (0.0f, 0.0f, 1.0f, 1.0f);
toolbar_alignment.TopPadding = 3u;
toolbar_alignment.BottomPadding = 3u;
header_toolbar = (Toolbar)ActionService.UIManager.GetWidget ("/HeaderToolbar");
header_toolbar.ShowArrow = false;
header_toolbar.ToolbarStyle = ToolbarStyle.BothHoriz;
header_toolbar.Show ();
toolbar_alignment.Add (header_toolbar);
toolbar_alignment.Show ();
header_table.Attach (toolbar_alignment, 0, 2, 1, 2,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Shrink, 0, 0);
var next_button = new NextButton (ActionService);
next_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/NextArrowButton", next_button);
seek_slider = new ConnectedSeekSlider () { Resizable = ShowSeekSliderResizer.Get () };
seek_slider.SeekSlider.WidthRequest = SeekSliderWidth.Get ();
seek_slider.SeekSlider.SizeAllocated += (o, a) => {
SeekSliderWidth.Set (seek_slider.SeekSlider.Allocation.Width);
};
seek_slider.ShowAll ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/SeekSlider", seek_slider);
var track_info_display = new ClassicTrackInfoDisplay ();
track_info_display.Show ();
track_info_container = TrackInfoDisplay.GetEditable (track_info_display);
track_info_container.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/TrackInfoDisplay", track_info_container, true);
var volume_button = new ConnectedVolumeButton ();
volume_button.Show ();
ActionService.PopulateToolbarPlaceholder (header_toolbar, "/HeaderToolbar/VolumeButton", volume_button);
}
private void BuildViews ()
{
source_box = new VBox ();
views_pane = new HPaned ();
PersistentPaneController.Control (views_pane, SourceViewWidth);
view_container = new ViewContainer ();
source_view = new SourceView ();
composite_view = new CompositeTrackSourceContents ();
Container source_scroll;
Hyena.Widgets.ScrolledWindow window;
if (ApplicationContext.CommandLine.Contains ("no-smooth-scroll")) {
window = new Hyena.Widgets.ScrolledWindow ();
} else {
window = new Hyena.Widgets.SmoothScrolledWindow ();
}
window.Add (source_view);
source_scroll = window;
composite_view.TrackView.HeaderVisible = false;
view_container.Content = composite_view;
source_box.PackStart (source_scroll, true, true, 0);
source_box.PackStart (new UserJobTileHost (), false, false, 0);
UpdateCoverArtDisplay ();
source_view.SetSizeRequest (125, -1);
view_container.SetSizeRequest (425, -1);
views_pane.Pack1 (source_box, false, false);
views_pane.Pack2 (view_container, true, false);
source_box.ShowAll ();
view_container.Show ();
views_pane.Show ();
primary_vbox.PackStart (views_pane, true, true, 0);
}
private void UpdateCoverArtDisplay ()
{
if (ShowCoverArt.Get ()) {
if (cover_art_display == null && source_box != null) {
cover_art_display = new CoverArtDisplay () { Visible = true };
source_box.SizeAllocated += OnSourceBoxSizeAllocated;
cover_art_display.HeightRequest = SourceViewWidth.Get ();
source_box.PackStart (cover_art_container = TrackInfoDisplay.GetEditable (cover_art_display), false, false, 4);
source_box.ShowAll ();
}
} else if (cover_art_display != null) {
cover_art_display.Hide ();
source_box.Remove (cover_art_container);
source_box.SizeAllocated -= OnSourceBoxSizeAllocated;
cover_art_display.Dispose ();
cover_art_display = null;
}
}
private void OnSourceBoxSizeAllocated (object o, EventArgs args)
{
cover_art_display.HeightRequest = source_box.Allocation.Width;
}
private void BuildFooter ()
{
footer_toolbar = new HBox () { BorderWidth = 2 };
task_status = new Banshee.Gui.Widgets.TaskStatusIcon ();
EventBox status_event_box = new EventBox ();
status_event_box.ButtonPressEvent += OnStatusBoxButtonPress;
status_label = new Label ();
status_event_box.Add (status_label);
HBox status_hbox = new HBox (true, 0);
status_hbox.PackStart (status_event_box, false, false, 0);
Alignment status_align = new Alignment (0.5f, 0.5f, 1.0f, 1.0f);
status_align.Add (status_hbox);
RepeatActionButton repeat_button = new RepeatActionButton ();
repeat_button.SizeAllocated += delegate (object o, Gtk.SizeAllocatedArgs args) {
status_align.LeftPadding = (uint)args.Allocation.Width;
};
footer_toolbar.PackStart (task_status, false, false, 0);
footer_toolbar.PackStart (status_align, true, true, 0);
footer_toolbar.PackStart (repeat_button, false, false, 0);
footer_toolbar.ShowAll ();
primary_vbox.PackStart (footer_toolbar, false, true, 0);
}
private void OnStatusBoxButtonPress (object o, ButtonPressEventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source != null) {
source.CycleStatusFormat ();
UpdateSourceInformation ();
}
}
#endregion
#region Events and Logic Setup
protected override void ConnectEvents ()
{
base.ConnectEvents ();
// Service events
ServiceManager.SourceManager.ActiveSourceChanged += OnActiveSourceChanged;
ServiceManager.SourceManager.SourceUpdated += OnSourceUpdated;
ActionService.TrackActions ["SearchForSameArtistAction"].Activated += OnProgrammaticSearch;
ActionService.TrackActions ["SearchForSameAlbumAction"].Activated += OnProgrammaticSearch;
(ActionService.ViewActions ["ShowCoverArtAction"] as Gtk.ToggleAction).Active = ShowCoverArt.Get ();
ActionService.ViewActions ["ShowCoverArtAction"].Activated += (o, a) => {
ShowCoverArt.Set ((o as Gtk.ToggleAction).Active);
UpdateCoverArtDisplay ();
};
// UI events
view_container.SearchEntry.Changed += OnSearchEntryChanged;
// TODO: Check that this still works, it was using SizeRequested
views_pane.SizeAllocated += delegate {
SourceViewWidth.Set (views_pane.Position);
};
source_view.RowActivated += delegate {
Source source = ServiceManager.SourceManager.ActiveSource;
var handler = source.Properties.Get<System.Action> ("ActivationAction");
if (handler != null) {
handler ();
} else if (source is ITrackModelSource) {
ServiceManager.PlaybackController.NextSource = (ITrackModelSource)source;
// Allow changing the play source without stopping the current song by
// holding ctrl when activating a source. After the song is done, playback will
// continue from the new source.
if (GtkUtilities.NoImportantModifiersAreSet (Gdk.ModifierType.ControlMask)) {
ServiceManager.PlaybackController.Next ();
}
}
};
}
#endregion
#region Service Event Handlers
private void OnProgrammaticSearch (object o, EventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.Ready = true;
}
private Source previous_source = null;
private TrackListModel previous_track_model = null;
private void OnActiveSourceChanged (SourceEventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
Source source = ServiceManager.SourceManager.ActiveSource;
search_entry_align.Visible = view_container.SearchSensitive = source != null && source.CanSearch;
if (source == null) {
return;
}
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.CancelSearch ();
/* Translators: this is a verb (command), not a noun (things) */
var msg = source.Properties.Get<string> ("SearchEntryDescription") ?? Catalog.GetString ("Search");
view_container.SearchEntry.EmptyMessage = msg;
view_container.SearchEntry.TooltipText = msg;
if (source.FilterQuery != null) {
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.ActivateFilter ((int)source.FilterType);
}
if (view_container.Content != null) {
view_container.Content.ResetSource ();
}
if (previous_track_model != null) {
previous_track_model.Reloaded -= HandleTrackModelReloaded;
previous_track_model = null;
}
if (source is ITrackModelSource) {
previous_track_model = (source as ITrackModelSource).TrackModel;
previous_track_model.Reloaded += HandleTrackModelReloaded;
}
if (previous_source != null) {
previous_source.Properties.PropertyChanged -= OnSourcePropertyChanged;
}
previous_source = source;
previous_source.Properties.PropertyChanged += OnSourcePropertyChanged;
UpdateSourceContents (source);
UpdateSourceInformation ();
view_container.SearchEntry.Ready = true;
SetSimple (source.Properties.Get<bool> ("Nereid.SimpleUI"));
});
}
private void OnSourcePropertyChanged (object o, PropertyChangeEventArgs args)
{
switch (args.PropertyName) {
case "Nereid.SourceContents":
ThreadAssist.ProxyToMain (delegate {
UpdateSourceContents (previous_source);
});
break;
case "FilterQuery":
var source = ServiceManager.SourceManager.ActiveSource;
var search_entry = source.Properties.Get<SearchEntry> ("Nereid.SearchEntry") ?? view_container.SearchEntry;
if (!search_entry.HasFocus) {
ThreadAssist.ProxyToMain (delegate {
view_container.SearchEntry.Ready = false;
view_container.SearchEntry.Query = source.FilterQuery;
view_container.SearchEntry.Ready = true;
});
}
break;
case "Nereid.SimpleUI":
SetSimple (ServiceManager.SourceManager.ActiveSource.Properties.Get<bool> ("Nereid.SimpleUI"));
break;
}
}
private void UpdateSourceContents (Source source)
{
if (source == null) {
return;
}
// Connect the source models to the views if possible
ISourceContents contents = source.GetProperty<ISourceContents> ("Nereid.SourceContents",
source.GetInheritedProperty<bool> ("Nereid.SourceContentsPropagate"));
view_container.ClearHeaderWidget ();
view_container.ClearFooter ();
if (contents != null) {
if (view_container.Content != contents) {
view_container.Content = contents;
}
view_container.Content.SetSource (source);
view_container.Show ();
} else if (source is ITrackModelSource) {
view_container.Content = composite_view;
view_container.Content.SetSource (source);
view_container.Show ();
} else if (source is Hyena.Data.IObjectListModel) {
if (object_view == null) {
object_view = new ObjectListSourceContents ();
}
view_container.Content = object_view;
view_container.Content.SetSource (source);
view_container.Show ();
} else {
view_container.Hide ();
}
// Associate the view with the model
if (view_container.Visible && view_container.Content is ITrackModelSourceContents) {
ITrackModelSourceContents track_content = view_container.Content as ITrackModelSourceContents;
source.Properties.Set<IListView<TrackInfo>> ("Track.IListView", track_content.TrackView);
}
var title_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.TitleWidget");
if (title_widget != null) {
Hyena.Log.WarningFormat ("Nereid.SourceContents.TitleWidget is no longer used (from {0})", source.Name);
}
Widget header_widget = null;
if (source.Properties.Contains ("Nereid.SourceContents.HeaderWidget")) {
header_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.HeaderWidget");
}
if (header_widget != null) {
view_container.SetHeaderWidget (header_widget);
}
Widget footer_widget = null;
if (source.Properties.Contains ("Nereid.SourceContents.FooterWidget")) {
footer_widget = source.Properties.Get<Widget> ("Nereid.SourceContents.FooterWidget");
}
if (footer_widget != null) {
view_container.SetFooter (footer_widget);
}
}
private void OnSourceUpdated (SourceEventArgs args)
{
if (args.Source == ServiceManager.SourceManager.ActiveSource) {
ThreadAssist.ProxyToMain (delegate {
UpdateSourceInformation ();
});
}
}
#endregion
#region UI Event Handlers
private void OnSearchEntryChanged (object o, EventArgs args)
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null)
return;
source.FilterType = (TrackFilterType)view_container.SearchEntry.ActiveFilterID;
source.FilterQuery = view_container.SearchEntry.Query;
}
#endregion
#region Implement Interfaces
// IHasSourceView
public Source HighlightedSource {
get { return source_view.HighlightedSource; }
}
public void BeginRenameSource (Source source)
{
source_view.BeginRenameSource (source);
}
public void ResetHighlight ()
{
source_view.ResetHighlight ();
}
public override Box ViewContainer {
get { return view_container; }
}
#endregion
#region Gtk.Window Overrides
private bool accel_group_active = true;
private void OnEntryFocusOutEvent (object o, FocusOutEventArgs args)
{
if (!accel_group_active) {
AddAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = true;
}
(o as Widget).FocusOutEvent -= OnEntryFocusOutEvent;
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
bool focus_search = false;
bool disable_keybindings = Focus is Gtk.Entry;
if (!disable_keybindings) {
var widget = Focus;
while (widget != null) {
if (widget is IDisableKeybindings) {
disable_keybindings = true;
break;
}
widget = widget.Parent;
}
}
// Don't disable them if ctrl is pressed, unless ctrl-a is pressed
if (evnt.Key != Gdk.Key.a) {
disable_keybindings &= (evnt.State & Gdk.ModifierType.ControlMask) == 0 &&
evnt.Key != Gdk.Key.Control_L && evnt.Key != Gdk.Key.Control_R;
}
if (disable_keybindings) {
if (accel_group_active) {
RemoveAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = false;
// Reinstate the AccelGroup as soon as the focus leaves the entry
Focus.FocusOutEvent += OnEntryFocusOutEvent;
}
} else {
if (!accel_group_active) {
AddAccelGroup (ActionService.UIManager.AccelGroup);
accel_group_active = true;
}
}
switch (evnt.Key) {
case Gdk.Key.f:
if (Gdk.ModifierType.ControlMask == (evnt.State & Gdk.ModifierType.ControlMask)) {
focus_search = true;
}
break;
case Gdk.Key.S:
case Gdk.Key.s:
case Gdk.Key.slash:
if (!disable_keybindings) {
focus_search = true;
}
break;
case Gdk.Key.F3:
focus_search = true;
break;
case Gdk.Key.F11:
ActionService.ViewActions["FullScreenAction"].Activate ();
break;
}
// The source might have its own custom search entry - use it if so
var src = ServiceManager.SourceManager.ActiveSource;
var search_entry = src.Properties.Get<SearchEntry> ("Nereid.SearchEntry") ?? view_container.SearchEntry;
if (focus_search && search_entry.Visible && !source_view.EditingRow) {
search_entry.GrabFocus ();
search_entry.HasFocus = true;
return true;
}
return base.OnKeyPressEvent (evnt);
}
#endregion
#region Popup Status Bar
#if false
private Gdk.FilterReturn OnGdkEventFilter (IntPtr xevent, Gdk.Event gdkevent)
{
if (!IsRealized || !IsMapped) {
return Gdk.FilterReturn.Continue;
}
Gdk.ModifierType mask;
int x, y;
GdkWindow.GetPointer (out x, out y, out mask);
return Gdk.FilterReturn.Continue;
}
#endif
#endregion
#region Helper Functions
private void HandleTrackModelReloaded (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (UpdateSourceInformation);
}
private void UpdateSourceInformation ()
{
if (status_label == null) {
return;
}
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null) {
status_label.Text = String.Empty;
return;
}
status_label.Text = source.GetStatusText ();
// We need a bit longer delay between query character typed to search initiated
// when the library is sufficiently big; see bgo #540835
bool long_delay = source.FilteredCount > 6000 || (source.Parent ?? source).Count > 12000;
view_container.SearchEntry.ChangeTimeoutMs = long_delay ? (uint)250 : (uint)25;
}
#endregion
#region Configuration Schemas
public static readonly SchemaEntry<int> SourceViewWidth = new SchemaEntry<int> (
"player_window", "source_view_width",
175,
"Source View Width",
"Width of Source View Column."
);
public static readonly SchemaEntry<bool> ShowCoverArt = new SchemaEntry<bool> (
"player_window", "show_cover_art",
false,
"Show cover art",
"Show cover art below source view if available"
);
private static readonly SchemaEntry<bool> ShowSeekSliderResizer = new SchemaEntry<bool> (
"player_window", "show_seek_slider_resizer",
true, "Show seek slider resize grip", ""
);
private static readonly SchemaEntry<int> SeekSliderWidth = new SchemaEntry<int> (
"player_window", "seek_slider_width",
175, "Width of seek slider in px", ""
);
private static readonly SchemaEntry<int> SearchEntryWidth = new SchemaEntry<int> (
"player_window", "search_entry_width",
200, "Width of search entry element in px", ""
);
#endregion
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
string IDBusObjectName.ExportObjectName {
get { return "ClientWindow"; }
}
string IService.ServiceName {
get { return "NereidPlayerInterface"; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace System.ComponentModel
{
/// <summary>
/// ReflectPropertyDescriptor defines a property. Properties are the main way that a user can
/// set up the state of a component.
/// The ReflectPropertyDescriptor class takes a component class that the property lives on,
/// a property name, the type of the property, and various attributes for the
/// property.
/// For a property named XXX of type YYY, the associated component class is
/// required to implement two methods of the following
/// form:
///
/// <code>
/// public YYY GetXXX();
/// public void SetXXX(YYY value);
/// </code>
/// The component class can optionally implement two additional methods of
/// the following form:
/// <code>
/// public boolean ShouldSerializeXXX();
/// public void ResetXXX();
/// </code>
/// These methods deal with a property's default value. The ShouldSerializeXXX()
/// method returns true if the current value of the XXX property is different
/// than it's default value, so that it should be persisted out. The ResetXXX()
/// method resets the XXX property to its default value. If the ReflectPropertyDescriptor
/// includes the default value of the property (using the DefaultValueAttribute),
/// the ShouldSerializeXXX() and ResetXXX() methods are ignored.
/// If the ReflectPropertyDescriptor includes a reference to an editor
/// then that value editor will be used to
/// edit the property. Otherwise, a system-provided editor will be used.
/// Various attributes can be passed to the ReflectPropertyDescriptor, as are described in
/// Attribute.
/// ReflectPropertyDescriptors can be obtained by a user programmatically through the
/// ComponentManager.
/// </summary>
internal sealed class ReflectPropertyDescriptor : PropertyDescriptor
{
private static readonly object s_noValue = new object();
private static readonly int s_bitDefaultValueQueried = InterlockedBitVector32.CreateMask();
private static readonly int s_bitGetQueried = InterlockedBitVector32.CreateMask(s_bitDefaultValueQueried);
private static readonly int s_bitSetQueried = InterlockedBitVector32.CreateMask(s_bitGetQueried);
private static readonly int s_bitShouldSerializeQueried = InterlockedBitVector32.CreateMask(s_bitSetQueried);
private static readonly int s_bitResetQueried = InterlockedBitVector32.CreateMask(s_bitShouldSerializeQueried);
private static readonly int s_bitChangedQueried = InterlockedBitVector32.CreateMask(s_bitResetQueried);
private static readonly int s_bitIPropChangedQueried = InterlockedBitVector32.CreateMask(s_bitChangedQueried);
private static readonly int s_bitReadOnlyChecked = InterlockedBitVector32.CreateMask(s_bitIPropChangedQueried);
private static readonly int s_bitAmbientValueQueried = InterlockedBitVector32.CreateMask(s_bitReadOnlyChecked);
private static readonly int s_bitSetOnDemand = InterlockedBitVector32.CreateMask(s_bitAmbientValueQueried);
private InterlockedBitVector32 _state; // Contains the state bits for this proeprty descriptor.
private readonly Type _componentClass; // used to determine if we should all on us or on the designer
private readonly Type _type; // the data type of the property
private object _defaultValue; // the default value of the property (or noValue)
private object _ambientValue; // the ambient value of the property (or noValue)
private PropertyInfo _propInfo; // the property info
private MethodInfo _getMethod; // the property get method
private MethodInfo _setMethod; // the property set method
private MethodInfo _shouldSerializeMethod; // the should serialize method
private MethodInfo _resetMethod; // the reset property method
private EventDescriptor _realChangedEvent; // <propertyname>Changed event handler on object
private EventDescriptor _realIPropChangedEvent; // INotifyPropertyChanged.PropertyChanged event handler on object
private readonly Type _receiverType; // Only set if we are an extender
/// <summary>
/// The main constructor for ReflectPropertyDescriptors.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Attribute[] attributes)
: base(name, attributes)
{
Debug.WriteLine($"Creating ReflectPropertyDescriptor for {componentClass?.FullName}.{name}");
try
{
if (type == null)
{
Debug.WriteLine($"type == null, name == {name}");
throw new ArgumentException(SR.Format(SR.ErrorInvalidPropertyType, name));
}
if (componentClass == null)
{
Debug.WriteLine($"componentClass == null, name == {name}");
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
_type = type;
_componentClass = componentClass;
}
catch (Exception t)
{
Debug.Fail($"Property '{name}' on component {componentClass.FullName} failed to init.");
Debug.Fail(t.ToString());
throw;
}
}
/// <summary>
/// A constructor for ReflectPropertyDescriptors that have no attributes.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs)
{
_propInfo = propInfo;
_getMethod = getMethod;
_setMethod = setMethod;
if (getMethod != null && propInfo != null && setMethod == null)
_state.DangerousSet(s_bitGetQueried | s_bitSetOnDemand, true);
else
_state.DangerousSet(s_bitGetQueried | s_bitSetQueried, true);
}
/// <summary>
/// A constructor for ReflectPropertyDescriptors that creates an extender property.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs)
{
_receiverType = receiverType;
_getMethod = getMethod;
_setMethod = setMethod;
_state.DangerousSet(s_bitGetQueried | s_bitSetQueried, true);
}
/// <summary>
/// This constructor takes an existing ReflectPropertyDescriptor and modifies it by merging in the
/// passed-in attributes.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes)
: base(oldReflectPropertyDescriptor, attributes)
{
_componentClass = componentClass;
_type = oldReflectPropertyDescriptor.PropertyType;
if (componentClass == null)
{
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
// If the classes are the same, we can potentially optimize the method fetch because
// the old property descriptor may already have it.
if (oldReflectPropertyDescriptor is ReflectPropertyDescriptor oldProp)
{
if (oldProp.ComponentType == componentClass)
{
_propInfo = oldProp._propInfo;
_getMethod = oldProp._getMethod;
_setMethod = oldProp._setMethod;
_shouldSerializeMethod = oldProp._shouldSerializeMethod;
_resetMethod = oldProp._resetMethod;
_defaultValue = oldProp._defaultValue;
_ambientValue = oldProp._ambientValue;
_state = oldProp._state;
}
// Now we must figure out what to do with our default value. First, check to see
// if the caller has provided an new default value attribute. If so, use it. Otherwise,
// just let it be and it will be picked up on demand.
//
if (attributes != null)
{
foreach (Attribute a in attributes)
{
if (a is DefaultValueAttribute dva)
{
_defaultValue = dva.Value;
// Default values for enums are often stored as their underlying integer type:
if (_defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == _defaultValue.GetType())
{
_defaultValue = Enum.ToObject(PropertyType, _defaultValue);
}
_state.DangerousSet(s_bitDefaultValueQueried, true);
}
else if (a is AmbientValueAttribute ava)
{
_ambientValue = ava.Value;
_state.DangerousSet(s_bitAmbientValueQueried, true);
}
}
}
}
}
/// <summary>
/// Retrieves the ambient value for this property.
/// </summary>
private object AmbientValue
{
get
{
if (!_state[s_bitAmbientValueQueried])
{
Attribute a = Attributes[typeof(AmbientValueAttribute)];
if (a != null)
{
_ambientValue = ((AmbientValueAttribute)a).Value;
}
else
{
_ambientValue = s_noValue;
}
_state[s_bitAmbientValueQueried] = true;
}
return _ambientValue;
}
}
/// <summary>
/// The EventDescriptor for the "{propertyname}Changed" event on the component, or null if there isn't one for this property.
/// </summary>
private EventDescriptor ChangedEventValue
{
get
{
if (!_state[s_bitChangedQueried])
{
_realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[Name + "Changed"];
_state[s_bitChangedQueried] = true;
}
return _realChangedEvent;
}
}
/// <summary>
/// The EventDescriptor for the INotifyPropertyChanged.PropertyChanged event on the component, or null if there isn't one for this property.
/// </summary>
private EventDescriptor IPropChangedEventValue
{
get
{
if (!_state[s_bitIPropChangedQueried])
{
if (typeof(INotifyPropertyChanged).IsAssignableFrom(ComponentType))
{
_realIPropChangedEvent = TypeDescriptor.GetEvents(typeof(INotifyPropertyChanged))["PropertyChanged"];
}
_state[s_bitIPropChangedQueried] = true;
}
return _realIPropChangedEvent;
}
}
/// <summary>
/// Retrieves the type of the component this PropertyDescriptor is bound to.
/// </summary>
public override Type ComponentType => _componentClass;
/// <summary>
/// Retrieves the default value for this property.
/// </summary>
private object DefaultValue
{
get
{
if (!_state[s_bitDefaultValueQueried])
{
Attribute a = Attributes[typeof(DefaultValueAttribute)];
if (a != null)
{
// Default values for enums are often stored as their underlying integer type:
object defaultValue = ((DefaultValueAttribute)a).Value;
bool storedAsUnderlyingType = defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType();
_defaultValue = storedAsUnderlyingType ?
Enum.ToObject(PropertyType, _defaultValue) :
defaultValue;
}
else
{
_defaultValue = s_noValue;
}
_state[s_bitDefaultValueQueried] = true;
}
return _defaultValue;
}
}
/// <summary>
/// The GetMethod for this property
/// </summary>
private MethodInfo GetMethodValue
{
get
{
if (!_state[s_bitGetQueried])
{
if (_receiverType == null)
{
if (_propInfo == null)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
_propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Array.Empty<Type>(), Array.Empty<ParameterModifier>());
}
if (_propInfo != null)
{
_getMethod = _propInfo.GetGetMethod(nonPublic: true);
}
if (_getMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name));
}
}
else
{
_getMethod = FindMethod(_componentClass, "Get" + Name, new Type[] { _receiverType }, _type);
if (_getMethod == null)
{
throw new ArgumentException(SR.Format(SR.ErrorMissingPropertyAccessors, Name));
}
}
_state[s_bitGetQueried] = true;
}
return _getMethod;
}
}
/// <summary>
/// Determines if this property is an extender property.
/// </summary>
private bool IsExtender => (_receiverType != null);
/// <summary>
/// Indicates whether this property is read only.
/// </summary>
public override bool IsReadOnly => SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly;
/// <summary>
/// Retrieves the type of the property.
/// </summary>
public override Type PropertyType => _type;
/// <summary>
/// Access to the reset method, if one exists for this property.
/// </summary>
private MethodInfo ResetMethodValue
{
get
{
if (!_state[s_bitResetQueried])
{
Type[] args;
if (_receiverType == null)
{
args = Array.Empty<Type>();
}
else
{
args = new Type[] { _receiverType };
}
_resetMethod = FindMethod(_componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false);
_state[s_bitResetQueried] = true;
}
return _resetMethod;
}
}
/// <summary>
/// Accessor for the set method
/// </summary>
private MethodInfo SetMethodValue
{
get
{
if (!_state[s_bitSetQueried] && _state[s_bitSetOnDemand])
{
string name = _propInfo.Name;
if (_setMethod == null)
{
for (Type t = ComponentType.BaseType; t != null && t != typeof(object); t = t.BaseType)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo p = t.GetProperty(name, bindingFlags, binder: null, PropertyType, Array.Empty<Type>(), null);
if (p != null)
{
_setMethod = p.GetSetMethod(nonPublic: false);
if (_setMethod != null)
{
break;
}
}
}
}
_state[s_bitSetQueried] = true;
}
if (!_state[s_bitSetQueried])
{
if (_receiverType == null)
{
if (_propInfo == null)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
_propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Array.Empty<Type>(), Array.Empty<ParameterModifier>());
}
if (_propInfo != null)
{
_setMethod = _propInfo.GetSetMethod(nonPublic: true);
}
}
else
{
_setMethod = FindMethod(_componentClass, "Set" + Name,
new Type[] { _receiverType, _type }, typeof(void));
}
_state[s_bitSetQueried] = true;
}
return _setMethod;
}
}
/// <summary>
/// Accessor for the ShouldSerialize method.
/// </summary>
private MethodInfo ShouldSerializeMethodValue
{
get
{
if (!_state[s_bitShouldSerializeQueried])
{
Type[] args;
if (_receiverType == null)
{
args = Array.Empty<Type>();
}
else
{
args = new Type[] { _receiverType };
}
_shouldSerializeMethod = FindMethod(_componentClass, "ShouldSerialize" + Name, args, typeof(bool), publicOnly: false);
_state[s_bitShouldSerializeQueried] = true;
}
return _shouldSerializeMethod;
}
}
/// <summary>
/// Allows interested objects to be notified when this property changes.
/// </summary>
public override void AddValueChanged(object component, EventHandler handler)
{
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
// If there's an event called <propertyname>Changed, hook the caller's handler directly up to that on the component
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler))
{
changedEvent.AddEventHandler(component, handler);
}
// Otherwise let the base class add the handler to its ValueChanged event for this component
else
{
// Special case: If this will be the FIRST handler added for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null)
{
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
iPropChangedEvent?.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
base.AddValueChanged(component, handler);
}
}
internal bool ExtenderCanResetValue(IExtenderProvider provider, object component)
{
if (DefaultValue != s_noValue)
{
return !Equals(ExtenderGetValue(provider, component), _defaultValue);
}
MethodInfo reset = ResetMethodValue;
if (reset != null)
{
MethodInfo shouldSerialize = ShouldSerializeMethodValue;
if (shouldSerialize != null)
{
try
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
return (bool)shouldSerialize.Invoke(provider, new object[] { component });
}
catch { }
}
return true;
}
return false;
}
internal Type ExtenderGetReceiverType() => _receiverType;
internal Type ExtenderGetType(IExtenderProvider provider) => PropertyType;
internal object ExtenderGetValue(IExtenderProvider provider, object component)
{
if (provider != null)
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
return GetMethodValue.Invoke(provider, new object[] { component });
}
return null;
}
internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc)
{
if (DefaultValue != s_noValue)
{
ExtenderSetValue(provider, component, DefaultValue, notifyDesc);
}
else if (AmbientValue != s_noValue)
{
ExtenderSetValue(provider, component, AmbientValue, notifyDesc);
}
else if (ResetMethodValue != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!ComponentModelSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
if (changeService != null)
{
oldValue = ExtenderGetValue(provider, component);
try
{
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (ResetMethodValue != null)
{
ResetMethodValue.Invoke(provider, new object[] { component });
// Now notify the change service that the change was successful.
if (changeService != null)
{
newValue = ExtenderGetValue(provider, component);
changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue);
}
}
}
}
internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc)
{
if (provider != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
// Announce that we are about to change this component
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!ComponentModelSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
if (changeService != null)
{
oldValue = ExtenderGetValue(provider, component);
try
{
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (SetMethodValue != null)
{
SetMethodValue.Invoke(provider, new object[] { component, value });
// Now notify the change service that the change was successful.
changeService?.OnComponentChanged(component, notifyDesc, oldValue, value);
}
}
}
internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component)
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (IsReadOnly)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component });
}
catch { }
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == s_noValue)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component });
}
catch { }
}
return true;
}
return !Equals(DefaultValue, ExtenderGetValue(provider, component));
}
/// <summary>
/// Indicates whether reset will change the value of the component. If there
/// is a DefaultValueAttribute, then this will return true if getValue returns
/// something different than the default value. If there is a reset method and
/// a ShouldSerialize method, this will return what ShouldSerialize returns.
/// If there is just a reset method, this always returns true. If none of these
/// cases apply, this returns false.
/// </summary>
public override bool CanResetValue(object component)
{
if (IsExtender || IsReadOnly)
{
return false;
}
if (DefaultValue != s_noValue)
{
return !Equals(GetValue(component), DefaultValue);
}
if (ResetMethodValue != null)
{
if (ShouldSerializeMethodValue != null)
{
component = GetInvocationTarget(_componentClass, component);
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return true;
}
if (AmbientValue != s_noValue)
{
return ShouldSerializeValue(component);
}
return false;
}
protected override void FillAttributes(IList attributes)
{
Debug.Assert(_componentClass != null, "Must have a component class for FillAttributes");
//
// The order that we fill in attributes is critical. The list of attributes will be
// filtered so that matching attributes at the end of the list replace earlier matches
// (last one in wins). Therefore, the four categories of attributes we add must be
// added as follows:
//
// 1. Attributes of the property type. These are the lowest level and should be
// overwritten by any newer attributes.
//
// 2. Attributes obtained from any SpecificTypeAttribute. These supercede attributes
// for the property type.
//
// 3. Attributes of the property itself, from base class to most derived. This way
// derived class attributes replace base class attributes.
//
// 4. Attributes from our base MemberDescriptor. While this seems opposite of what
// we want, MemberDescriptor only has attributes if someone passed in a new
// set in the constructor. Therefore, these attributes always
// supercede existing values.
//
// We need to include attributes from the type of the property.
foreach (Attribute typeAttr in TypeDescriptor.GetAttributes(PropertyType))
{
attributes.Add(typeAttr);
}
// NOTE : Must look at method OR property, to handle the case of Extender properties...
//
// Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-acquire
// : the property info, rather than use the one we have cached. The one we have cached
// : may ave come from a base class, meaning we will request custom metadata for this
// : class twice.
Type currentReflectType = _componentClass;
int depth = 0;
// First, calculate the depth of the object hierarchy. We do this so we can do a single
// object create for an array of attributes.
while (currentReflectType != null && currentReflectType != typeof(object))
{
depth++;
currentReflectType = currentReflectType.BaseType;
}
// Now build up an array in reverse order
if (depth > 0)
{
currentReflectType = _componentClass;
Attribute[][] attributeStack = new Attribute[depth][];
while (currentReflectType != null && currentReflectType != typeof(object))
{
MemberInfo memberInfo = null;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;
// Fill in our member info so we can get at the custom attributes.
if (IsExtender)
{
//receiverType is used to avoid ambitiousness when there are overloads for the get method.
memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags, binder: null, new Type[] { _receiverType }, modifiers: null);
}
else
{
memberInfo = currentReflectType.GetProperty(Name, bindingFlags, binder: null, PropertyType, Array.Empty<Type>(), Array.Empty<ParameterModifier>());
}
// Get custom attributes for the member info.
if (memberInfo != null)
{
attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo);
}
// Ready for the next loop iteration.
currentReflectType = currentReflectType.BaseType;
}
// Look in the attribute stack for AttributeProviders
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
if (attr is AttributeProviderAttribute sta)
{
Type specificType = Type.GetType(sta.TypeName);
if (specificType != null)
{
Attribute[] stAttrs = null;
if (!string.IsNullOrEmpty(sta.PropertyName))
{
MemberInfo[] milist = specificType.GetMember(sta.PropertyName);
if (milist.Length > 0 && milist[0] != null)
{
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]);
}
}
else
{
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType);
}
if (stAttrs != null)
{
foreach (Attribute stAttr in stAttrs)
{
attributes.Add(stAttr);
}
}
}
}
}
}
}
// Now trawl the attribute stack so that we add attributes
// from base class to most derived.
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
attributes.Add(attr);
}
}
}
}
// Include the base attributes. These override all attributes on the actual
// property, so we want to add them last.
base.FillAttributes(attributes);
// Finally, override any form of ReadOnlyAttribute.
if (SetMethodValue == null)
{
attributes.Add(ReadOnlyAttribute.Yes);
}
}
/// <summary>
/// Retrieves the current value of the property on component,
/// invoking the getXXX method. An exception in the getXXX
/// method will pass through.
/// </summary>
public override object GetValue(object component)
{
Debug.WriteLine($"[{Name}]: GetValue({component?.GetType().Name ?? "(null)"})");
if (IsExtender)
{
Debug.WriteLine($"[{Name}]: ---> returning: null");
return null;
}
Debug.Assert(component != null, "GetValue must be given a component");
if (component != null)
{
component = GetInvocationTarget(_componentClass, component);
try
{
return GetMethodValue.Invoke(component, null);
}
catch (Exception t)
{
string name = null;
IComponent comp = component as IComponent;
ISite site = comp?.Site;
if (site?.Name != null)
{
name = site.Name;
}
if (name == null)
{
name = component.GetType().FullName;
}
if (t is TargetInvocationException)
{
t = t.InnerException;
}
string message = t.Message ?? t.GetType().Name;
throw new TargetInvocationException(SR.Format(SR.ErrorPropertyAccessorException, Name, name, message), t);
}
}
Debug.WriteLine("[" + Name + "]: ---> returning: null");
return null;
}
/// <summary>
/// Handles INotifyPropertyChanged.PropertyChange events from components.
/// If event pertains to this property, issue a ValueChanged event.
/// </summary>
internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e)
{
if (string.IsNullOrEmpty(e.PropertyName) ||
string.Compare(e.PropertyName, Name, true, CultureInfo.InvariantCulture) == 0)
{
OnValueChanged(component, e);
}
}
/// <summary>
/// This should be called by your property descriptor implementation
/// when the property value has changed.
/// </summary>
protected override void OnValueChanged(object component, EventArgs e)
{
if (_state[s_bitChangedQueried] && _realChangedEvent == null)
{
base.OnValueChanged(component, e);
}
}
/// <summary>
/// Allows interested objects to be notified when this property changes.
/// </summary>
public override void RemoveValueChanged(object component, EventHandler handler)
{
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
// If there's an event called <propertyname>Changed, we hooked the caller's
// handler directly up to that on the component, so remove it now.
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler))
{
changedEvent.RemoveEventHandler(component, handler);
}
// Otherwise the base class added the handler to its ValueChanged
// event for this component, so let the base class remove it now.
else
{
base.RemoveValueChanged(component, handler);
// Special case: If that was the LAST handler removed for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null)
{
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
iPropChangedEvent?.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
}
}
/// <summary>
/// Will reset the default value for this property on the component. If
/// there was a default value passed in as a DefaultValueAttribute, that
/// value will be set as the value of the property on the component. If
/// there was no default value passed in, a ResetXXX method will be looked
/// for. If one is found, it will be invoked. If one is not found, this
/// is a nop.
/// </summary>
public override void ResetValue(object component)
{
object invokee = GetInvocationTarget(_componentClass, component);
if (DefaultValue != s_noValue)
{
SetValue(component, DefaultValue);
}
else if (AmbientValue != s_noValue)
{
SetValue(component, AmbientValue);
}
else if (ResetMethodValue != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!ComponentModelSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
if (changeService != null)
{
// invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method
oldValue = GetMethodValue.Invoke(invokee, null);
try
{
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
if (ResetMethodValue != null)
{
ResetMethodValue.Invoke(invokee, null);
// Now notify the change service that the change was successful.
if (changeService != null)
{
newValue = GetMethodValue.Invoke(invokee, null);
changeService.OnComponentChanged(component, this, oldValue, newValue);
}
}
}
}
/// <summary>
/// This will set value to be the new value of this property on the
/// component by invoking the setXXX method on the component. If the
/// value specified is invalid, the component should throw an exception
/// which will be passed up. The component designer should design the
/// property so that getXXX following a setXXX should return the value
/// passed in if no exception was thrown in the setXXX call.
/// </summary>
public override void SetValue(object component, object value)
{
Debug.WriteLine($"[{Name}]: SetValue({component?.GetType().Name ?? "(null)"}, {value?.GetType().Name ?? "(null)"})");
if (component != null)
{
ISite site = GetSite(component);
object oldValue = null;
object invokee = GetInvocationTarget(_componentClass, component);
if (!IsReadOnly)
{
IComponentChangeService changeService = null;
// Announce that we are about to change this component
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!ComponentModelSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
if (changeService != null)
{
oldValue = GetMethodValue.Invoke(invokee, null);
try
{
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
try
{
try
{
SetMethodValue.Invoke(invokee, new object[] { value });
OnValueChanged(invokee, EventArgs.Empty);
}
catch (Exception t)
{
// Give ourselves a chance to unwind properly before rethrowing the exception.
//
value = oldValue;
// If there was a problem setting the controls property then we get:
// ArgumentException (from properties set method)
// ==> Becomes inner exception of TargetInvocationException
// ==> caught here
if (t is TargetInvocationException && t.InnerException != null)
{
// Propagate the original exception up
throw t.InnerException;
}
else
{
throw t;
}
}
}
finally
{
// Now notify the change service that the change was successful.
changeService?.OnComponentChanged(component, this, oldValue, value);
}
}
}
}
/// <summary>
/// Indicates whether the value of this property needs to be persisted. In
/// other words, it indicates whether the state of the property is distinct
/// from when the component is first instantiated. If there is a default
/// value specified in this ReflectPropertyDescriptor, it will be compared against the
/// property's current value to determine this. If there isn't, the
/// ShouldSerializeXXX method is looked for and invoked if found. If both
/// these routes fail, true will be returned.
///
/// If this returns false, a tool should not persist this property's value.
/// </summary>
public override bool ShouldSerializeValue(object component)
{
component = GetInvocationTarget(_componentClass, component);
if (IsReadOnly)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == s_noValue)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return true;
}
return !Equals(DefaultValue, GetValue(component));
}
/// <summary>
/// Indicates whether value change notifications for this property may originate from outside the property
/// descriptor, such as from the component itself (value=true), or whether notifications will only originate
/// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may
/// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property.
/// </summary>
public override bool SupportsChangeEvents => IPropChangedEventValue != null || ChangedEventValue != null;
}
}
| |
using System;
using System.Runtime.InteropServices;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
namespace Godot
{
/// <summary>
/// A unit quaternion used for representing 3D rotations.
/// Quaternions need to be normalized to be used for rotation.
///
/// It is similar to Basis, which implements matrix representation of
/// rotations, and can be parametrized using both an axis-angle pair
/// or Euler angles. Basis stores rotation, scale, and shearing,
/// while Quat only stores rotation.
///
/// Due to its compactness and the way it is stored in memory, certain
/// operations (obtaining axis-angle and performing SLERP, in particular)
/// are more efficient and robust against floating-point errors.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quat : IEquatable<Quat>
{
/// <summary>
/// X component of the quaternion (imaginary `i` axis part).
/// Quaternion components should usually not be manipulated directly.
/// </summary>
public real_t x;
/// <summary>
/// Y component of the quaternion (imaginary `j` axis part).
/// Quaternion components should usually not be manipulated directly.
/// </summary>
public real_t y;
/// <summary>
/// Z component of the quaternion (imaginary `k` axis part).
/// Quaternion components should usually not be manipulated directly.
/// </summary>
public real_t z;
/// <summary>
/// W component of the quaternion (real part).
/// Quaternion components should usually not be manipulated directly.
/// </summary>
public real_t w;
/// <summary>
/// Access quaternion components using their index.
/// </summary>
/// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`, `[3]` is equivalent to `.w`.</value>
public real_t this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
case 3:
return w;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
case 3:
w = value;
break;
default:
throw new IndexOutOfRangeException();
}
}
}
/// <summary>
/// Returns the length (magnitude) of the quaternion.
/// </summary>
/// <value>Equivalent to `Mathf.Sqrt(LengthSquared)`.</value>
public real_t Length
{
get { return Mathf.Sqrt(LengthSquared); }
}
/// <summary>
/// Returns the squared length (squared magnitude) of the quaternion.
/// This method runs faster than <see cref="Length"/>, so prefer it if
/// you need to compare quaternions or need the squared length for some formula.
/// </summary>
/// <value>Equivalent to `Dot(this)`.</value>
public real_t LengthSquared
{
get { return Dot(this); }
}
/// <summary>
/// Performs a cubic spherical interpolation between quaternions `preA`,
/// this vector, `b`, and `postB`, by the given amount `t`.
/// </summary>
/// <param name="b">The destination quaternion.</param>
/// <param name="preA">A quaternion before this quaternion.</param>
/// <param name="postB">A quaternion after `b`.</param>
/// <param name="t">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The interpolated quaternion.</returns>
public Quat CubicSlerp(Quat b, Quat preA, Quat postB, real_t t)
{
real_t t2 = (1.0f - t) * t * 2f;
Quat sp = Slerp(b, t);
Quat sq = preA.Slerpni(postB, t);
return sp.Slerpni(sq, t2);
}
/// <summary>
/// Returns the dot product of two quaternions.
/// </summary>
/// <param name="b">The other quaternion.</param>
/// <returns>The dot product.</returns>
public real_t Dot(Quat b)
{
return x * b.x + y * b.y + z * b.z + w * b.w;
}
/// <summary>
/// Returns Euler angles (in the YXZ convention: when decomposing,
/// first Z, then X, and Y last) corresponding to the rotation
/// represented by the unit quaternion. Returned vector contains
/// the rotation angles in the format (X angle, Y angle, Z angle).
/// </summary>
/// <returns>The Euler angle representation of this quaternion.</returns>
public Vector3 GetEuler()
{
#if DEBUG
if (!IsNormalized())
{
throw new InvalidOperationException("Quat is not normalized");
}
#endif
var basis = new Basis(this);
return basis.GetEuler();
}
/// <summary>
/// Returns the inverse of the quaternion.
/// </summary>
/// <returns>The inverse quaternion.</returns>
public Quat Inverse()
{
#if DEBUG
if (!IsNormalized())
{
throw new InvalidOperationException("Quat is not normalized");
}
#endif
return new Quat(-x, -y, -z, w);
}
/// <summary>
/// Returns whether the quaternion is normalized or not.
/// </summary>
/// <returns>A bool for whether the quaternion is normalized or not.</returns>
public bool IsNormalized()
{
return Mathf.Abs(LengthSquared - 1) <= Mathf.Epsilon;
}
/// <summary>
/// Returns a copy of the quaternion, normalized to unit length.
/// </summary>
/// <returns>The normalized quaternion.</returns>
public Quat Normalized()
{
return this / Length;
}
/// <summary>
/// Returns the result of the spherical linear interpolation between
/// this quaternion and `to` by amount `weight`.
///
/// Note: Both quaternions must be normalized.
/// </summary>
/// <param name="to">The destination quaternion for interpolation. Must be normalized.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting quaternion of the interpolation.</returns>
public Quat Slerp(Quat to, real_t weight)
{
#if DEBUG
if (!IsNormalized())
{
throw new InvalidOperationException("Quat is not normalized");
}
if (!to.IsNormalized())
{
throw new ArgumentException("Argument is not normalized", nameof(to));
}
#endif
// Calculate cosine.
real_t cosom = x * to.x + y * to.y + z * to.z + w * to.w;
var to1 = new Quat();
// Adjust signs if necessary.
if (cosom < 0.0)
{
cosom = -cosom;
to1.x = -to.x;
to1.y = -to.y;
to1.z = -to.z;
to1.w = -to.w;
}
else
{
to1.x = to.x;
to1.y = to.y;
to1.z = to.z;
to1.w = to.w;
}
real_t sinom, scale0, scale1;
// Calculate coefficients.
if (1.0 - cosom > Mathf.Epsilon)
{
// Standard case (Slerp).
real_t omega = Mathf.Acos(cosom);
sinom = Mathf.Sin(omega);
scale0 = Mathf.Sin((1.0f - weight) * omega) / sinom;
scale1 = Mathf.Sin(weight * omega) / sinom;
}
else
{
// Quaternions are very close so we can do a linear interpolation.
scale0 = 1.0f - weight;
scale1 = weight;
}
// Calculate final values.
return new Quat
(
scale0 * x + scale1 * to1.x,
scale0 * y + scale1 * to1.y,
scale0 * z + scale1 * to1.z,
scale0 * w + scale1 * to1.w
);
}
/// <summary>
/// Returns the result of the spherical linear interpolation between
/// this quaternion and `to` by amount `weight`, but without
/// checking if the rotation path is not bigger than 90 degrees.
/// </summary>
/// <param name="to">The destination quaternion for interpolation. Must be normalized.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting quaternion of the interpolation.</returns>
public Quat Slerpni(Quat to, real_t weight)
{
real_t dot = Dot(to);
if (Mathf.Abs(dot) > 0.9999f)
{
return this;
}
real_t theta = Mathf.Acos(dot);
real_t sinT = 1.0f / Mathf.Sin(theta);
real_t newFactor = Mathf.Sin(weight * theta) * sinT;
real_t invFactor = Mathf.Sin((1.0f - weight) * theta) * sinT;
return new Quat
(
invFactor * x + newFactor * to.x,
invFactor * y + newFactor * to.y,
invFactor * z + newFactor * to.z,
invFactor * w + newFactor * to.w
);
}
/// <summary>
/// Returns a vector transformed (multiplied) by this quaternion.
/// </summary>
/// <param name="v">A vector to transform.</param>
/// <returns>The transformed vector.</returns>
public Vector3 Xform(Vector3 v)
{
#if DEBUG
if (!IsNormalized())
{
throw new InvalidOperationException("Quat is not normalized");
}
#endif
var u = new Vector3(x, y, z);
Vector3 uv = u.Cross(v);
return v + ((uv * w) + u.Cross(uv)) * 2;
}
// Constants
private static readonly Quat _identity = new Quat(0, 0, 0, 1);
/// <summary>
/// The identity quaternion, representing no rotation.
/// Equivalent to an identity <see cref="Basis"/> matrix. If a vector is transformed by
/// an identity quaternion, it will not change.
/// </summary>
/// <value>Equivalent to `new Quat(0, 0, 0, 1)`.</value>
public static Quat Identity { get { return _identity; } }
/// <summary>
/// Constructs a quaternion defined by the given values.
/// </summary>
/// <param name="x">X component of the quaternion (imaginary `i` axis part).</param>
/// <param name="y">Y component of the quaternion (imaginary `j` axis part).</param>
/// <param name="z">Z component of the quaternion (imaginary `k` axis part).</param>
/// <param name="w">W component of the quaternion (real part).</param>
public Quat(real_t x, real_t y, real_t z, real_t w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/// <summary>
/// Constructs a quaternion from the given quaternion.
/// </summary>
/// <param name="q">The existing quaternion.</param>
public Quat(Quat q)
{
this = q;
}
/// <summary>
/// Constructs a quaternion from the given <see cref="Basis"/>.
/// </summary>
/// <param name="basis">The basis to construct from.</param>
public Quat(Basis basis)
{
this = basis.Quat();
}
/// <summary>
/// Constructs a quaternion that will perform a rotation specified by
/// Euler angles (in the YXZ convention: when decomposing,
/// first Z, then X, and Y last),
/// given in the vector format as (X angle, Y angle, Z angle).
/// </summary>
/// <param name="eulerYXZ"></param>
public Quat(Vector3 eulerYXZ)
{
real_t half_a1 = eulerYXZ.y * 0.5f;
real_t half_a2 = eulerYXZ.x * 0.5f;
real_t half_a3 = eulerYXZ.z * 0.5f;
// R = Y(a1).X(a2).Z(a3) convention for Euler angles.
// Conversion to quaternion as listed in https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf (page A-6)
// a3 is the angle of the first rotation, following the notation in this reference.
real_t cos_a1 = Mathf.Cos(half_a1);
real_t sin_a1 = Mathf.Sin(half_a1);
real_t cos_a2 = Mathf.Cos(half_a2);
real_t sin_a2 = Mathf.Sin(half_a2);
real_t cos_a3 = Mathf.Cos(half_a3);
real_t sin_a3 = Mathf.Sin(half_a3);
x = sin_a1 * cos_a2 * sin_a3 + cos_a1 * sin_a2 * cos_a3;
y = sin_a1 * cos_a2 * cos_a3 - cos_a1 * sin_a2 * sin_a3;
z = cos_a1 * cos_a2 * sin_a3 - sin_a1 * sin_a2 * cos_a3;
w = sin_a1 * sin_a2 * sin_a3 + cos_a1 * cos_a2 * cos_a3;
}
/// <summary>
/// Constructs a quaternion that will rotate around the given axis
/// by the specified angle. The axis must be a normalized vector.
/// </summary>
/// <param name="axis">The axis to rotate around. Must be normalized.</param>
/// <param name="angle">The angle to rotate, in radians.</param>
public Quat(Vector3 axis, real_t angle)
{
#if DEBUG
if (!axis.IsNormalized())
{
throw new ArgumentException("Argument is not normalized", nameof(axis));
}
#endif
real_t d = axis.Length();
if (d == 0f)
{
x = 0f;
y = 0f;
z = 0f;
w = 0f;
}
else
{
real_t sinAngle = Mathf.Sin(angle * 0.5f);
real_t cosAngle = Mathf.Cos(angle * 0.5f);
real_t s = sinAngle / d;
x = axis.x * s;
y = axis.y * s;
z = axis.z * s;
w = cosAngle;
}
}
public static Quat operator *(Quat left, Quat right)
{
return new Quat
(
left.w * right.x + left.x * right.w + left.y * right.z - left.z * right.y,
left.w * right.y + left.y * right.w + left.z * right.x - left.x * right.z,
left.w * right.z + left.z * right.w + left.x * right.y - left.y * right.x,
left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z
);
}
public static Quat operator +(Quat left, Quat right)
{
return new Quat(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
}
public static Quat operator -(Quat left, Quat right)
{
return new Quat(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
}
public static Quat operator -(Quat left)
{
return new Quat(-left.x, -left.y, -left.z, -left.w);
}
public static Quat operator *(Quat left, Vector3 right)
{
return new Quat
(
left.w * right.x + left.y * right.z - left.z * right.y,
left.w * right.y + left.z * right.x - left.x * right.z,
left.w * right.z + left.x * right.y - left.y * right.x,
-left.x * right.x - left.y * right.y - left.z * right.z
);
}
public static Quat operator *(Vector3 left, Quat right)
{
return new Quat
(
right.w * left.x + right.y * left.z - right.z * left.y,
right.w * left.y + right.z * left.x - right.x * left.z,
right.w * left.z + right.x * left.y - right.y * left.x,
-right.x * left.x - right.y * left.y - right.z * left.z
);
}
public static Quat operator *(Quat left, real_t right)
{
return new Quat(left.x * right, left.y * right, left.z * right, left.w * right);
}
public static Quat operator *(real_t left, Quat right)
{
return new Quat(right.x * left, right.y * left, right.z * left, right.w * left);
}
public static Quat operator /(Quat left, real_t right)
{
return left * (1.0f / right);
}
public static bool operator ==(Quat left, Quat right)
{
return left.Equals(right);
}
public static bool operator !=(Quat left, Quat right)
{
return !left.Equals(right);
}
public override bool Equals(object obj)
{
if (obj is Quat)
{
return Equals((Quat)obj);
}
return false;
}
public bool Equals(Quat other)
{
return x == other.x && y == other.y && z == other.z && w == other.w;
}
/// <summary>
/// Returns true if this quaternion and `other` are approximately equal, by running
/// <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component.
/// </summary>
/// <param name="other">The other quaternion to compare.</param>
/// <returns>Whether or not the quaternions are approximately equal.</returns>
public bool IsEqualApprox(Quat other)
{
return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z) && Mathf.IsEqualApprox(w, other.w);
}
public override int GetHashCode()
{
return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode();
}
public override string ToString()
{
return String.Format("({0}, {1}, {2}, {3})", x.ToString(), y.ToString(), z.ToString(), w.ToString());
}
public string ToString(string format)
{
return String.Format("({0}, {1}, {2}, {3})", x.ToString(format), y.ToString(format), z.ToString(format), w.ToString(format));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using PhysXWrapper;
using Quaternion=OpenMetaverse.Quaternion;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Region.Physics.PhysXPlugin
{
public class PhysXCharacter : PhysicsActor
{
private Vector3 _position;
private Vector3 _velocity;
private Vector3 m_rotationalVelocity = Vector3.Zero;
private Vector3 _acceleration;
private NxCharacter _character;
private bool flying;
private bool iscolliding = false;
private float gravityAccel;
public PhysXCharacter(NxCharacter character)
{
_character = character;
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set
{
_position = value;
Vec3 ps = new Vec3();
ps.X = value.X;
ps.Y = value.Y;
ps.Z = value.Z;
_character.Position = ps;
}
}
public override Vector3 Size
{
get { return Vector3.Zero; }
set { }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
}
public void SetAcceleration(Vector3 accel)
{
_acceleration = accel;
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public void Move(float timeStep)
{
Vec3 vec = new Vec3();
vec.X = _velocity.X*timeStep;
vec.Y = _velocity.Y*timeStep;
if (flying)
{
vec.Z = (_velocity.Z)*timeStep;
}
else
{
gravityAccel += -9.8f;
vec.Z = (gravityAccel + _velocity.Z)*timeStep;
}
int res = _character.Move(vec);
if (res == 1)
{
gravityAccel = 0;
}
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public void UpdatePosition()
{
Vec3 vec = _character.Position;
_position.X = vec.X;
_position.Y = vec.Y;
_position.Z = vec.Z;
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override float PIDHoverHeight { set { return; } }
public override bool PIDHoverActive { set { return; } }
public override PIDHoverType PIDHoverType { set { return; } }
public override float PIDHoverTau { set { return; } }
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
#endregion
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Represents a dynamically loaded unmanaged library in a (partially) platform independent manner.
/// First, the native library is loaded using dlopen (on Unix systems) or using LoadLibrary (on Windows).
/// dlsym or GetProcAddress are then used to obtain symbol addresses. <c>Marshal.GetDelegateForFunctionPointer</c>
/// transforms the addresses into delegates to native methods.
/// See http://stackoverflow.com/questions/13461989/p-invoke-to-dynamically-loaded-library-on-mono.
/// </summary>
internal class UnmanagedLibrary
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<UnmanagedLibrary>();
// flags for dlopen
const int RTLD_LAZY = 1;
const int RTLD_GLOBAL = 8;
readonly string libraryPath;
readonly IntPtr handle;
public UnmanagedLibrary(string[] libraryPathAlternatives)
{
this.libraryPath = FirstValidLibraryPath(libraryPathAlternatives);
Logger.Debug("Attempting to load native library \"{0}\"", this.libraryPath);
this.handle = PlatformSpecificLoadLibrary(this.libraryPath);
if (this.handle == IntPtr.Zero)
{
throw new IOException(string.Format("Error loading native library \"{0}\"", this.libraryPath));
}
}
/// <summary>
/// Loads symbol in a platform specific way.
/// </summary>
/// <param name="symbolName"></param>
/// <returns></returns>
public IntPtr LoadSymbol(string symbolName)
{
if (PlatformApis.IsWindows)
{
// See http://stackoverflow.com/questions/10473310 for background on this.
if (PlatformApis.Is64Bit)
{
return Windows.GetProcAddress(this.handle, symbolName);
}
else
{
// Yes, we could potentially predict the size... but it's a lot simpler to just try
// all the candidates. Most functions have a suffix of @0, @4 or @8 so we won't be trying
// many options - and if it takes a little bit longer to fail if we've really got the wrong
// library, that's not a big problem. This is only called once per function in the native library.
symbolName = "_" + symbolName + "@";
for (int stackSize = 0; stackSize < 128; stackSize += 4)
{
IntPtr candidate = Windows.GetProcAddress(this.handle, symbolName + stackSize);
if (candidate != IntPtr.Zero)
{
return candidate;
}
}
// Fail.
return IntPtr.Zero;
}
}
if (PlatformApis.IsLinux)
{
if (PlatformApis.IsMono)
{
return Mono.dlsym(this.handle, symbolName);
}
if (PlatformApis.IsNetCore)
{
return CoreCLR.dlsym(this.handle, symbolName);
}
return Linux.dlsym(this.handle, symbolName);
}
if (PlatformApis.IsMacOSX)
{
return MacOSX.dlsym(this.handle, symbolName);
}
throw new InvalidOperationException("Unsupported platform.");
}
public T GetNativeMethodDelegate<T>(string methodName)
where T : class
{
var ptr = LoadSymbol(methodName);
if (ptr == IntPtr.Zero)
{
throw new MissingMethodException(string.Format("The native method \"{0}\" does not exist", methodName));
}
return Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T;
}
/// <summary>
/// Loads library in a platform specific way.
/// </summary>
private static IntPtr PlatformSpecificLoadLibrary(string libraryPath)
{
if (PlatformApis.IsWindows)
{
return Windows.LoadLibrary(libraryPath);
}
if (PlatformApis.IsLinux)
{
if (PlatformApis.IsMono)
{
return Mono.dlopen(libraryPath, RTLD_GLOBAL + RTLD_LAZY);
}
if (PlatformApis.IsNetCore)
{
return CoreCLR.dlopen(libraryPath, RTLD_GLOBAL + RTLD_LAZY);
}
return Linux.dlopen(libraryPath, RTLD_GLOBAL + RTLD_LAZY);
}
if (PlatformApis.IsMacOSX)
{
return MacOSX.dlopen(libraryPath, RTLD_GLOBAL + RTLD_LAZY);
}
throw new InvalidOperationException("Unsupported platform.");
}
private static string FirstValidLibraryPath(string[] libraryPathAlternatives)
{
GrpcPreconditions.CheckArgument(libraryPathAlternatives.Length > 0, "libraryPathAlternatives cannot be empty.");
foreach (var path in libraryPathAlternatives)
{
if (File.Exists(path))
{
return path;
}
}
throw new FileNotFoundException(
String.Format("Error loading native library. Not found in any of the possible locations: {0}",
string.Join(",", libraryPathAlternatives)));
}
private static class Windows
{
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(string filename);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
}
private static class Linux
{
[DllImport("libdl.so")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libdl.so")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
private static class MacOSX
{
[DllImport("libSystem.dylib")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libSystem.dylib")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
/// <summary>
/// On Linux systems, using using dlopen and dlsym results in
/// DllNotFoundException("libdl.so not found") if libc6-dev
/// is not installed. As a workaround, we load symbols for
/// dlopen and dlsym from the current process as on Linux
/// Mono sure is linked against these symbols.
/// </summary>
private static class Mono
{
[DllImport("__Internal")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("__Internal")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
/// <summary>
/// Similarly as for Mono on Linux, we load symbols for
/// dlopen and dlsym from the "libcoreclr.so",
/// to avoid the dependency on libc-dev Linux.
/// </summary>
private static class CoreCLR
{
[DllImport("libcoreclr.so")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libcoreclr.so")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
}
}
| |
// 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 Xunit;
using Tests.HashSet_HashSetTestSupport;
using Tests.HashSet_SetCollectionRelationshipTests;
using Tests.HashSet_SetCollectionComparerTests;
using Tests.HashSet_SetCollectionDuplicateItemTests;
namespace Tests
{
public class HashSet_ExceptWithTests
{
#region Set/Collection Relationship Tests (tests 1-42)
//Test 1: other is null
[Fact]
public static void IsExceptWith_Test1()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest1(out hashSet, out other);
Assert.Throws<ArgumentNullException>(() => hashSet.ExceptWith(other)); //"ArgumenNullException expected."
}
//Test 2: other is empty and set is empty
[Fact]
public static void IsExceptWith_Test2()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest2(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 3: Set/Collection Relationship Test 3: other is empty and set is single-item
[Fact]
public static void IsExceptWith_Test3()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest3(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1) }, hashSet.Comparer);
}
//Test 4: Set/Collection Relationship Test 4: other is empty and set is multi-item
[Fact]
public static void IsExceptWith_Test4()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest4(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(-23) }, hashSet.Comparer);
}
//Test 5: Set/Collection Relationship Test 5: other is single-item and set is empty
[Fact]
public static void IsExceptWith_Test5()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest5(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 6: Set/Collection Relationship Test 6: other is single-item and set is single-item with a different item
[Fact]
public static void IsExceptWith_Test6()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest6(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(34) }, hashSet.Comparer);
}
//Test 7: Set/Collection Relationship Test 7: other is single-item and set is single-item with the same item
[Fact]
public static void IsExceptWith_Test7()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest7(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 8: Set/Collection Relationship Test 8: other is single-item and set is multi-item where set and other are disjoint
[Fact]
public static void IsExceptWith_Test8()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest8(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(234) }, hashSet.Comparer);
}
//Test 9: Set/Collection Relationship Test 9: other is single-item and set is multi-item where set contains other
[Fact]
public static void IsExceptWith_Test9()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest9(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0) }, hashSet.Comparer);
}
//Test 10: Set/Collection Relationship Test 10: other is multi-item and set is empty
[Fact]
public static void IsExceptWith_Test10()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest10(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 11: Set/Collection Relationship Test 11: other is multi-item and set is single-item and set and other are disjoint
[Fact]
public static void IsExceptWith_Test11()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest11(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-222) }, hashSet.Comparer);
}
//Test 12: Set/Collection Relationship Test 12: other is multi-item and set is single-item and other contains set
[Fact]
public static void IsExceptWith_Test12()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest12(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 13: Set/Collection Relationship Test 13: other is multi-item and set is multi-item and set and other disjoint
[Fact]
public static void IsExceptWith_Test13()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest13(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222), new Item(322) }, hashSet.Comparer);
}
//Test 14: Set/Collection Relationship Test 14: other is multi-item and set is multi-item and set and other overlap but are non-comparable
[Fact]
public static void IsExceptWith_Test14()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest14(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222) }, hashSet.Comparer);
}
//Test 15: Set/Collection Relationship Test 15: other is multi-item and set is multi-item and other is a proper subset of set
[Fact]
public static void IsExceptWith_Test15()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest15(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222) }, hashSet.Comparer);
}
//Test 16: Set/Collection Relationship Test 16: other is multi-item and set is multi-item and set is a proper subset of other
[Fact]
public static void IsExceptWith_Test16()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest16(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 17: Set/Collection Relationship Test 17: other is multi-item and set is multi-item and set and other are equal
[Fact]
public static void IsExceptWith_Test17()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest17(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 18: Set/Collection Relationship Test 18: other is set and set is empty
[Fact]
public static void IsExceptWith_Test18()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest18(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 19: Set/Collection Relationship Test 19: other is set and set is single-item and set contains set
[Fact]
public static void IsExceptWith_Test19()
{
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest19(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer);
}
//Test 20: Set/Collection Relationship Test 20: other is set and set is single-item and set does not contain set
[Fact]
public static void IsExceptWith_Test20()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest20(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 21: Set/Collection Relationship Test 21: other is set and set is multi-item and set contains set
[Fact]
public static void IsExceptWith_Test21()
{
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest21(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer);
}
//Test 22: Set/Collection Relationship Test 22: other is set and set is multi-item and set does not contain set
[Fact]
public static void IsExceptWith_Test22()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest22(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 23: Set/Collection Relationship Test 23: item is only item in other: Item is the set and item is in the set
[Fact]
public static void IsExceptWith_Test23()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest23(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 24: Set/Collection Relationship Test 24: item is only item in other: Item is the set and item is not in the set
[Fact]
public static void IsExceptWith_Test24()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest24(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 25: Set/Collection Relationship Test 25: item is only item in other: Item is Default<T> and in set. T is a numeric type
[Fact]
public static void IsExceptWith_Test25()
{
HashSet<int> hashSet;
IEnumerable<int> other;
SetCollectionRelationshipTests.SetupTest25(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7 }, hashSet.Comparer);
}
//Test 26: Set/Collection Relationship Test 26: item is only item in other: Item is Default<T> and in set. T is a reference type
[Fact]
public static void IsExceptWith_Test26()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest26(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 27: Set/Collection Relationship Test 27: item is only item in other: Item is Default<T> and not in set. T is a numeric type
[Fact]
public static void IsExceptWith_Test27()
{
HashSet<int> hashSet;
IEnumerable<int> other;
SetCollectionRelationshipTests.SetupTest27(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7, 5 }, hashSet.Comparer);
}
//Test 28: Set/Collection Relationship Test 28: item is only item in other: Item is Default<T> and not in set. T is a reference type
[Fact]
public static void IsExceptWith_Test28()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest28(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 29: Set/Collection Relationship Test 29: item is only item in other: Item is equal to an item in set but different.
[Fact]
public static void IsExceptWith_Test29()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest29(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 30: Set/Collection Relationship Test 30: item is only item in other: Item shares hash value with unequal item in set
[Fact]
public static void IsExceptWith_Test30()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest30(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 31: Set/Collection Relationship Test 31: item is only item in other: Item was previously in set but not currently
[Fact]
public static void IsExceptWith_Test31()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest31(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 32: Set/Collection Relationship Test 32: item is only item in other: Item was previously removed from set but in it currently
[Fact]
public static void IsExceptWith_Test32()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest32(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 33: Set/Collection Relationship Test 33: item is one of the items in other: Item is the set and item is in the set
[Fact]
public static void IsExceptWith_Test33()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest33(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 34: Set/Collection Relationship Test 34: item is one of the items in other: Item is the set and item is not in the set
[Fact]
public static void IsExceptWith_Test34()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
SetCollectionRelationshipTests.SetupTest34(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 35: Set/Collection Relationship Test 35: item is one of the items in other: Item is Default<T> and in set. T is a numeric type
[Fact]
public static void IsExceptWith_Test35()
{
HashSet<int> hashSet;
IEnumerable<int> other;
SetCollectionRelationshipTests.SetupTest35(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7 }, hashSet.Comparer);
}
//Test 36: Set/Collection Relationship Test 36: item is one of the items in other: Item is Default<T> and in set. T is a reference type
[Fact]
public static void IsExceptWith_Test36()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest36(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 37: Set/Collection Relationship Test 37: item is one of the items in other: Item is Default<T> and not in set. T is a numeric type
[Fact]
public static void IsExceptWith_Test37()
{
HashSet<int> hashSet;
IEnumerable<int> other;
SetCollectionRelationshipTests.SetupTest37(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7, 5 }, hashSet.Comparer);
}
//Test 38: Set/Collection Relationship Test 38: item is one of the items in other: Item is Default<T> and not in set. T is a reference type
[Fact]
public static void IsExceptWith_Test38()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest38(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 39: Set/Collection Relationship Test 39: item is one of the items in other: Item is equal to an item in set but different.
[Fact]
public static void IsExceptWith_Test39()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest39(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 40: Set/Collection Relationship Test 40: item is one of the items in other: Item shares hash value with unequal item in set
[Fact]
public static void IsExceptWith_Test40()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest40(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 41: Set/Collection Relationship Test 41: item is one of the items in other: Item was previously in set but not currently
[Fact]
public static void IsExceptWith_Test41()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest41(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 42: Set/Collection Relationship Test 42: item is one of the items in other: Item was previously removed from set but in it currently
[Fact]
public static void IsExceptWith_Test42()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
SetCollectionRelationshipTests.SetupTest42(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
#endregion
#region Set/Collection Comparer Tests (tests 43-57)
//Test 43: Set/Collection Comparer Test 1: Item is in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test43()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest1(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 44: Set/Collection Comparer Test 2: Item is in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test44()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest2(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 45: Set/Collection Comparer Test 3: Item is in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test45()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest3(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 46: Set/Collection Comparer Test 4: Item is in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test46()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest4(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 48: Set/Collection Comparer Test 6: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test48()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest6(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 49: Set/Collection Comparer Test 7: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test49()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest7(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 50: Set/Collection Comparer Test 8: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test50()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest8(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 51: Set/Collection Comparer Test 9: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test51()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest9(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 52: Set/Collection Comparer Test 10: Item is only item in collection: item contains set and item in set with GetSetComparer<T> as comparer
[Fact]
public static void IsExceptWith_Test52()
{
ValueItem itemn4 = new ValueItem(-4, -4);
ValueItem itemn3 = new ValueItem(-3, -3);
ValueItem itemn2 = new ValueItem(-2, -2);
ValueItem itemn1 = new ValueItem(-1, -1);
ValueItem item1 = new ValueItem(1, 1);
ValueItem item2 = new ValueItem(2, 2);
ValueItem item3 = new ValueItem(3, 3);
ValueItem item4 = new ValueItem(4, 4);
HashSet<IEnumerable> itemhs1 = new HashSet<IEnumerable>(new ValueItem[] { item1, item2, item3, item4 });
HashSet<IEnumerable> itemhs2 = new HashSet<IEnumerable>(new ValueItem[] { itemn1, itemn2, itemn3, itemn4 });
HashSet<HashSet<IEnumerable>> hashSet;
IEnumerable<HashSet<IEnumerable>> other;
SetCollectionComparerTests.SetupTest10(out hashSet, out other);
hashSet.ExceptWith(other);
HashSet<IEnumerable>[] expected = new HashSet<IEnumerable>[] { itemhs1, itemhs2 };
HashSet<IEnumerable>[] actual = new HashSet<IEnumerable>[2];
hashSet.CopyTo(actual, 0, 2);
Assert.Equal(2, hashSet.Count); //"Should be equal"
HashSetTestSupport.HashSetContains(actual, expected);
}
//Test 53: Set/Collection Comparer Test 11: Item is collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test53()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest11(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 54: Set/Collection Comparer Test 12: Item is collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void IsExceptWith_Test54()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest12(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 55: Set/Collection Comparer Test 13: Item is collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test55()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest13(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 56: Set/Collection Comparer Test 14: Item is collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void IsExceptWith_Test56()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest14(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 57: Set/Collection Comparer Test 15: Item is collection: item contains set and item in set with GetSetComparer<T> as comparer
[Fact]
public static void IsExceptWith_Test57()
{
HashSet<HashSet<IEnumerable>> hashSet;
IEnumerable<HashSet<IEnumerable>> other;
SetCollectionComparerTests.SetupTest15(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<HashSet<IEnumerable>>.VerifyHashSet(hashSet, new HashSet<IEnumerable>[0], hashSet.Comparer);
}
#endregion
#region Set/Collection Duplicate Item Tests (tests 58-73)
//Test 58: Set/Collection Duplicate Item Test 1: other collection is multi-item with duplicates, set is empty
[Fact]
public static void IsExceptWith_Test58()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest1(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 59: Set/Collection Duplicate Item Test 2: other collection is multi-item with duplicates, set contains a single item not in other
[Fact]
public static void IsExceptWith_Test59()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem item5 = new ValueItem(101, 101);
SetCollectionDuplicateItemTests.SetupTest2(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item5 }, hashSet.Comparer);
}
//Test 60: Set/Collection Duplicate Item Test 3: other collection is multi-item with duplicates, set contains a single item that is in other but not a duplicate in other
[Fact]
public static void IsExceptWith_Test60()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest3(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 61: Set/Collection Duplicate Item Test 4: other collection is multi-item with duplicates, set contains a single item that is a duplicate in other
[Fact]
public static void IsExceptWith_Test61()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest4(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 62: Set/Collection Duplicate Item Test 5: other collection is multi-item with duplicates, set is multi-item as well, set and other are disjoint
[Fact]
public static void IsExceptWith_Test62()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-4, -4);
ValueItem items3 = new ValueItem(-9999, 2);
ValueItem items4 = new ValueItem(-99, 2);
SetCollectionDuplicateItemTests.SetupTest5(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
//Test 63: Set/Collection Duplicate Item Test 6: other collection is multi-item with duplicates, set is multi-item as well, set and other overlap but are non-comparable, the overlap contains duplicate items from other
[Fact]
public static void IsExceptWith_Test63()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items3 = new ValueItem(-9999, 2);
SetCollectionDuplicateItemTests.SetupTest6(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3 }, hashSet.Comparer);
}
//Test 64: Set/Collection Duplicate Item Test 7: other collection is multi-item with duplicates, set is multi-item as well, set and other overlap but are non-comparable, the overlap does not contain duplicate items from other
[Fact]
public static void IsExceptWith_Test64()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items3 = new ValueItem(-9999, 2);
SetCollectionDuplicateItemTests.SetupTest7(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3 }, hashSet.Comparer);
}
//Test 65: Set/Collection Duplicate Item Test 8: other collection is multi-item with duplicates, set is multi-item as well, other is a proper subset of set
[Fact]
public static void IsExceptWith_Test65()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-4, -4);
ValueItem items3 = new ValueItem(-9999, 2);
ValueItem items4 = new ValueItem(-99, 2);
SetCollectionDuplicateItemTests.SetupTest8(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
//Test 66: Set/Collection Duplicate Item Test 9: other collection is multi-item with duplicates, set is multi-item as well, set is a proper subset of other, set contains duplicate items from other
[Fact]
public static void IsExceptWith_Test66()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest9(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 67: Set/Collection Duplicate Item Test 10: other collection is multi-item with duplicates, set is multi-item as well, set is a proper subset of other, set does not contain duplicate items from other
[Fact]
public static void IsExceptWith_Test67()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest10(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 68: Set/Collection Duplicate Item Test 11: other collection is multi-item with duplicates, set is multi-item as well, set and other are equal
[Fact]
public static void IsExceptWith_Test68()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
SetCollectionDuplicateItemTests.SetupTest11(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[0], hashSet.Comparer);
}
//Test 69: Set/Collection Duplicate Item Test 12: other contains duplicates by sets comparer but not by default comparer
[Fact]
public static void IsExceptWith_Test69()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items3 = new ValueItem(-9999, 2);
ValueItem items4 = new ValueItem(-99, -2);
SetCollectionDuplicateItemTests.SetupTest12(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items3, items4 }, hashSet.Comparer);
}
//Test 70: Set/Collection Duplicate Item Test 13: other contains duplicates by default comparer but not by sets comparer
[Fact]
public static void IsExceptWith_Test70()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-4, -4);
ValueItem items3 = new ValueItem(-9999, 2);
ValueItem items4 = new ValueItem(-99, -2);
SetCollectionDuplicateItemTests.SetupTest13(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
//Test 71: Set/Collection Duplicate Item Test 14: set contains duplicate items by default comparer, those items also in other
[Fact]
public static void IsExceptWith_Test71()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-99, -4);
ValueItem items3 = new ValueItem(-34, 2);
ValueItem items4 = new ValueItem(-99, -2);
SetCollectionDuplicateItemTests.SetupTest14(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
//Test 72: Set/Collection Duplicate Item Test 15: set contains duplicate items by default comparer, one of those items also in other
[Fact]
public static void IsExceptWith_Test72()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-99, -4);
ValueItem items3 = new ValueItem(-34, 2);
ValueItem items4 = new ValueItem(-99, -2);
SetCollectionDuplicateItemTests.SetupTest15(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
//Test 73: Set/Collection Duplicate Item Test 16: set contains duplicate items by default comparer, those items not in other
[Fact]
public static void IsExceptWith_Test73()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
ValueItem items1 = new ValueItem(-34, 5);
ValueItem items2 = new ValueItem(-99, -4);
ValueItem items3 = new ValueItem(-34, 2);
ValueItem items4 = new ValueItem(-99, -2);
SetCollectionDuplicateItemTests.SetupTest16(out hashSet, out other);
hashSet.ExceptWith(other);
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { items1, items2, items3, items4 }, hashSet.Comparer);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL.Stubs
{
/// <summary>
/// Intrinsic support arround EqualityComparer<T> and Comparer<T>.
/// </summary>
public static class ComparerIntrinsics
{
/// <summary>
/// Generates a specialized method body for Comparer`1.Create or returns null if no specialized body can be generated.
/// </summary>
public static MethodIL EmitComparerCreate(MethodDesc target)
{
return EmitComparerAndEqualityComparerCreateCommon(target, "Comparer", "IComparable`1");
}
/// <summary>
/// Generates a specialized method body for EqualityComparer`1.Create or returns null if no specialized body can be generated.
/// </summary>
public static MethodIL EmitEqualityComparerCreate(MethodDesc target)
{
return EmitComparerAndEqualityComparerCreateCommon(target, "EqualityComparer", "IEquatable`1");
}
/// <summary>
/// Gets the concrete type EqualityComparer`1.Create returns or null if it's not known at compile time.
/// </summary>
public static TypeDesc GetEqualityComparerForType(TypeDesc comparand)
{
return GetComparerForType(comparand, "EqualityComparer", "IEquatable`1");
}
private static MethodIL EmitComparerAndEqualityComparerCreateCommon(MethodDesc methodBeingGenerated, string flavor, string interfaceName)
{
// We expect the method to be fully instantiated
Debug.Assert(!methodBeingGenerated.IsTypicalMethodDefinition);
TypeDesc owningType = methodBeingGenerated.OwningType;
TypeDesc comparedType = owningType.Instantiation[0];
// If the type is canonical, we use the default implementation provided by the class library.
// This will rely on the type loader to load the proper type at runtime.
if (comparedType.IsCanonicalSubtype(CanonicalFormKind.Any))
return null;
TypeDesc comparerType = GetComparerForType(comparedType, flavor, interfaceName);
Debug.Assert(comparerType != null);
ILEmitter emitter = new ILEmitter();
var codeStream = emitter.NewCodeStream();
codeStream.Emit(ILOpcode.newobj, emitter.NewToken(comparerType.GetParameterlessConstructor()));
codeStream.Emit(ILOpcode.dup);
codeStream.Emit(ILOpcode.stsfld, emitter.NewToken(owningType.GetKnownField("_default")));
codeStream.Emit(ILOpcode.ret);
return emitter.Link(methodBeingGenerated);
}
/// <summary>
/// Gets the comparer type that is suitable to compare instances of <paramref name="type"/>
/// or null if such comparer cannot be determined at compile time.
/// </summary>
private static TypeDesc GetComparerForType(TypeDesc type, string flavor, string interfaceName)
{
TypeSystemContext context = type.Context;
if (context.IsCanonicalDefinitionType(type, CanonicalFormKind.Any) ||
(type.IsRuntimeDeterminedSubtype && !type.HasInstantiation))
{
// The comparer will be determined at runtime. We can't tell the exact type at compile time.
return null;
}
else if (type.IsNullable)
{
TypeDesc nullableType = type.Instantiation[0];
if (context.IsCanonicalDefinitionType(nullableType, CanonicalFormKind.Universal))
{
// We can't tell at compile time either.
return null;
}
else if (ImplementsInterfaceOfSelf(nullableType, interfaceName))
{
return context.SystemModule.GetKnownType("System.Collections.Generic", $"Nullable{flavor}`1")
.MakeInstantiatedType(nullableType);
}
}
else if (flavor == "EqualityComparer" && type.IsEnum)
{
// Enums have a specialized comparer that avoids boxing
return context.SystemModule.GetKnownType("System.Collections.Generic", $"Enum{flavor}`1")
.MakeInstantiatedType(type);
}
else if (ImplementsInterfaceOfSelf(type, interfaceName))
{
return context.SystemModule.GetKnownType("System.Collections.Generic", $"Generic{flavor}`1")
.MakeInstantiatedType(type);
}
return context.SystemModule.GetKnownType("System.Collections.Generic", $"Object{flavor}`1")
.MakeInstantiatedType(type);
}
public static TypeDesc[] GetPotentialComparersForType(TypeDesc type)
{
return GetPotentialComparersForTypeCommon(type, "Comparer", "IComparable`1");
}
public static TypeDesc[] GetPotentialEqualityComparersForType(TypeDesc type)
{
return GetPotentialComparersForTypeCommon(type, "EqualityComparer", "IEquatable`1");
}
/// <summary>
/// Gets the set of template types needed to support loading comparers for the give canonical type at runtime.
/// </summary>
private static TypeDesc[] GetPotentialComparersForTypeCommon(TypeDesc type, string flavor, string interfaceName)
{
Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any));
TypeDesc exactComparer = GetComparerForType(type, flavor, interfaceName);
if (exactComparer != null)
{
// If we have a comparer that is exactly known at runtime, we're done.
// This will typically be if type is a generic struct, generic enum, or a nullable.
return new TypeDesc[] { exactComparer };
}
TypeSystemContext context = type.Context;
if (context.IsCanonicalDefinitionType(type, CanonicalFormKind.Universal))
{
// This can be any of the comparers we have.
ArrayBuilder<TypeDesc> universalComparers = new ArrayBuilder<TypeDesc>();
universalComparers.Add(context.SystemModule.GetKnownType("System.Collections.Generic", $"Nullable{flavor}`1")
.MakeInstantiatedType(type));
if (flavor == "EqualityComparer")
universalComparers.Add(context.SystemModule.GetKnownType("System.Collections.Generic", $"Enum{flavor}`1")
.MakeInstantiatedType(type));
universalComparers.Add(context.SystemModule.GetKnownType("System.Collections.Generic", $"Generic{flavor}`1")
.MakeInstantiatedType(type));
universalComparers.Add(context.SystemModule.GetKnownType("System.Collections.Generic", $"Object{flavor}`1")
.MakeInstantiatedType(type));
return universalComparers.ToArray();
}
// This mirrors exactly what GetUnknownEquatableComparer and GetUnknownComparer (in the class library)
// will need at runtime. This is the general purpose code path that can be used to compare
// anything.
if (type.IsNullable)
{
TypeDesc nullableType = type.Instantiation[0];
// This should only be reachabe for universal canon code.
// For specific canon, this should have been an exact match above.
Debug.Assert(context.IsCanonicalDefinitionType(nullableType, CanonicalFormKind.Universal));
return new TypeDesc[]
{
context.SystemModule.GetKnownType("System.Collections.Generic", $"Nullable{flavor}`1")
.MakeInstantiatedType(nullableType),
context.SystemModule.GetKnownType("System.Collections.Generic", $"Object{flavor}`1")
.MakeInstantiatedType(type),
};
}
return new TypeDesc[]
{
context.SystemModule.GetKnownType("System.Collections.Generic", $"Generic{flavor}`1")
.MakeInstantiatedType(type),
context.SystemModule.GetKnownType("System.Collections.Generic", $"Object{flavor}`1")
.MakeInstantiatedType(type),
};
}
public static bool ImplementsIEquatable(TypeDesc type)
=> ImplementsInterfaceOfSelf(type, "IEquatable`1");
private static bool ImplementsInterfaceOfSelf(TypeDesc type, string interfaceName)
{
MetadataType interfaceType = null;
foreach (TypeDesc implementedInterface in type.RuntimeInterfaces)
{
Instantiation interfaceInstantiation = implementedInterface.Instantiation;
if (interfaceInstantiation.Length == 1 &&
interfaceInstantiation[0] == type)
{
if (interfaceType == null)
interfaceType = type.Context.SystemModule.GetKnownType("System", interfaceName);
if (implementedInterface.GetTypeDefinition() == interfaceType)
return true;
}
}
return false;
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_11_5_3 : EcmaTest
{
[Fact]
[Trait("Category", "11.5.3")]
public void WhiteSpaceAndLineTerminatorBetweenMultiplicativeexpressionAndOrBetweenAndUnaryexpressionAreAllowed()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYUsesGetvalue()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.1_T1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYUsesGetvalue2()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.1_T2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYUsesGetvalue3()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.1_T3.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYUsesDefaultValue()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.2_T1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TonumberFirstExpressionIsCalledFirstAndThenTonumberSecondExpression()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.3_T1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.4_T1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression2()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.4_T2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression3()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A2.4_T3.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T1.1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY2()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T1.2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY3()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T1.3.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY4()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T1.4.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY5()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T1.5.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY6()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY7()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY8()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.3.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY9()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.4.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY10()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.5.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY11()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.6.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY12()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.7.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY13()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.8.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void OperatorXYReturnsTonumberXTonumberY14()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A3_T2.9.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T1.1.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics2()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T1.2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics3()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T2.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics4()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T3.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics5()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T4.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics6()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T5.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics7()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T6.js", false);
}
[Fact]
[Trait("Category", "11.5.3")]
public void TheResultOfAEcmascriptFloatingPointRemainderOperationIsDeterminedByTheRulesOfIeeeArithmetics8()
{
RunTest(@"TestCases/ch11/11.5/11.5.3/S11.5.3_A4_T7.js", false);
}
}
}
| |
/*
* Copyright 2008-2015 the GAP developers. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
* Bijgewerkt gebruikersbeheer Copyright 2014, 2015, 2017 Chirojeugd-Vlaanderen vzw
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.ServiceModel;
using System.Web;
using Chiro.Ad.ServiceContracts;
using Chiro.Cdf.Poco;
using Chiro.Cdf.ServiceHelper;
using Chiro.Cdf.Sso;
using Chiro.Gap.Domain;
using Chiro.Gap.Poco.Model;
using Chiro.Gap.ServiceContracts;
using Chiro.Gap.ServiceContracts.DataContracts;
using Chiro.Gap.ServiceContracts.FaultContracts;
using Chiro.Gap.Services.Properties;
using Chiro.Gap.WorkerInterfaces;
using GebruikersRecht = Chiro.Gap.ServiceContracts.DataContracts.GebruikersRecht;
#if KIPDORP
using System.Transactions;
#endif
namespace Chiro.Gap.Services
{
/// <summary>
/// Interface voor de service voor gebruikersrechtenbeheer.
/// </summary>
public class GebruikersService : BaseService, IGebruikersService, IDisposable
{
#region Disposable etc
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_repositoryProvider.Dispose();
}
disposed = true;
}
}
~GebruikersService()
{
Dispose(false);
}
#endregion
private readonly ServiceHelper _serviceHelper;
public ServiceHelper ServiceHelper { get { return _serviceHelper; } }
// Repositories, verantwoordelijk voor data access.
private readonly IRepositoryProvider _repositoryProvider;
private readonly IRepository<GebruikersRechtV2> _rechtenRepo;
private readonly IRepository<GelieerdePersoon> _gelieerdePersonenRepo;
private readonly IRepository<Persoon> _personenRepo;
// Managers voor niet-triviale businesslogica
private readonly IGebruikersRechtenManager _gebruikersRechtenMgr;
private readonly IGelieerdePersonenManager _gelieerdePersonenMgr;
private readonly GavChecker _gav;
/// <summary>
/// Nieuwe groepenservice
/// </summary>
/// <param name="autorisatieMgr">Verantwoordelijke voor autorisatie</param>
/// <param name="gebruikersRechtenMgr">Businesslogica aangaande gebruikersrechten</param>
/// <param name="authenticatieManager">Levert de gebruikersnaam op</param>
/// <param name="ledenManager">Businesslogica m.b.t. de leden</param>
/// <param name="groepsWerkJarenManager">Businesslogica m.b.t. de groepswerkjaren.</param>
/// <param name="gelieerdePersonenManager">Businesslogica i.f.v. gelieerde personen</param>
/// <param name="abonnementenManager">Businesslogica i.f.v. abonnementen.</param>
/// <param name="repositoryProvider">De repository provider levert alle nodige repository's op.</param>
/// <param name="serviceHelper">Service helper die gebruikt zal worden om de active-directory-service aan te spreken.</param>
public GebruikersService(IAutorisatieManager autorisatieMgr,
IGebruikersRechtenManager gebruikersRechtenMgr,
IAuthenticatieManager authenticatieManager,
ILedenManager ledenManager,
IGroepsWerkJarenManager groepsWerkJarenManager,
IGelieerdePersonenManager gelieerdePersonenManager,
IAbonnementenManager abonnementenManager,
IRepositoryProvider repositoryProvider,
ServiceHelper serviceHelper)
: base(ledenManager, groepsWerkJarenManager, authenticatieManager, autorisatieMgr, abonnementenManager)
{
_repositoryProvider = repositoryProvider;
_rechtenRepo = repositoryProvider.RepositoryGet<GebruikersRechtV2>();
_gelieerdePersonenRepo = repositoryProvider.RepositoryGet<GelieerdePersoon>();
_personenRepo = repositoryProvider.RepositoryGet<Persoon>();
_gebruikersRechtenMgr = gebruikersRechtenMgr;
_gelieerdePersonenMgr = gelieerdePersonenManager;
_gav = new GavChecker(_autorisatieMgr);
_serviceHelper = serviceHelper;
}
public GavChecker Gav
{
get { return _gav; }
}
/// <summary>
/// Als de persoon met gegeven <paramref name="gelieerdePersoonId"/> nog geen account heeft, krijgt
/// hij een account voor zijn eigen groep. Aan die account worden dan de meegegeven
/// <paramref name="gebruikersRecht"/> gekoppeld.
/// </summary>
/// <param name="gelieerdePersoonId">Id van gelieerde persoon die rechten moet krijgen</param>
/// <param name="gebruikersRecht">Rechten die de account moet krijgen. Mag leeg zijn. Bestaande
/// gebruikersrechten worden zo mogelijk verlengd als ze in <paramref name="gebruikersRecht"/>
/// voorkomen, eventuele bestaande rechten niet in <paramref name="gebruikersRecht"/> blijven
/// onaangeroerd.
/// </param>
public void RechtenToekennen(int gelieerdePersoonId, GebruikersRecht gebruikersRecht)
{
var gelieerdePersoon = _gelieerdePersonenRepo.ByID(gelieerdePersoonId);
Gav.Check(gelieerdePersoon);
if (gebruikersRecht == null)
{
// Als er geen gebruikersrechten meegegeven zijn, dan geven we de gelieerde persoon
// rechten 'geen' op zijn eigen groep.
gebruikersRecht = new GebruikersRecht();
}
var p = gelieerdePersoon.Persoon;
if (p.AdNummer == null)
{
throw FaultExceptionHelper.FoutNummer(FoutNummer.AdNummerVerplicht,
Resources.AdNummerVerplicht);
}
if (string.IsNullOrEmpty(_gelieerdePersonenMgr.ContactEmail(gelieerdePersoon)))
{
throw FaultExceptionHelper.FoutNummer(FoutNummer.EMailVerplicht, Resources.EmailOntbreekt);
}
_gebruikersRechtenMgr.ToekennenOfWijzigen(gelieerdePersoon.Persoon, gelieerdePersoon.Groep,
gebruikersRecht.PersoonsPermissies, gebruikersRecht.GroepsPermissies, gebruikersRecht.AfdelingsPermissies,
gebruikersRecht.IedereenPermissies);
#if KIPDORP
using (var tx = new TransactionScope())
{
#endif
_rechtenRepo.SaveChanges();
// Zoekt de gegeven gebruiker in active directory. Maakt die gebruiker aan als die nog
// niet bestaat. En voegt hem/haar toe aan de groep GapGebruikers.
ServiceHelper.CallService<IAdService, string>(
svc =>
svc.GapLoginAanvragen(p.AdNummer.Value, p.VoorNaam, p.Naam,
_gelieerdePersonenMgr.ContactEmail(gelieerdePersoon)));
#if KIPDORP
tx.Complete();
}
#endif
}
/// <summary>
/// Neemt de alle gebruikersrechten van de gelieerde persoon met gegeven
/// <paramref name="persoonID"/> af voor de groepen met gegeven <paramref name="groepIDs"/>
/// </summary>
/// <param name="persoonID">Id van persoon met af te nemen gebruikersrechten</param>
/// <param name="groepIDs">Id's van groepen waarvoor gebruikersrecht afgenomen moet worden.</param>
/// <remarks>In praktijk gebeurt dit door de vervaldatum in het verleden te leggen.</remarks>
public void RechtenAfnemen(int persoonID, int[] groepIDs)
{
var persoon = _personenRepo.ByID(persoonID);
Gav.Check(persoon);
if (persoon == null)
{
throw FaultExceptionHelper.GeenGav();
}
var teExpirenRechten =
(from g in persoon.GebruikersRechtV2
where (g.VervalDatum == null || g.VervalDatum >= DateTime.Today) && groepIDs.Contains(g.Groep.ID)
select g).ToList();
foreach (var gr in teExpirenRechten)
{
gr.VervalDatum = DateTime.Today.AddDays(-1);
}
_rechtenRepo.SaveChanges();
}
/// <summary>
/// Levert een redirection-url op naar de site van de verzekeraar
/// </summary>
/// <returns>Redirection-url naar de site van de verzekeraar</returns>
public string VerzekeringsUrlGet(int groepID)
{
int? adNummer = _authenticatieMgr.AdNummerGet();
GelieerdePersoon mijnGp = null;
if (adNummer == null)
{
throw FaultExceptionHelper.GeenGav();
}
var ik = (from p in _personenRepo.Select()
where p.AdNummer == adNummer
select p).First();
if (ik != null)
{
mijnGp = (from gp in ik.GelieerdePersoon
where gp.Groep.ID == groepID
select gp).FirstOrDefault();
}
if (mijnGp == null)
{
throw new FaultException<FoutNummerFault>(new FoutNummerFault
{
Bericht = Resources.KoppelingLoginPersoonOntbreekt,
FoutNummer = FoutNummer.KoppelingLoginPersoonOntbreekt
});
}
// haal puntkomma's uit onderdelen, want die zijn straks veldseparatiedingen
var naam = String.Format("{0} {1}", mijnGp.Persoon.VoorNaam, mijnGp.Persoon.Naam).Replace(';', ',');
var stamnr = (from gr in ik.GebruikersRechtV2
where gr.Groep.ID == groepID
select gr.Groep.Code).First().Replace(';', ',');
string email =
mijnGp.Communicatie.Where(comm => comm.CommunicatieType.ID == (int) CommunicatieTypeEnum.Email)
.OrderByDescending(comm => comm.Voorkeur)
.Select(comm => comm.Nummer).FirstOrDefault();
if (email == null)
{
throw new FaultException<FoutNummerFault>(new FoutNummerFault
{
Bericht = Resources.EmailOntbreekt,
FoutNummer = FoutNummer.EMailVerplicht
});
}
email = email.Replace(';', ',');
var cp = new CredentialsProvider(Settings.Default.EncryptieSleutel,
Settings.Default.HashSleutel);
var credentials = cp.Genereren(String.Format("{0};{1};{2};{3:dd/MM/yyyy H:mm:ss zzz}", naam, stamnr, email, DateTime.Now));
return String.Format(Settings.Default.UrlVerzekeraar,
HttpUtility.UrlEncode(credentials.GeencrypteerdeUserInfo),
HttpUtility.UrlEncode(credentials.Hash));
}
/// <summary>
/// Indien de ingelogde gebruiker lid is voor gegeven groep in het recentste werkjaar, dan wordt de id van dat lid terug gegeven
/// </summary>
public int? AangelogdeGebruikerLidIdGet(int groepID)
{
int? adNummer = _authenticatieMgr.AdNummerGet();
var ik = (from p in _personenRepo.Select()
where p.AdNummer == adNummer
select p).First();
// Mag ik mijn eigen gegevens lezen?
if (_autorisatieMgr.MagLezen(ik, ik))
{
throw FaultExceptionHelper.GeenGav();
}
var lps = (from gp in ik.GelieerdePersoon
where gp.Groep.ID == groepID
select gp).ToList();
var leden = lps.SelectMany(gp => gp.Lid).ToList();
if (!leden.Any())
{
return null;
}
var maxJaar = leden.Max(l => l.GroepsWerkJaar.WerkJaar);
return leden.First(l => l.GroepsWerkJaar.WerkJaar == maxJaar).ID;
}
/// <summary>
/// Levert de details van de persoon met gegeven <paramref name="adNummer"/>, inclusief gebruikersnaam.
/// </summary>
/// <param name="adNummer">AD-nummer van een persoon.</param>
/// <param name="aanMaken">Als deze <c>true</c> is, wordt een 'stub' aangemaakt als de persoon niet wordt gevonden.</param>
/// <returns>Details van de persoon met gegeven <paramref name="adNummer"/>.</returns>
public GebruikersDetail DetailsOphalen(int adNummer, bool aanMaken)
{
int? mijnAdNummer = _authenticatieMgr.AdNummerGet();
if (mijnAdNummer == null)
{
throw FaultExceptionHelper.FoutNummer(FoutNummer.KoppelingLoginPersoonOntbreekt, String.Format(
Resources.KoppelingLoginPersoonOntbreekt,
_authenticatieMgr.GebruikersNaamGet(),
mijnAdNummer));
}
var persoon = (from p in _personenRepo.Select()
where p.AdNummer == adNummer
select p).FirstOrDefault();
var ik = (from p in _personenRepo.Select()
where p.AdNummer == mijnAdNummer
select p).FirstOrDefault();
if (persoon == null && aanMaken)
{
// We gaan de persoon registreren. Als hij nog niet bestond, had hij nog geen rechten.
// TODO: gegevens ophalen uit Civi, ipv leeg te laten (zie #5612).
persoon = new Persoon
{
// FIXME: stub-naam is niet zo goed. Misschien login erin verwerken?
VoorNaam = adNummer.ToString(),
Naam = "AD-nummer",
AdNummer = mijnAdNummer,
Geslacht = GeslachtsType.Onbekend,
};
_personenRepo.Add(persoon);
_personenRepo.SaveChanges();
}
// Controleer gebruikersrechten. Ik test ook op AD-nummer, want als ik mezelf net heb
// aangemaakt loopt het anders fout.
if (adNummer != mijnAdNummer && !_autorisatieMgr.MagLezen(ik, persoon))
{
throw FaultExceptionHelper.GeenGav();
}
return _mappingHelper.Map<Persoon, GebruikersDetail>(persoon);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindAccess
{
/// <summary>
/// Strongly-typed collection for the CustomerDemographic class.
/// </summary>
[Serializable]
public partial class CustomerDemographicCollection : ActiveList<CustomerDemographic, CustomerDemographicCollection>
{
public CustomerDemographicCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>CustomerDemographicCollection</returns>
public CustomerDemographicCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
CustomerDemographic o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CustomerDemographics table.
/// </summary>
[Serializable]
public partial class CustomerDemographic : ActiveRecord<CustomerDemographic>, IActiveRecord
{
#region .ctors and Default Settings
public CustomerDemographic()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public CustomerDemographic(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public CustomerDemographic(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public CustomerDemographic(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CustomerDemographics", TableType.Table, DataService.GetInstance("NorthwindAccess"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarCustomerTypeID = new TableSchema.TableColumn(schema);
colvarCustomerTypeID.ColumnName = "CustomerTypeID";
colvarCustomerTypeID.DataType = DbType.String;
colvarCustomerTypeID.MaxLength = 10;
colvarCustomerTypeID.AutoIncrement = false;
colvarCustomerTypeID.IsNullable = false;
colvarCustomerTypeID.IsPrimaryKey = true;
colvarCustomerTypeID.IsForeignKey = false;
colvarCustomerTypeID.IsReadOnly = false;
colvarCustomerTypeID.DefaultSetting = @"";
colvarCustomerTypeID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerTypeID);
TableSchema.TableColumn colvarCustomerDesc = new TableSchema.TableColumn(schema);
colvarCustomerDesc.ColumnName = "CustomerDesc";
colvarCustomerDesc.DataType = DbType.String;
colvarCustomerDesc.MaxLength = 0;
colvarCustomerDesc.AutoIncrement = false;
colvarCustomerDesc.IsNullable = true;
colvarCustomerDesc.IsPrimaryKey = false;
colvarCustomerDesc.IsForeignKey = false;
colvarCustomerDesc.IsReadOnly = false;
colvarCustomerDesc.DefaultSetting = @"";
colvarCustomerDesc.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerDesc);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindAccess"].AddSchema("CustomerDemographics",schema);
}
}
#endregion
#region Props
[XmlAttribute("CustomerTypeID")]
[Bindable(true)]
public string CustomerTypeID
{
get { return GetColumnValue<string>(Columns.CustomerTypeID); }
set { SetColumnValue(Columns.CustomerTypeID, value); }
}
[XmlAttribute("CustomerDesc")]
[Bindable(true)]
public string CustomerDesc
{
get { return GetColumnValue<string>(Columns.CustomerDesc); }
set { SetColumnValue(Columns.CustomerDesc, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public NorthwindAccess.CustomerCustomerDemoCollection CustomerCustomerDemoRecords()
{
return new NorthwindAccess.CustomerCustomerDemoCollection().Where(CustomerCustomerDemo.Columns.CustomerTypeID, CustomerTypeID).Load();
}
#endregion
//no foreign key tables defined (0)
#region Many To Many Helpers
public NorthwindAccess.CustomerCollection GetCustomerCollection() { return CustomerDemographic.GetCustomerCollection(this.CustomerTypeID); }
public static NorthwindAccess.CustomerCollection GetCustomerCollection(string varCustomerTypeID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [Customers] INNER JOIN [CustomerCustomerDemo] ON [Customers].[CustomerID] = [CustomerCustomerDemo].[CustomerID] WHERE [CustomerCustomerDemo].[CustomerTypeID] = PARM__CustomerTypeID", CustomerDemographic.Schema.Provider.Name);
cmd.AddParameter("PARM__CustomerTypeID", varCustomerTypeID, DbType.String);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
CustomerCollection coll = new CustomerCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveCustomerMap(string varCustomerTypeID, CustomerCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = PARM__CustomerTypeID", CustomerDemographic.Schema.Provider.Name);
cmdDel.AddParameter("PARM__CustomerTypeID", varCustomerTypeID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (Customer item in items)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID);
varCustomerCustomerDemo.SetColumnValue("CustomerID", item.GetPrimaryKeyValue());
varCustomerCustomerDemo.Save();
}
}
public static void SaveCustomerMap(string varCustomerTypeID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = PARM__CustomerTypeID", CustomerDemographic.Schema.Provider.Name);
cmdDel.AddParameter("PARM__CustomerTypeID", varCustomerTypeID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID);
varCustomerCustomerDemo.SetColumnValue("CustomerID", l.Value);
varCustomerCustomerDemo.Save();
}
}
}
public static void SaveCustomerMap(string varCustomerTypeID , string[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = PARM__CustomerTypeID", CustomerDemographic.Schema.Provider.Name);
cmdDel.AddParameter("PARM__CustomerTypeID", varCustomerTypeID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (string item in itemList)
{
CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo();
varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID);
varCustomerCustomerDemo.SetColumnValue("CustomerID", item);
varCustomerCustomerDemo.Save();
}
}
public static void DeleteCustomerMap(string varCustomerTypeID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = PARM__CustomerTypeID", CustomerDemographic.Schema.Provider.Name);
cmdDel.AddParameter("PARM__CustomerTypeID", varCustomerTypeID, DbType.String);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerTypeID,string varCustomerDesc)
{
CustomerDemographic item = new CustomerDemographic();
item.CustomerTypeID = varCustomerTypeID;
item.CustomerDesc = varCustomerDesc;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varCustomerTypeID,string varCustomerDesc)
{
CustomerDemographic item = new CustomerDemographic();
item.CustomerTypeID = varCustomerTypeID;
item.CustomerDesc = varCustomerDesc;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CustomerTypeIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerDescColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerTypeID = @"CustomerTypeID";
public static string CustomerDesc = @"CustomerDesc";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[ActiveIssue(5283, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[ActiveIssue(5284, PlatformID.Windows)]
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
[PlatformSpecific(PlatformID.Linux | PlatformID.OSX)]
public void NegotiateStream_Ctor_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new NegotiateStream(new FakeNetworkStream(false, null)));
}
}
}
| |
#nullable disable
// ZlibCodec.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-November-03 15:40:51>
//
// ------------------------------------------------------------------
//
// This module defines a Codec for ZLIB compression and
// decompression. This code extends code that was based the jzlib
// implementation of zlib, but this code is completely novel. The codec
// class is new, and encapsulates some behaviors that are new, and some
// that were present in other classes in the jzlib code base. In
// keeping with the license for jzlib, the copyright to the jzlib code
// is included below.
//
// ------------------------------------------------------------------
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 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.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
//
// -----------------------------------------------------------------------
//
// This program is based on zlib-1.1.3; credit to authors
// Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
// and contributors of zlib.
//
// -----------------------------------------------------------------------
using System;
namespace SharpCompress.Compressors.Deflate
{
/// <summary>
/// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
/// </summary>
///
/// <remarks>
/// This class compresses and decompresses data according to the Deflate algorithm
/// and optionally, the ZLIB format, as documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>.
/// </remarks>
internal sealed class ZlibCodec
{
/// <summary>
/// The buffer from which data is taken.
/// </summary>
public byte[] InputBuffer;
/// <summary>
/// An index into the InputBuffer array, indicating where to start reading.
/// </summary>
public int NextIn;
/// <summary>
/// The number of bytes available in the InputBuffer, starting at NextIn.
/// </summary>
/// <remarks>
/// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesIn;
/// <summary>
/// Total number of bytes read so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesIn;
/// <summary>
/// Buffer to store output data.
/// </summary>
public byte[] OutputBuffer;
/// <summary>
/// An index into the OutputBuffer array, indicating where to start writing.
/// </summary>
public int NextOut;
/// <summary>
/// The number of bytes available in the OutputBuffer, starting at NextOut.
/// </summary>
/// <remarks>
/// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesOut;
/// <summary>
/// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesOut;
/// <summary>
/// used for diagnostics, when something goes wrong!
/// </summary>
public string Message;
internal DeflateManager dstate;
internal InflateManager istate;
internal uint _adler32;
/// <summary>
/// The compression level to use in this codec. Useful only in compression mode.
/// </summary>
public CompressionLevel CompressLevel = CompressionLevel.Default;
/// <summary>
/// The number of Window Bits to use.
/// </summary>
/// <remarks>
/// This gauges the size of the sliding window, and hence the
/// compression effectiveness as well as memory consumption. It's best to just leave this
/// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
/// a 32k window.
/// </remarks>
public int WindowBits = ZlibConstants.WindowBitsDefault;
/// <summary>
/// The compression strategy to use.
/// </summary>
/// <remarks>
/// This is only effective in compression. The theory offered by ZLIB is that different
/// strategies could potentially produce significant differences in compression behavior
/// for different data sets. Unfortunately I don't have any good recommendations for how
/// to set it differently. When I tested changing the strategy I got minimally different
/// compression performance. It's best to leave this property alone if you don't have a
/// good feel for it. Or, you may want to produce a test harness that runs through the
/// different strategy options and evaluates them on different file types. If you do that,
/// let me know your results.
/// </remarks>
public CompressionStrategy Strategy = CompressionStrategy.Default;
/// <summary>
/// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
/// </summary>
public int Adler32 => (int)_adler32;
/// <summary>
/// Create a ZlibCodec.
/// </summary>
/// <remarks>
/// If you use this default constructor, you will later have to explicitly call
/// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
/// or decompress.
/// </remarks>
public ZlibCodec()
{
}
/// <summary>
/// Create a ZlibCodec that either compresses or decompresses.
/// </summary>
/// <param name="mode">
/// Indicates whether the codec should compress (deflate) or decompress (inflate).
/// </param>
public ZlibCodec(CompressionMode mode)
{
if (mode == CompressionMode.Compress)
{
int rc = InitializeDeflate();
if (rc != ZlibConstants.Z_OK)
{
throw new ZlibException("Cannot initialize for deflate.");
}
}
else if (mode == CompressionMode.Decompress)
{
int rc = InitializeInflate();
if (rc != ZlibConstants.Z_OK)
{
throw new ZlibException("Cannot initialize for inflate.");
}
}
else
{
throw new ZlibException("Invalid ZlibStreamFlavor.");
}
}
/// <summary>
/// Initialize the inflation state.
/// </summary>
/// <remarks>
/// It is not necessary to call this before using the ZlibCodec to inflate data;
/// It is implicitly called when you call the constructor.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate()
{
return InitializeInflate(WindowBits);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to
/// govern the handling of RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// By default, the ZLIB header defined in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
/// you want to read a zlib stream you should specify true for
/// expectRfc1950Header. If you have a deflate stream, you will want to specify
/// false. It is only necessary to invoke this initializer explicitly if you
/// want to specify false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
/// pair when reading the stream of data to be inflated.</param>
///
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(bool expectRfc1950Header)
{
return InitializeInflate(WindowBits, expectRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for inflation, with the specified number of window bits.
/// </summary>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeInflate(int windowBits)
{
WindowBits = windowBits;
return InitializeInflate(windowBits, true);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to govern the handling of
/// RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// If you want to read a zlib stream you should specify true for
/// expectRfc1950Header. In this case, the library will expect to find a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
/// GZIP stream, which does not have such a header, you will want to specify
/// false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
/// the stream of data to be inflated.</param>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(int windowBits, bool expectRfc1950Header)
{
WindowBits = windowBits;
if (dstate != null)
{
throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
}
istate = new InflateManager(expectRfc1950Header);
return istate.Initialize(this, windowBits);
}
/// <summary>
/// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
/// AvailableBytesOut before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void InflateBuffer()
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec decompressor = new ZlibCodec();
///
/// Console.WriteLine("\n============================================");
/// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
/// MemoryStream ms = new MemoryStream(DecompressedBytes);
///
/// int rc = decompressor.InitializeInflate();
///
/// decompressor.InputBuffer = CompressedBytes;
/// decompressor.NextIn = 0;
/// decompressor.AvailableBytesIn = CompressedBytes.Length;
///
/// decompressor.OutputBuffer = buffer;
///
/// // pass 1: inflate
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// if (buffer.Length - decompressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// decompressor.EndInflate();
/// }
///
/// </code>
/// </example>
/// <param name="flush">The flush to use when inflating.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int Inflate(FlushType flush)
{
if (istate is null)
{
throw new ZlibException("No Inflate State!");
}
return istate.Inflate(flush);
}
/// <summary>
/// Ends an inflation session.
/// </summary>
/// <remarks>
/// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
/// After calling this you cannot call Inflate() without a intervening call to one of the
/// InitializeInflate() overloads.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int EndInflate()
{
if (istate is null)
{
throw new ZlibException("No Inflate State!");
}
int ret = istate.End();
istate = null;
return ret;
}
/// <summary>
/// I don't know what this does!
/// </summary>
/// <returns>Z_OK if everything goes well.</returns>
public int SyncInflate()
{
if (istate is null)
{
throw new ZlibException("No Inflate State!");
}
return istate.Sync();
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation.
/// </summary>
/// <remarks>
/// The codec will use the MAX window bits and the default level of compression.
/// </remarks>
/// <example>
/// <code>
/// int bufferSize = 40000;
/// byte[] CompressedBytes = new byte[bufferSize];
/// byte[] DecompressedBytes = new byte[bufferSize];
///
/// ZlibCodec compressor = new ZlibCodec();
///
/// compressor.InitializeDeflate(CompressionLevel.Default);
///
/// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
///
/// compressor.OutputBuffer = CompressedBytes;
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = CompressedBytes.Length;
///
/// while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
/// {
/// compressor.Deflate(FlushType.None);
/// }
///
/// while (true)
/// {
/// int rc= compressor.Deflate(FlushType.Finish);
/// if (rc == ZlibConstants.Z_STREAM_END) break;
/// }
///
/// compressor.EndDeflate();
///
/// </code>
/// </example>
/// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
public int InitializeDeflate()
{
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified
/// CompressionLevel. It will emit a ZLIB stream as it compresses.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level)
{
CompressLevel = level;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the explicit flag governing whether to emit an RFC1950 header byte pair.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified CompressionLevel.
/// If you want to generate a zlib stream, you should specify true for
/// wantRfc1950Header. In this case, the library will emit a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
{
CompressLevel = level;
return _InternalInitializeDeflate(wantRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the specified number of window bits.
/// </summary>
/// <remarks>
/// The codec will use the specified number of window bits and the specified CompressionLevel.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits)
{
CompressLevel = level;
WindowBits = bits;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified
/// CompressionLevel, the specified number of window bits, and the explicit flag
/// governing whether to emit an RFC1950 header byte pair.
/// </summary>
///
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
{
CompressLevel = level;
WindowBits = bits;
return _InternalInitializeDeflate(wantRfc1950Header);
}
private int _InternalInitializeDeflate(bool wantRfc1950Header)
{
if (istate != null)
{
throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
}
dstate = new DeflateManager();
dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
return dstate.Initialize(this, CompressLevel, WindowBits, Strategy);
}
/// <summary>
/// Deflate one batch of data.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void DeflateBuffer(CompressionLevel level)
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec compressor = new ZlibCodec();
///
/// Console.WriteLine("\n============================================");
/// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
/// MemoryStream ms = new MemoryStream();
///
/// int rc = compressor.InitializeDeflate(level);
///
/// compressor.InputBuffer = UncompressedBytes;
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = UncompressedBytes.Length;
///
/// compressor.OutputBuffer = buffer;
///
/// // pass 1: deflate
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("deflating: " + compressor.Message);
///
/// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("deflating: " + compressor.Message);
///
/// if (buffer.Length - compressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// compressor.EndDeflate();
///
/// ms.Seek(0, SeekOrigin.Begin);
/// CompressedBytes = new byte[compressor.TotalBytesOut];
/// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
/// }
/// </code>
/// </example>
/// <param name="flush">whether to flush all data as you deflate. Generally you will want to
/// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
/// flush everything.
/// </param>
/// <returns>Z_OK if all goes well.</returns>
public int Deflate(FlushType flush)
{
if (dstate is null)
{
throw new ZlibException("No Deflate State!");
}
return dstate.Deflate(flush);
}
/// <summary>
/// End a deflation session.
/// </summary>
/// <remarks>
/// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public int EndDeflate()
{
if (dstate is null)
{
throw new ZlibException("No Deflate State!");
}
// TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
//int ret = dstate.End();
dstate = null;
return ZlibConstants.Z_OK; //ret;
}
/// <summary>
/// Reset a codec for another deflation session.
/// </summary>
/// <remarks>
/// Call this to reset the deflation state. For example if a thread is deflating
/// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
/// block and before the next Deflate(None) of the second block.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public void ResetDeflate()
{
if (dstate is null)
{
throw new ZlibException("No Deflate State!");
}
dstate.Reset();
}
/// <summary>
/// Set the CompressionStrategy and CompressionLevel for a deflation session.
/// </summary>
/// <param name="level">the level of compression to use.</param>
/// <param name="strategy">the strategy to use for compression.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
{
if (dstate is null)
{
throw new ZlibException("No Deflate State!");
}
return dstate.SetParams(level, strategy);
}
/// <summary>
/// Set the dictionary to be used for either Inflation or Deflation.
/// </summary>
/// <param name="dictionary">The dictionary bytes to use.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDictionary(byte[] dictionary)
{
if (istate != null)
{
return istate.SetDictionary(dictionary);
}
if (dstate != null)
{
return dstate.SetDictionary(dictionary);
}
throw new ZlibException("No Inflate or Deflate state!");
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
internal void flush_pending()
{
int len = dstate.pendingCount;
if (len > AvailableBytesOut)
{
len = AvailableBytesOut;
}
if (len == 0)
{
return;
}
if (dstate.pending.Length <= dstate.nextPending ||
OutputBuffer.Length <= NextOut ||
dstate.pending.Length < (dstate.nextPending + len) ||
OutputBuffer.Length < (NextOut + len))
{
throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
dstate.pending.Length, dstate.pendingCount));
}
Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
NextOut += len;
dstate.nextPending += len;
TotalBytesOut += len;
AvailableBytesOut -= len;
dstate.pendingCount -= len;
if (dstate.pendingCount == 0)
{
dstate.nextPending = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
internal int read_buf(byte[] buf, int start, int size)
{
int len = AvailableBytesIn;
if (len > size)
{
len = size;
}
if (len == 0)
{
return 0;
}
AvailableBytesIn -= len;
if (dstate.WantRfc1950HeaderBytes)
{
_adler32 = Algorithms.Adler32.Calculate(_adler32, InputBuffer.AsSpan(NextIn, len));
}
Array.Copy(InputBuffer, NextIn, buf, start, len);
NextIn += len;
TotalBytesIn += len;
return len;
}
}
}
| |
using System;
using System.Threading;
namespace Amib.Threading
{
/// <summary>
/// Summary description for STPStartInfo.
/// </summary>
public class STPStartInfo : WIGStartInfo
{
private int _idleTimeout = SmartThreadPool.DefaultIdleTimeout;
private int _minWorkerThreads = SmartThreadPool.DefaultMinWorkerThreads;
private int _maxWorkerThreads = SmartThreadPool.DefaultMaxWorkerThreads;
private ThreadPriority _threadPriority = SmartThreadPool.DefaultThreadPriority;
private string _pcInstanceName = SmartThreadPool.DefaultPerformanceCounterInstanceName;
public STPStartInfo()
{
}
public STPStartInfo(STPStartInfo stpStartInfo)
: base(stpStartInfo)
{
_idleTimeout = stpStartInfo._idleTimeout;
_minWorkerThreads = stpStartInfo._minWorkerThreads;
_maxWorkerThreads = stpStartInfo._maxWorkerThreads;
_threadPriority = stpStartInfo._threadPriority;
_pcInstanceName = stpStartInfo._pcInstanceName;
}
/// <summary>
/// Get/Set the idle timeout in milliseconds.
/// If a thread is idle (starved) longer than IdleTimeout then it may quit.
/// </summary>
public virtual int IdleTimeout
{
get { return _idleTimeout; }
set { _idleTimeout = value; }
}
/// <summary>
/// Get/Set the lower limit of threads in the pool.
/// </summary>
public virtual int MinWorkerThreads
{
get { return _minWorkerThreads; }
set { _minWorkerThreads = value; }
}
/// <summary>
/// Get/Set the upper limit of threads in the pool.
/// </summary>
public virtual int MaxWorkerThreads
{
get { return _maxWorkerThreads; }
set { _maxWorkerThreads = value; }
}
/// <summary>
/// Get/Set the scheduling priority of the threads in the pool.
/// The Os handles the scheduling.
/// </summary>
public virtual ThreadPriority ThreadPriority
{
get { return _threadPriority; }
set { _threadPriority = value; }
}
/// <summary>
/// Get/Set the performance counter instance name of this SmartThreadPool
/// The default is null which indicate not to use performance counters at all.
/// </summary>
public virtual string PerformanceCounterInstanceName
{
get { return _pcInstanceName; }
set { _pcInstanceName = value; }
}
/// <summary>
/// Get a readonly version of this STPStartInfo.
/// </summary>
/// <returns>Returns a readonly reference to this STPStartInfo</returns>
public new STPStartInfo AsReadOnly()
{
return new STPStartInfoRO(this);
}
#region STPStartInfoRO class
private class STPStartInfoRO : STPStartInfo
{
private readonly STPStartInfo _stpStartInfo;
public STPStartInfoRO(STPStartInfo stpStartInfo)
{
_stpStartInfo = stpStartInfo;
}
/// <summary>
/// Get/Set the idle timeout in milliseconds.
/// If a thread is idle (starved) longer than IdleTimeout then it may quit.
/// </summary>
public override int IdleTimeout
{
get { return _stpStartInfo.IdleTimeout; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the lower limit of threads in the pool.
/// </summary>
public override int MinWorkerThreads
{
get { return _stpStartInfo.MinWorkerThreads; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the upper limit of threads in the pool.
/// </summary>
public override int MaxWorkerThreads
{
get { return _stpStartInfo.MaxWorkerThreads; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the scheduling priority of the threads in the pool.
/// The Os handles the scheduling.
/// </summary>
public override ThreadPriority ThreadPriority
{
get { return _stpStartInfo.ThreadPriority; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the performance counter instance name of this SmartThreadPool
/// The default is null which indicate not to use performance counters at all.
/// </summary>
public override string PerformanceCounterInstanceName
{
get { return _stpStartInfo.PerformanceCounterInstanceName; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get if to use the caller's security context
/// </summary>
public override bool UseCallerCallContext
{
get { return _stpStartInfo.UseCallerCallContext; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get if to use the caller's HTTP context
/// </summary>
public override bool UseCallerHttpContext
{
get { return _stpStartInfo.UseCallerHttpContext; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get if to dispose of the state object of a work item
/// </summary>
public override bool DisposeOfStateObjects
{
get { return _stpStartInfo.DisposeOfStateObjects; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the run the post execute options
/// </summary>
public override CallToPostExecute CallToPostExecute
{
get { return _stpStartInfo.CallToPostExecute; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the default post execute callback
/// </summary>
public override PostExecuteWorkItemCallback PostExecuteWorkItemCallback
{
get { return _stpStartInfo.PostExecuteWorkItemCallback; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get if the work items execution should be suspended until the Start()
/// method is called.
/// </summary>
public override bool StartSuspended
{
get { return _stpStartInfo.StartSuspended; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Get the default priority that a work item gets when it is enqueued
/// </summary>
public override WorkItemPriority WorkItemPriority
{
get { return _stpStartInfo.WorkItemPriority; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
/// <summary>
/// Indicate if QueueWorkItem of Action<...>/Func<...> fill the
/// arguments as an object array into the state of the work item.
/// The arguments can be access later by IWorkItemResult.State.
/// </summary>
public override bool FillStateWithArgs
{
get { return _stpStartInfo.FillStateWithArgs; }
set { throw new NotSupportedException("This is a readonly instance and set is not supported"); }
}
}
#endregion
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using GgpGrpc.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using YetiCommon;
using YetiCommon.SSH;
using YetiVSI.Metrics;
namespace YetiVSI
{
[Flags]
public enum MountConfiguration
{
// Default configuration, /mnt/developer is bind-mounted to /srv/game/assets.
None = 0,
// /mnt/developer is mounted as top-level overlay to /srv/game/assets.
InstanceStorageOverlay = 1 << 0,
// A package is mounted to /mnt/package.
PackageMounted = 1 << 1,
// A game was run directly, e.g. with ggp run --package.
RunFromPackage = 1 << 2,
// A local workstation directory is mounted to /mnt/workstation and
// visible in /srv/game/assets, i.e. asset streaming is active.
LocalDirMounted = 1 << 3,
}
/// <summary>
/// Provides logic to verify gamelet mount state before running the application.
/// </summary>
public class GameletMountChecker
{
public const string ReadMountsCmd = "cat /proc/mounts";
const string _overlayFileSystem = "overlay";
// Possible values are be fuse.sshfs (AS20) or fuse.cdc_fuse_fs (AS30).
const string _fuseFileSystem = "fuse.";
readonly HashSet<string> _keys = new HashSet<string>
{
YetiConstants.GameAssetsMountingPoint,
YetiConstants.PackageMountingPoint,
YetiConstants.DeveloperMountingPoint,
YetiConstants.WorkstationMountingPoint
};
readonly IRemoteCommand _remoteCommand;
readonly IDialogUtil _dialogUtil;
readonly CancelableTask.Factory _cancelableTaskFactory;
public GameletMountChecker(IRemoteCommand remoteCommand, IDialogUtil dialogUtil,
CancelableTask.Factory cancelableTaskFactory)
{
_remoteCommand = remoteCommand;
_dialogUtil = dialogUtil;
_cancelableTaskFactory = cancelableTaskFactory;
}
readonly StringComparison _comparisonType = StringComparison.OrdinalIgnoreCase;
public MountConfiguration GetConfiguration(Gamelet gamelet, ActionRecorder actionRecorder)
{
MountConfiguration mountConfiguration = MountConfiguration.None;
List<string> mountsInfo = ReadMountsContentOrDefault(gamelet, actionRecorder);
if (mountsInfo.Count == 0)
{
return mountConfiguration;
}
Dictionary<string, Device> devices = GetDevices(mountsInfo);
Device gameAssetsDevice = devices[YetiConstants.GameAssetsMountingPoint];
Device workstationDevice = devices[YetiConstants.WorkstationMountingPoint];
Device packageDevice = devices[YetiConstants.PackageMountingPoint];
Device developerDevice = devices[YetiConstants.DeveloperMountingPoint];
bool gameAssetsIsOverlay =
gameAssetsDevice?.FileSystemType.Equals(_overlayFileSystem, _comparisonType) ??
false;
// Check whether /srv/game/assets is mounted as overlayfs with /mnt/developer as
// mount dir. gameAssetsDevice.Parameters lists the overlay layers, e.g.
// lowerdir=/home/cloudcast/.overlayfs_workaround_layer:/mnt/workstation:/mnt/package.
if (gameAssetsIsOverlay &&
gameAssetsDevice.Parameters.Contains(YetiConstants.DeveloperMountingPoint))
{
mountConfiguration |= MountConfiguration.InstanceStorageOverlay;
}
if (workstationDevice?.FileSystemType.StartsWith(_fuseFileSystem, _comparisonType) ??
false)
{
if (gameAssetsIsOverlay &&
gameAssetsDevice.Parameters.Contains(YetiConstants.WorkstationMountingPoint))
{
// Mounted as overlay, e.g. 'ggp instance mount --local-dir --package'.
mountConfiguration |= MountConfiguration.LocalDirMounted;
}
else if (gameAssetsDevice?.FileSystemType.StartsWith(
_fuseFileSystem, _comparisonType) ?? false)
{
// Mounted as bind-mount, e.g. 'ggp instance mount --local-dir'.
mountConfiguration |= MountConfiguration.LocalDirMounted;
}
}
if (!string.IsNullOrWhiteSpace(packageDevice?.Address))
{
if (gameAssetsIsOverlay &&
gameAssetsDevice.Parameters.Contains(YetiConstants.PackageMountingPoint))
{
// Mounted as overlay, e.g. 'ggp instance mount --local-dir --package'.
mountConfiguration |= MountConfiguration.PackageMounted;
}
else if (packageDevice.Address.Equals(gameAssetsDevice?.Address, _comparisonType))
{
// Mounted as bind-mount, e.g. 'ggp instance mount --package'.
mountConfiguration |= MountConfiguration.PackageMounted;
}
}
if (gameAssetsDevice != null &&
!gameAssetsDevice.Address.Equals(developerDevice?.Address, _comparisonType) &&
!gameAssetsDevice.Address.Equals(workstationDevice?.Address, _comparisonType) &&
!gameAssetsDevice.Address.Equals(packageDevice?.Address, _comparisonType) &&
!gameAssetsIsOverlay)
{
// Game was run from package, e.g. 'ggp run --package'.
mountConfiguration |= MountConfiguration.RunFromPackage;
}
return mountConfiguration;
}
/// <summary>
/// Returns true iff writes to /mnt/developer are not visible in /srv/game/assets.
/// </summary>
/// <param name="currentMountConfiguration">
/// Mount configuration as returned by GetConfiguration()
/// </param>
public bool IsGameAssetsDetachedFromDeveloperFolder(
MountConfiguration currentMountConfiguration) =>
currentMountConfiguration != MountConfiguration.None &&
!currentMountConfiguration.HasFlag(MountConfiguration.InstanceStorageOverlay);
List<string> ReadMountsContentOrDefault(Gamelet gamelet, ActionRecorder actionRecorder)
{
List<string> content = new List<string>();
ICancelableTask getMountsTask = _cancelableTaskFactory.Create(
TaskMessages.CheckingMountInfo,
async _ =>
{
content = await _remoteCommand.RunWithSuccessCapturingOutputAsync(
new SshTarget(gamelet), ReadMountsCmd) ?? new List<string>();
});
try
{
getMountsTask.RunAndRecord(actionRecorder, ActionType.GameletReadMounts);
return content;
}
catch (ProcessException e)
{
Trace.WriteLine($"Error reading /proc/mounts file: {e.Message}");
_dialogUtil.ShowError(ErrorStrings.FailedToStartRequiredProcess(e.Message), e);
return content;
}
finally
{
string joinedContent = string.Join("\n\t", content);
Trace.WriteLine($"Gamelet /proc/mounts:{Environment.NewLine}{joinedContent}");
}
}
public class Device
{
public Device(string address, string fileSystemType, string parameters)
{
Address = address;
FileSystemType = fileSystemType;
Parameters = parameters;
}
public string Address { get; }
public string FileSystemType { get; }
public string Parameters { get; }
}
/// <summary>
/// Returns dictionary of the mounting points of interest (/srv/game/assets, /mnt/package,
/// /mnt/developer) to the devices they are currently mounted to.
/// Format of /proc/mounts is:
/// 1st column - device that is mounted;
/// 2nd column - the mount point;
/// 3rd column - the file-system type;
/// 4th column - file system parameters, e.g. read-only (ro), read-write (rw);
/// 5th, 6th column - place-holders;
/// </summary>
/// <param name="procMountsContent">Content of /proc/mounts file on the gamelet.</param>
/// <returns>Dictionary of mounting point to device.</returns>
public Dictionary<string, Device> GetDevices(IEnumerable<string> procMountsContent)
{
var mountingPointToDevice = new Dictionary<string, Device>();
foreach (string key in _keys)
{
mountingPointToDevice[key] = null;
}
foreach (string mountInfo in procMountsContent)
{
// Split the line into column values.
string[] items = mountInfo.Split(' ');
if (items.Length != 6)
{
Trace.WriteLine($"Line {mountInfo} from /proc/mounts file is corrupted");
continue;
}
// Read mounting point of this line.
string mountingPoint = items[1];
if (_keys.Contains(mountingPoint))
{
// Get device from the line and add it to the resulting dictionary.
mountingPointToDevice[mountingPoint] = new Device(items[0], items[2], items[3]);
}
}
return mountingPointToDevice;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.ServiceModel.Channels;
using System.Xml;
namespace System.ServiceModel
{
public class NetTcpBinding : Binding
{
// private BindingElements
private TcpTransportBindingElement _transport;
private BinaryMessageEncodingBindingElement _encoding;
private long _maxBufferPoolSize;
private NetTcpSecurity _security = new NetTcpSecurity();
public NetTcpBinding() { Initialize(); }
public NetTcpBinding(SecurityMode securityMode)
: this()
{
_security.Mode = securityMode;
}
public NetTcpBinding(string configurationName)
: this()
{
if (!String.IsNullOrEmpty(configurationName))
{
throw ExceptionHelper.PlatformNotSupported();
}
}
private NetTcpBinding(TcpTransportBindingElement transport,
BinaryMessageEncodingBindingElement encoding,
NetTcpSecurity security)
: this()
{
_security = security;
}
[DefaultValue(ConnectionOrientedTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get { return _transport.TransferMode; }
set { _transport.TransferMode = value; }
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get { return _maxBufferPoolSize; }
set
{
_maxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get { return _transport.MaxBufferSize; }
set { _transport.MaxBufferSize = value; }
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get { return _transport.MaxReceivedMessageSize; }
set { _transport.MaxReceivedMessageSize = value; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get { return _encoding.ReaderQuotas; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
value.CopyTo(_encoding.ReaderQuotas);
}
}
public override string Scheme { get { return _transport.Scheme; } }
public EnvelopeVersion EnvelopeVersion
{
get { return EnvelopeVersion.Soap12; }
}
public NetTcpSecurity Security
{
get { return _security; }
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
_security = value;
}
}
private void Initialize()
{
_transport = new TcpTransportBindingElement();
_encoding = new BinaryMessageEncodingBindingElement();
// NetNative and CoreCLR initialize to what TransportBindingElement does in the desktop
// This property is not available in shipped contracts
_maxBufferPoolSize = TransportDefaults.MaxBufferPoolSize;
}
// check that properties of the HttpTransportBindingElement and
// MessageEncodingBindingElement not exposed as properties on BasicHttpBinding
// match default values of the binding elements
private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding)
{
if (!_transport.IsMatch(transport))
return false;
if (!_encoding.IsMatch(encoding))
return false;
return true;
}
private void CheckSettings()
{
#if FEATURE_NETNATIVE // In .NET Native, some settings for the binding security are not supported; this check is not necessary for CoreCLR
NetTcpSecurity security = this.Security;
if (security == null)
{
return;
}
SecurityMode mode = security.Mode;
if (mode == SecurityMode.None)
{
return;
}
else if (mode == SecurityMode.Message)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode)));
}
// Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported.
if (mode == SecurityMode.TransportWithMessageCredential)
{
MessageSecurityOverTcp message = security.Message;
if (message != null)
{
MessageCredentialType mct = message.ClientCredentialType;
if ((mct == MessageCredentialType.Certificate) || (mct == MessageCredentialType.IssuedToken) || (mct == MessageCredentialType.Windows))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Message.ClientCredentialType", mct)));
}
}
}
// Transport.ClientCredentialType = Certificate is not supported.
Contract.Assert((mode == SecurityMode.Transport) || (mode == SecurityMode.TransportWithMessageCredential), "Unexpected SecurityMode value: " + mode);
TcpTransportSecurity transport = security.Transport;
if ((transport != null) && (transport.ClientCredentialType == TcpClientCredentialType.Certificate))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType)));
}
#endif // FEATURE_NETNATIVE
}
public override BindingElementCollection CreateBindingElements()
{
this.CheckSettings();
// return collection of BindingElements
BindingElementCollection bindingElements = new BindingElementCollection();
// order of BindingElements is important
// add security (*optional)
SecurityBindingElement wsSecurity = CreateMessageSecurity();
if (wsSecurity != null)
bindingElements.Add(wsSecurity);
// add encoding
bindingElements.Add(_encoding);
// add transport security
BindingElement transportSecurity = CreateTransportSecurity();
if (transportSecurity != null)
{
bindingElements.Add(transportSecurity);
}
// add transport (tcp)
bindingElements.Add(_transport);
return bindingElements.Clone();
}
internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
{
binding = null;
if (elements.Count > 6)
return false;
// collect all binding elements
TcpTransportBindingElement transport = null;
BinaryMessageEncodingBindingElement encoding = null;
SecurityBindingElement wsSecurity = null;
BindingElement transportSecurity = null;
foreach (BindingElement element in elements)
{
if (element is SecurityBindingElement)
wsSecurity = element as SecurityBindingElement;
else if (element is TransportBindingElement)
transport = element as TcpTransportBindingElement;
else if (element is MessageEncodingBindingElement)
encoding = element as BinaryMessageEncodingBindingElement;
else
{
if (transportSecurity != null)
return false;
transportSecurity = element;
}
}
if (transport == null)
return false;
if (encoding == null)
return false;
TcpTransportSecurity tcpTransportSecurity = new TcpTransportSecurity();
UnifiedSecurityMode mode = GetModeFromTransportSecurity(transportSecurity);
NetTcpSecurity security;
if (!TryCreateSecurity(wsSecurity, mode, false /*session != null*/, transportSecurity, tcpTransportSecurity, out security))
return false;
if (!SetTransportSecurity(transportSecurity, security.Mode, tcpTransportSecurity))
return false;
NetTcpBinding netTcpBinding = new NetTcpBinding(transport, encoding, security);
if (!netTcpBinding.IsBindingElementsMatch(transport, encoding))
return false;
binding = netTcpBinding;
return true;
}
private BindingElement CreateTransportSecurity()
{
return _security.CreateTransportSecurity();
}
private static UnifiedSecurityMode GetModeFromTransportSecurity(BindingElement transport)
{
return NetTcpSecurity.GetModeFromTransportSecurity(transport);
}
private static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity)
{
return NetTcpSecurity.SetTransportSecurity(transport, mode, transportSecurity);
}
private SecurityBindingElement CreateMessageSecurity()
{
if (_security.Mode == SecurityMode.Message || _security.Mode == SecurityMode.TransportWithMessageCredential)
{
throw ExceptionHelper.PlatformNotSupported("NetTcpBinding.CreateMessageSecurity is not supported.");
}
else
{
return null;
}
}
private static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, bool isReliableSession, BindingElement transportSecurity, TcpTransportSecurity tcpTransportSecurity, out NetTcpSecurity security)
{
if (sbe != null)
mode &= UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential;
else
mode &= ~(UnifiedSecurityMode.Message | UnifiedSecurityMode.TransportWithMessageCredential);
SecurityMode securityMode = SecurityModeHelper.ToSecurityMode(mode);
Contract.Assert(SecurityModeHelper.IsDefined(securityMode), string.Format("Invalid SecurityMode value: {0}.", securityMode.ToString()));
if (NetTcpSecurity.TryCreate(sbe, securityMode, isReliableSession, transportSecurity, tcpTransportSecurity, out security))
return true;
return false;
}
}
}
| |
// Resharper disable InconsistentNaming
namespace PokerTell.PokerHand.Tests.ViewModels
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using Moq;
using NUnit.Framework;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.PokerHand.Analyzation;
using PokerTell.PokerHand.Services;
using PokerTell.PokerHand.Tests.Fakes;
using PokerTell.PokerHand.ViewModels;
using PokerTell.UnitTests;
using PokerTell.UnitTests.Tools;
using Tools;
using Tools.Interfaces;
[TestFixture]
[RequiresSTA]
public class HandHistoriesViewModelTests : TestWithLog
{
IHandHistoriesViewModel _viewModel;
IUnityContainer _container;
[SetUp]
public void _Init()
{
_container = new UnityContainer()
.RegisterConstructor<IHandHistoryViewModel, HandHistoryViewModel>()
.RegisterType<IItemsPagesManager<IHandHistoryViewModel>, ItemsPagesManager<IHandHistoryViewModel>>()
.RegisterType<IHandHistoriesFilter, HandHistoriesFilter>()
.RegisterType<IHandHistoriesViewModel, FakeHandHistoriesViewModel>();
_viewModel = _container.Resolve<IHandHistoriesViewModel>();
}
[Test]
public void InitializeWith_EmptyHands_KeepsHandHistoryViewModelsEmpty()
{
IList<IConvertedPokerHand> hands = new List<IConvertedPokerHand>();
_viewModel.InitializeWith(hands);
Assert.That(_viewModel.HandHistoriesOnPage.Count(), Is.EqualTo(0));
}
[Test]
public void InitializeWith_OneHand_AddsOneHandHistoryViewModels()
{
var hand = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand };
_viewModel.InitializeWith(hands);
Assert.That(_viewModel.HandHistoriesOnPage.Count(), Is.EqualTo(1));
}
[Test]
public void InitializeWith_OneHandWithHeroName_AssignsHeroNameToFilterHeroName()
{
var handHistoriesFilter_Mock = new Mock<IHandHistoriesFilter>();
const string heroName = "some hero";
var hand = new ConvertedPokerHand { HeroName = heroName };
var hands = new List<IConvertedPokerHand> { hand };
_container
.RegisterInstance(handHistoriesFilter_Mock.Object)
.Resolve<IHandHistoriesViewModel>()
.InitializeWith(hands);
handHistoriesFilter_Mock.VerifySet(f => f.HeroName = heroName);
}
[Test]
public void InitializeWith_OneHandWithoutHeroName_DoesNotAssignHeroNameToFilterHeroName()
{
var handHistoriesFilter_Mock = new Mock<IHandHistoriesFilter>();
var hand = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand };
_container
.RegisterInstance(handHistoriesFilter_Mock.Object)
.Resolve<IHandHistoriesViewModel>()
.InitializeWith(hands);
handHistoriesFilter_Mock.VerifySet(f => f.HeroName = It.IsAny<string>(), Times.Never());
}
[Test]
public void InitializeWith_TwoHands_AddsTwoHandHistoryViewModels()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel.InitializeWith(hands);
Assert.That(_viewModel.HandHistoriesOnPage.Count(), Is.EqualTo(2));
}
[Test]
public void BinaryDeserialize_Serialized_RestoresItemsHandHistoriesOnPage()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel.InitializeWith(hands);
Assert.That(_viewModel.BinaryDeserializedInMemory().HandHistoriesOnPage,
Is.EqualTo(_viewModel.HandHistoriesOnPage));
}
[Test]
public void BinaryDeserialize_Serialized_RestoresSelectedHandHistories()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel.InitializeWith(hands);
Assert.That(_viewModel.BinaryDeserializedInMemory().SelectedHandHistories,
Is.EqualTo(_viewModel.SelectedHandHistories));
}
[Test]
public void BinaryDeserialize_Serialized_RestoresPageNumbers()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands);
Assert.That(_viewModel.BinaryDeserializedInMemory().PageNumbers, Is.EqualTo(_viewModel.PageNumbers));
}
[Test]
public void BinaryDeserialize_Serialized_RestoresHandHistoriesFilter()
{
IList<IConvertedPokerHand> hands = new List<IConvertedPokerHand>();
_viewModel.InitializeWith(hands);
_viewModel.HandHistoriesFilter.HeroName = "someName";
_viewModel.HandHistoriesFilter.ShowPreflopFolds = true;
_viewModel.HandHistoriesFilter.ShowSawFlop = true;
Affirm.That(_viewModel.BinaryDeserializedInMemory().HandHistoriesFilter)
.IsEqualTo(_viewModel.HandHistoriesFilter);
}
[Test]
public void SelectAllHandHistoriesOnPage_TwoHandsOnPage_SelectsTwoHands()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.SelectAllHandHistoriesOnPageCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(2));
}
[Test]
public void SelectAllShownHandHistories_TwoHandsShownAndTwoOnPage_SelectsTwoHands()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.SelectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(2));
}
[Test]
public void UnselectAllShownHandHistories_TwoSelectedHandsShownAndTwoOnPage_UnselectsTwoHands()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.SelectAllShownHandHistoriesCommand.Execute(null);
_viewModel
.UnselectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(0));
}
[Test]
public void SelectAllHandHistoriesOnPage_TwoHandsShownButOnlyOneHandOnPage_SelectsOneHand()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.HandHistoriesOnPage.RemoveAt(0);
_viewModel
.SelectAllHandHistoriesOnPageCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(1));
}
[Test]
public void UnselectAllHandHistoriesOnPage_TwoSelectedHandsShownButOnlyOneHandOnPage_UnselectsOneHand()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.SelectAllHandHistoriesOnPageCommand.Execute(null);
_viewModel
.HandHistoriesOnPage.RemoveAt(0);
_viewModel
.UnselectAllHandHistoriesOnPageCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(1));
}
[Test]
public void SelectAllShownHandHistories_TwoHandsShownButOnlyOneHandOnPage_SelectsTwoHands()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.HandHistoriesOnPage.RemoveAt(0);
_viewModel
.SelectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(2));
}
[Test]
public void UnselectAllShownHandHistories_TwoSelectedHandsShownButOnlyOneHandOnPage_UnselectsTwoHands()
{
var hand1 = new ConvertedPokerHand();
var hand2 = new ConvertedPokerHand();
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
_viewModel
.InitializeWith(hands)
.SelectAllShownHandHistoriesCommand.Execute(null);
_viewModel
.HandHistoriesOnPage.RemoveAt(0);
_viewModel
.UnselectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(0));
}
[Test]
public void SelectAllShownHandHistories_TwoHandsTotalButOnlyOneHandShown_SelectsOneHand()
{
var hand1 = new ConvertedPokerHand { Id = 1 };
var hand2 = new ConvertedPokerHand { Id = 2 };
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
var filterCondition = new StubConditionWithHandId { HandIdToMatch = hand1.Id };
_viewModel
.InitializeWith(hands)
.ApplyFilter(filterCondition)
.SelectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(1));
}
[Test]
public void UnselectAllShownHandHistories_TwoSelectedHandsTotalButOnlyOneHandShown_UnselectsOneHand()
{
var hand1 = new ConvertedPokerHand { Id = 1 };
var hand2 = new ConvertedPokerHand { Id = 2 };
var hands = new List<IConvertedPokerHand> { hand1, hand2 };
var filterCondition = new StubConditionWithHandId { HandIdToMatch = hand1.Id };
_viewModel
.InitializeWith(hands)
.SelectAllShownHandHistoriesCommand.Execute(null);
_viewModel
.ApplyFilter(filterCondition)
.UnselectAllShownHandHistoriesCommand.Execute(null);
Assert.That(_viewModel.SelectedHandHistories.Count(), Is.EqualTo(1));
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
#if USE_REFEMIT
public class XmlWriterDelegator
#else
internal class XmlWriterDelegator
#endif
{
protected XmlWriter writer;
protected XmlDictionaryWriter dictionaryWriter;
internal int depth;
int prefixes;
public XmlWriterDelegator(XmlWriter writer)
{
XmlObjectSerializer.CheckNull(writer, "writer");
this.writer = writer;
this.dictionaryWriter = writer as XmlDictionaryWriter;
}
internal XmlWriter Writer
{
get { return writer; }
}
internal void Flush()
{
writer.Flush();
}
internal string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
public void WriteEndElement()
{
writer.WriteEndElement();
depth--;
}
internal void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
internal void WriteRaw(string data)
{
writer.WriteRaw(data);
}
internal void WriteXmlnsAttribute(XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
if (ns != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
}
else
WriteXmlnsAttribute(ns.Value);
}
internal void WriteXmlnsAttribute(string ns)
{
if (ns != null)
{
if (ns.Length == 0)
writer.WriteAttributeString("xmlns", String.Empty, null, ns);
else
{
if (dictionaryWriter != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
else
{
string prefix = writer.LookupPrefix(ns);
if (prefix == null)
{
prefix = String.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, prefixes);
prefixes++;
writer.WriteAttributeString("xmlns", prefix, null, ns);
}
}
}
}
}
internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
dictionaryWriter.WriteXmlnsAttribute(prefix, ns);
}
else
{
writer.WriteAttributeString("xmlns", prefix, null, ns.Value);
}
}
void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri);
else
writer.WriteStartAttribute(prefix,
(localName == null ? null : localName.Value),
(namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteAttributeString(string prefix, string localName, string ns, string value)
{
WriteStartAttribute(prefix, localName, ns);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
void WriteAttributeStringValue(string value)
{
writer.WriteValue(value);
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
void WriteAttributeStringValue(XmlDictionaryString value)
{
if (dictionaryWriter == null)
writer.WriteString(value.Value);
else
dictionaryWriter.WriteString(value);
}
internal void WriteAttributeInt(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, int value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeIntValue(value);
WriteEndAttribute();
}
void WriteAttributeIntValue(int value)
{
writer.WriteValue(value);
}
internal void WriteAttributeBool(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, bool value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeBoolValue(value);
WriteEndAttribute();
}
void WriteAttributeBoolValue(bool value)
{
writer.WriteValue(value);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
void WriteAttributeQualifiedNameValue(string name, string ns)
{
writer.WriteQualifiedName(name, ns);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(name.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(name, ns);
}
internal void WriteStartElement(string localName, string ns)
{
WriteStartElement(null, localName, ns);
}
internal virtual void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
depth++;
prefixes = 1;
}
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartElement(null, localName, namespaceUri);
}
internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri);
else
writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
depth++;
prefixes = 1;
}
internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(null, localName, namespaceUri);
else
writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteEndElementPrimitive()
{
writer.WriteEndElement();
}
internal WriteState WriteState
{
get { return writer.WriteState; }
}
internal string XmlLang
{
get { return writer.XmlLang; }
}
internal XmlSpace XmlSpace
{
get { return writer.XmlSpace; }
}
public void WriteNamespaceDecl(XmlDictionaryString ns)
{
WriteXmlnsAttribute(ns);
}
Exception CreateInvalidPrimitiveTypeException(Type type)
{
return new InvalidDataContractException(SR.GetString(SR.InvalidPrimitiveType, DataContract.GetClrTypeFullName(type)));
}
internal void WriteAnyType(object value)
{
WriteAnyType(value, value.GetType());
}
internal void WriteAnyType(object value, Type valueType)
{
bool handled = true;
switch (Type.GetTypeCode(valueType))
{
case TypeCode.Boolean:
WriteBoolean((bool)value);
break;
case TypeCode.Char:
WriteChar((char)value);
break;
case TypeCode.Byte:
WriteUnsignedByte((byte)value);
break;
case TypeCode.Int16:
WriteShort((short)value);
break;
case TypeCode.Int32:
WriteInt((int)value);
break;
case TypeCode.Int64:
WriteLong((long)value);
break;
case TypeCode.Single:
WriteFloat((float)value);
break;
case TypeCode.Double:
WriteDouble((double)value);
break;
case TypeCode.Decimal:
WriteDecimal((decimal)value);
break;
case TypeCode.DateTime:
WriteDateTime((DateTime)value);
break;
case TypeCode.String:
WriteString((string)value);
break;
case TypeCode.SByte:
WriteSignedByte((sbyte)value);
break;
case TypeCode.UInt16:
WriteUnsignedShort((ushort)value);
break;
case TypeCode.UInt32:
WriteUnsignedInt((uint)value);
break;
case TypeCode.UInt64:
WriteUnsignedLong((ulong)value);
break;
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64((byte[])value);
else if (valueType == Globals.TypeOfObject)
{
//Write Nothing
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan((TimeSpan)value);
else if (valueType == Globals.TypeOfGuid)
WriteGuid((Guid)value);
else if (valueType == Globals.TypeOfUri)
WriteUri((Uri)value);
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName((XmlQualifiedName)value);
else
handled = false;
break;
}
if (!handled)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
internal void WriteExtensionData(IDataNode dataNode)
{
bool handled = true;
Type valueType = dataNode.DataType;
switch (Type.GetTypeCode(valueType))
{
case TypeCode.Boolean:
WriteBoolean(((DataNode<bool>)dataNode).GetValue());
break;
case TypeCode.Char:
WriteChar(((DataNode<char>)dataNode).GetValue());
break;
case TypeCode.Byte:
WriteUnsignedByte(((DataNode<byte>)dataNode).GetValue());
break;
case TypeCode.Int16:
WriteShort(((DataNode<short>)dataNode).GetValue());
break;
case TypeCode.Int32:
WriteInt(((DataNode<int>)dataNode).GetValue());
break;
case TypeCode.Int64:
WriteLong(((DataNode<long>)dataNode).GetValue());
break;
case TypeCode.Single:
WriteFloat(((DataNode<float>)dataNode).GetValue());
break;
case TypeCode.Double:
WriteDouble(((DataNode<double>)dataNode).GetValue());
break;
case TypeCode.Decimal:
WriteDecimal(((DataNode<decimal>)dataNode).GetValue());
break;
case TypeCode.DateTime:
WriteDateTime(((DataNode<DateTime>)dataNode).GetValue());
break;
case TypeCode.String:
WriteString(((DataNode<string>)dataNode).GetValue());
break;
case TypeCode.SByte:
WriteSignedByte(((DataNode<sbyte>)dataNode).GetValue());
break;
case TypeCode.UInt16:
WriteUnsignedShort(((DataNode<ushort>)dataNode).GetValue());
break;
case TypeCode.UInt32:
WriteUnsignedInt(((DataNode<uint>)dataNode).GetValue());
break;
case TypeCode.UInt64:
WriteUnsignedLong(((DataNode<ulong>)dataNode).GetValue());
break;
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64(((DataNode<byte[]>)dataNode).GetValue());
else if (valueType == Globals.TypeOfObject)
{
object obj = dataNode.Value;
if (obj != null)
WriteAnyType(obj);
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan(((DataNode<TimeSpan>)dataNode).GetValue());
else if (valueType == Globals.TypeOfGuid)
WriteGuid(((DataNode<Guid>)dataNode).GetValue());
else if (valueType == Globals.TypeOfUri)
WriteUri(((DataNode<Uri>)dataNode).GetValue());
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName(((DataNode<XmlQualifiedName>)dataNode).GetValue());
else
handled = false;
break;
}
if (!handled)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
internal void WriteString(string value)
{
writer.WriteValue(value);
}
internal virtual void WriteBoolean(bool value)
{
writer.WriteValue(value);
}
public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteBoolean(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDateTime(DateTime value)
{
writer.WriteValue(value);
}
public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteDateTime(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDecimal(decimal value)
{
writer.WriteValue(value);
}
public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteDecimal(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDouble(double value)
{
writer.WriteValue(value);
}
public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteDouble(value);
WriteEndElementPrimitive();
}
internal virtual void WriteInt(int value)
{
writer.WriteValue(value);
}
public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteLong(long value)
{
writer.WriteValue(value);
}
public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteFloat(float value)
{
writer.WriteValue(value);
}
public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteFloat(value);
WriteEndElementPrimitive();
}
private const int CharChunkSize = 76;
private const int ByteChunkSize = CharChunkSize / 4 * 3;
internal virtual void WriteBase64(byte[] bytes)
{
if (bytes == null)
return;
writer.WriteBase64(bytes, 0, bytes.Length);
}
internal virtual void WriteShort(short value)
{
writer.WriteValue(value);
}
public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedByte(byte value)
{
writer.WriteValue(value);
}
public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteSignedByte(sbyte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
#endif
public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteSignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedInt(uint value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
#endif
public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedLong(ulong value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
[CLSCompliant(false)]
#endif
public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedShort(ushort value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
#endif
public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteChar(char value)
{
writer.WriteValue((int)value);
}
public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteChar(value);
WriteEndElementPrimitive();
}
internal void WriteTimeSpan(TimeSpan value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteTimeSpan(value);
WriteEndElementPrimitive();
}
internal void WriteGuid(Guid value)
{
writer.WriteRaw(value.ToString());
}
public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteGuid(value);
WriteEndElementPrimitive();
}
internal void WriteUri(Uri value)
{
writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
}
internal virtual void WriteQName(XmlQualifiedName value)
{
if (value != XmlQualifiedName.Empty)
{
WriteXmlnsAttribute(value.Namespace);
WriteQualifiedName(value.Name, value.Namespace);
}
}
internal void WriteQualifiedName(string localName, string ns)
{
writer.WriteQualifiedName(localName, ns);
}
internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(localName.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(localName, ns);
}
public void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteBoolean(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDateTime(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDecimal(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteInt(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteLong(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteFloat(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
public void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDouble(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
}
}
| |
// 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.CodeAnalysis;
namespace System.Globalization
{
/// <summary>
/// Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
/// That is,
/// Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01
/// </summary>
/// <remarks>
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 1912/01/01 9999/12/31
/// Taiwan 01/01/01 8088/12/31
/// </remarks>
public class TaiwanCalendar : Calendar
{
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
private static EraInfo[] s_taiwanEraInfo = new EraInfo[]
{
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
private static volatile Calendar s_defaultInstance;
private readonly GregorianCalendarHelper _helper;
internal static Calendar GetDefaultInstance()
{
return s_defaultInstance ?? (s_defaultInstance = new TaiwanCalendar());
}
private static readonly DateTime s_calendarMinValue = new DateTime(1912, 1, 1);
public override DateTime MinSupportedDateTime => s_calendarMinValue;
public override DateTime MaxSupportedDateTime => DateTime.MaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar;
public TaiwanCalendar()
{
try
{
new CultureInfo("zh-TW");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(GetType().ToString(), e);
}
_helper = new GregorianCalendarHelper(this, s_taiwanEraInfo);
}
internal override CalendarId ID => CalendarId.TAIWAN;
public override DateTime AddMonths(DateTime time, int months)
{
return _helper.AddMonths(time, months);
}
public override DateTime AddYears(DateTime time, int years)
{
return _helper.AddYears(time, years);
}
public override int GetDaysInMonth(int year, int month, int era)
{
return _helper.GetDaysInMonth(year, month, era);
}
public override int GetDaysInYear(int year, int era)
{
return _helper.GetDaysInYear(year, era);
}
public override int GetDayOfMonth(DateTime time)
{
return _helper.GetDayOfMonth(time);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return _helper.GetDayOfWeek(time);
}
public override int GetDayOfYear(DateTime time)
{
return _helper.GetDayOfYear(time);
}
public override int GetMonthsInYear(int year, int era)
{
return _helper.GetMonthsInYear(year, era);
}
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return _helper.GetWeekOfYear(time, rule, firstDayOfWeek);
}
public override int GetEra(DateTime time)
{
return _helper.GetEra(time);
}
public override int GetMonth(DateTime time)
{
return _helper.GetMonth(time);
}
public override int GetYear(DateTime time)
{
return _helper.GetYear(time);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return _helper.IsLeapDay(year, month, day, era);
}
public override bool IsLeapYear(int year, int era)
{
return _helper.IsLeapYear(year, era);
}
public override int GetLeapMonth(int year, int era)
{
return _helper.GetLeapMonth(year, era);
}
public override bool IsLeapMonth(int year, int month, int era)
{
return _helper.IsLeapMonth(year, month, era);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era);
}
public override int[] Eras => _helper.Eras;
private const int DefaultTwoDigitYearMax = 99;
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
VerifyWritable();
if (value < 99 || value > _helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear));
}
_twoDigitYearMax = value;
}
}
/// <summary>
/// For Taiwan calendar, four digit year is not used.
/// Therefore, for any two digit number, we just return the original number.
/// </summary>
public override int ToFourDigitYear(int year)
{
if (year <= 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedPosNum);
}
if (year > _helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear));
}
return year;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Wildcard.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Wildcard
*
* wildcard wrappers for Regex
*
* (1) Wildcard does straight string wildcarding with no path separator awareness
* (2) WildcardUrl recognizes that forward / slashes are special and can't match * or ?
* (3) WildcardDos recognizes that backward \ and : are special and can't match * or ?
*
* Copyright (c) 1999, Microsoft Corporation
*/
namespace System.Web.Util {
using System.Runtime.Serialization.Formatters;
using System.Text.RegularExpressions;
/*
* Wildcard
*
* Wildcard patterns have three metacharacters:
*
* A ? is equivalent to .
* A * is equivalent to .*
* A , is equivalent to |
*
* Note that by each alternative is surrounded by \A...\z to anchor
* at the edges of the string.
*/
internal class Wildcard {
#if NOT_USED
internal /*public*/ Wildcard(String pattern) : this (pattern, false) {
}
#endif
internal /*public*/ Wildcard(String pattern, bool caseInsensitive) {
_pattern = pattern;
_caseInsensitive = caseInsensitive;
}
internal String _pattern;
internal bool _caseInsensitive;
internal Regex _regex;
protected static Regex metaRegex = new Regex("[\\+\\{\\\\\\[\\|\\(\\)\\.\\^\\$]");
protected static Regex questRegex = new Regex("\\?");
protected static Regex starRegex = new Regex("\\*");
protected static Regex commaRegex = new Regex(",");
protected static Regex slashRegex = new Regex("(?=/)");
protected static Regex backslashRegex = new Regex("(?=[\\\\:])");
/*
* IsMatch returns true if the input is an exact match for the
* wildcard pattern.
*/
internal /*public*/ bool IsMatch(String input) {
EnsureRegex();
bool result = _regex.IsMatch(input);
return result;
}
#if DONT_COMPILE
internal /*public*/ String Pattern {
get {
return _pattern;
}
}
#endif
/*
* Builds the matching regex when needed
*/
protected void EnsureRegex() {
// threadsafe without protection because of gc
if (_regex != null)
return;
_regex = RegexFromWildcard(_pattern, _caseInsensitive);
}
/*
* Basic wildcard -> Regex conversion, no slashes
*/
protected virtual Regex RegexFromWildcard(String pattern, bool caseInsensitive) {
RegexOptions options = RegexOptions.None;
// match right-to-left (for speed) if the pattern starts with a *
if (pattern.Length > 0 && pattern[0] == '*')
options = RegexOptions.RightToLeft | RegexOptions.Singleline;
else
options = RegexOptions.Singleline;
// case insensitivity
if (caseInsensitive)
options |= RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
// Remove regex metacharacters
pattern = metaRegex.Replace(pattern, "\\$0");
// Replace wildcard metacharacters with regex codes
pattern = questRegex.Replace(pattern, ".");
pattern = starRegex.Replace(pattern, ".*");
pattern = commaRegex.Replace(pattern, "\\z|\\A");
// anchor the pattern at beginning and end, and return the regex
return new Regex("\\A" + pattern + "\\z", options);
}
}
abstract internal class WildcardPath : Wildcard {
#if NOT_USED
internal /*public*/ WildcardPath(String pattern) : base(pattern) {
}
private Regex[][] _dirs;
#endif
internal /*public*/ WildcardPath(String pattern, bool caseInsensitive) : base(pattern, caseInsensitive) {
}
private Regex _suffix;
/*
* IsSuffix returns true if a suffix of the input is an exact
* match for the wildcard pattern.
*/
internal /*public*/ bool IsSuffix(String input) {
EnsureSuffix();
return _suffix.IsMatch(input);
}
#if NOT_USED
/*
* AllowPrefix returns true if the input is an exact match for
* a prefix-directory of the wildcard pattern (i.e., if it
* is possible to match the wildcard pattern by adding
* more subdirectories or a filename at the end of the path).
*/
internal /*public*/ bool AllowPrefix(String prefix) {
String[] dirs = SplitDirs(prefix);
EnsureDirs();
for (int i = 0; i < _dirs.Length; i++) {
// pattern is shorter than prefix: reject
if (_dirs[i].Length < dirs.Length)
goto NextAlt;
for (int j = 0; j < dirs.Length; j++) {
// the jth directory doesn't match; path is not a prefix
if (!_dirs[i][j].IsMatch(dirs[j]))
goto NextAlt;
}
// one alternative passed: we pass.
return true;
NextAlt:
;
}
return false;
}
/*
* Builds the matching regex array when needed
*/
protected void EnsureDirs() {
// threadsafe without protection because of gc
if (_dirs != null)
return;
_dirs = DirsFromWildcard(_pattern);
}
#endif
/*
* Builds the matching regex when needed
*/
protected void EnsureSuffix() {
// threadsafe without protection because of gc
if (_suffix != null)
return;
_suffix = SuffixFromWildcard(_pattern, _caseInsensitive);
}
/*
* Specialize for forward-slash and backward-slash cases
*/
protected abstract Regex SuffixFromWildcard(String pattern, bool caseInsensitive);
protected abstract Regex[][] DirsFromWildcard(String pattern);
protected abstract String[] SplitDirs(String input);
}
/*
* WildcardUrl
*
* The twist is that * and ? cannot match forward slashes,
* and we can do an exact suffix match that starts after
* any /, and we can also do a prefix prune.
*/
internal class WildcardUrl : WildcardPath {
#if NOT_USED
internal /*public*/ WildcardUrl(String pattern) : base(pattern) {
}
#endif
internal /*public*/ WildcardUrl(String pattern, bool caseInsensitive) : base(pattern, caseInsensitive) {
}
protected override String[] SplitDirs(String input) {
return slashRegex.Split(input);
}
protected override Regex RegexFromWildcard(String pattern, bool caseInsensitive) {
RegexOptions options;
// match right-to-left (for speed) if the pattern starts with a *
if (pattern.Length > 0 && pattern[0] == '*')
options = RegexOptions.RightToLeft;
else
options = RegexOptions.None;
// case insensitivity
if (caseInsensitive)
options |= RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
// Remove regex metacharacters
pattern = metaRegex.Replace(pattern, "\\$0");
// Replace wildcard metacharacters with regex codes
pattern = questRegex.Replace(pattern, "[^/]");
pattern = starRegex.Replace(pattern, "[^/]*");
pattern = commaRegex.Replace(pattern, "\\z|\\A");
// anchor the pattern at beginning and end, and return the regex
return new Regex("\\A" + pattern + "\\z", options);
}
protected override Regex SuffixFromWildcard(String pattern, bool caseInsensitive) {
RegexOptions options;
// match right-to-left (for speed)
options = RegexOptions.RightToLeft;
// case insensitivity
if (caseInsensitive)
options |= RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
// Remove regex metacharacters
pattern = metaRegex.Replace(pattern, "\\$0");
// Replace wildcard metacharacters with regex codes
pattern = questRegex.Replace(pattern, "[^/]");
pattern = starRegex.Replace(pattern, "[^/]*");
pattern = commaRegex.Replace(pattern, "\\z|(?:\\A|(?<=/))");
// anchor the pattern at beginning and end, and return the regex
return new Regex("(?:\\A|(?<=/))" + pattern + "\\z", options);
}
protected override Regex[][] DirsFromWildcard(String pattern) {
String[] alts = commaRegex.Split(pattern);
Regex[][] dirs = new Regex[alts.Length][];
for (int i = 0; i < alts.Length; i++) {
String[] dirpats = slashRegex.Split(alts[i]);
Regex[] dirregex = new Regex[dirpats.Length];
if (alts.Length == 1 && dirpats.Length == 1) {
// common case: no commas, no slashes: dir regex is same as top regex.
EnsureRegex();
dirregex[0] = _regex;
}
else {
for (int j = 0; j < dirpats.Length; j++) {
dirregex[j] = RegexFromWildcard(dirpats[j], _caseInsensitive);
}
}
dirs[i] = dirregex;
}
return dirs;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Rest.Generator.Logging;
using Microsoft.Rest.Generator.Properties;
using Microsoft.Rest.Generator.Utilities;
using Newtonsoft.Json;
namespace Microsoft.Rest.Generator.Extensibility
{
public static class ExtensionsLoader
{
/// <summary>
/// The name of the AutoRest configuration file.
/// </summary>
private const string ConfigurationFileName = "AutoRest.json";
/// <summary>
/// Gets the code generator specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Code generator specified in Settings.CodeGenerator</returns>
public static CodeGenerator GetCodeGenerator(Settings settings)
{
Logger.LogInfo(Resources.InitializingCodeGenerator);
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (string.IsNullOrEmpty(settings.CodeGenerator))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "CodeGenerator"));
}
CodeGenerator codeGenerator = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
codeGenerator = LoadTypeFromAssembly<CodeGenerator>(config.CodeGenerators, settings.CodeGenerator,
settings);
Settings.PopulateSettings(codeGenerator, settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.GeneratorInitialized,
settings.CodeGenerator,
codeGenerator.GetType().Assembly.GetName().Version);
return codeGenerator;
}
/// <summary>
/// Gets the modeler specified in the provided Settings.
/// </summary>
/// <param name="settings">The code generation settings</param>
/// <returns>Modeler specified in Settings.Modeler</returns>
public static Modeler GetModeler(Settings settings)
{
Logger.LogInfo(Resources.ModelerInitialized);
if (settings == null)
{
throw new ArgumentNullException("settings", "settings or settings.Modeler cannot be null.");
}
if (string.IsNullOrEmpty(settings.Modeler))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
Resources.ParameterValueIsMissing, "Modeler"));
}
Modeler modeler = null;
string configurationFile = GetConfigurationFileContent(settings);
if (configurationFile != null)
{
try
{
var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile);
modeler = LoadTypeFromAssembly<Modeler>(config.Modelers, settings.Modeler, settings);
Settings.PopulateSettings(modeler, settings.CustomSettings);
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
}
}
else
{
throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
}
Logger.LogInfo(Resources.ModelerInitialized,
settings.Modeler,
modeler.GetType().Assembly.GetName().Version);
return modeler;
}
private static string GetConfigurationFileContent(Settings settings)
{
string path = ConfigurationFileName;
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Directory.GetCurrentDirectory(), ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof (Settings)).Location),
ConfigurationFileName);
}
if (!settings.FileSystem.FileExists(path))
{
return null;
}
return settings.FileSystem.ReadFileAsText(path);
}
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
private static T LoadTypeFromAssembly<T>(IDictionary<string, AutoRestProviderConfiguration> section,
string key, Settings settings)
{
T instance = default(T);
if (!section.IsNullOrEmpty() && section.ContainsKey(key))
{
string fullTypeName = section[key].TypeName;
if (string.IsNullOrEmpty(fullTypeName))
{
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
int indexOfComma = fullTypeName.IndexOf(',');
if (indexOfComma < 0)
{
throw ErrorManager.CreateError(Resources.TypeShouldBeAssemblyQualified, fullTypeName);
}
string typeName = fullTypeName.Substring(0, indexOfComma).Trim();
string assemblyName = fullTypeName.Substring(indexOfComma + 1).Trim();
try
{
Assembly loadedAssembly;
try
{
loadedAssembly = Assembly.Load(assemblyName);
}
catch(FileNotFoundException)
{
loadedAssembly = Assembly.LoadFrom(assemblyName + ".dll");
if(loadedAssembly == null)
{
throw;
}
}
Type loadedType = loadedAssembly.GetTypes()
.Single(t => string.IsNullOrEmpty(typeName) ||
t.Name == typeName ||
t.FullName == typeName);
instance = (T) loadedType.GetConstructor(
new[] {typeof (Settings)}).Invoke(new object[] {settings});
if (!section[key].Settings.IsNullOrEmpty())
{
foreach (var settingFromFile in section[key].Settings)
{
settings.CustomSettings[settingFromFile.Key] = settingFromFile.Value;
}
}
}
catch (Exception ex)
{
throw ErrorManager.CreateError(ex, Resources.ErrorLoadingAssembly, key, ex.Message);
}
return instance;
}
throw ErrorManager.CreateError(Resources.ExtensionNotFound, key);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HPSF.Extractor
{
using System;
using System.Text;
using System.IO;
using System.Collections;
using NPOI;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
using System.Globalization;
/// <summary>
/// Extracts all of the HPSF properties, both
/// build in and custom, returning them in
/// textual form.
/// </summary>
public class HPSFPropertiesExtractor : POITextExtractor
{
public HPSFPropertiesExtractor(POITextExtractor mainExtractor)
: base(mainExtractor)
{
}
public HPSFPropertiesExtractor(POIDocument doc)
: base(doc)
{
}
public HPSFPropertiesExtractor(POIFSFileSystem fs)
: base(new PropertiesOnlyDocument(fs))
{
}
public HPSFPropertiesExtractor(NPOIFSFileSystem fs)
: base(new PropertiesOnlyDocument(fs))
{
}
/// <summary>
/// Gets the document summary information text.
/// </summary>
/// <value>The document summary information text.</value>
public String DocumentSummaryInformationText
{
get
{
DocumentSummaryInformation dsi = document.DocumentSummaryInformation;
StringBuilder text = new StringBuilder();
// Normal properties
text.Append(GetPropertiesText(dsi));
// Now custom ones
CustomProperties cps = dsi == null ? null : dsi.CustomProperties;
if (cps != null)
{
IEnumerator keys = cps.NameSet().GetEnumerator();
while (keys.MoveNext())
{
String key = keys.Current.ToString();
String val = GetPropertyValueText(cps[key]);
text.Append(key + " = " + val + "\n");
}
}
// All done
return text.ToString();
}
}
/// <summary>
/// Gets the summary information text.
/// </summary>
/// <value>The summary information text.</value>
public String SummaryInformationText
{
get
{
SummaryInformation si = document.SummaryInformation;
// Just normal properties
return GetPropertiesText(si);
}
}
/// <summary>
/// Gets the properties text.
/// </summary>
/// <param name="ps">The ps.</param>
/// <returns></returns>
private static String GetPropertiesText(SpecialPropertySet ps)
{
if (ps == null)
{
// Not defined, oh well
return "";
}
StringBuilder text = new StringBuilder();
Wellknown.PropertyIDMap idMap = ps.PropertySetIDMap;
Property[] props = ps.Properties;
for (int i = 0; i < props.Length; i++)
{
String type = props[i].ID.ToString(CultureInfo.InvariantCulture);
Object typeObj = idMap.Get(props[i].ID);
if (typeObj != null)
{
type = typeObj.ToString();
}
String val = GetPropertyValueText(props[i].Value);
text.Append(type + " = " + val + "\n");
}
return text.ToString();
}
/// <summary>
/// Gets the property value text.
/// </summary>
/// <param name="val">The val.</param>
/// <returns></returns>
private static String GetPropertyValueText(Object val)
{
if (val == null)
{
return "(not set)";
}
if (val is byte[])
{
byte[] b = (byte[])val;
if (b.Length == 0)
{
return "";
}
if (b.Length == 1)
{
return b[0].ToString(CultureInfo.InvariantCulture);
}
if (b.Length == 2)
{
return LittleEndian.GetUShort(b).ToString(CultureInfo.InvariantCulture);
}
if (b.Length == 4)
{
return LittleEndian.GetUInt(b).ToString(CultureInfo.InvariantCulture);
}
// Maybe it's a string? who knows!
return b.ToString();
}
return val.ToString();
}
/// <summary>
/// Return the text of all the properties defined in
/// the document.
/// </summary>
/// <value>All the text from the document.</value>
public override String Text
{
get
{
return SummaryInformationText + DocumentSummaryInformationText;
}
}
/// <summary>
/// Returns another text extractor, which is able to
/// output the textual content of the document
/// metadata / properties, such as author and title.
/// </summary>
/// <value>The metadata text extractor.</value>
public override POITextExtractor MetadataTextExtractor
{
get
{
throw new InvalidOperationException("You already have the Metadata Text Extractor, not recursing!");
}
}
/// <summary>
/// So we can get at the properties of any
/// random OLE2 document.
/// </summary>
private class PropertiesOnlyDocument : POIDocument
{
public PropertiesOnlyDocument(NPOIFSFileSystem fs)
: base(fs.Root)
{
}
public PropertiesOnlyDocument(POIFSFileSystem fs)
: base(fs)
{
}
public override void Write(Stream out1)
{
throw new InvalidOperationException("Unable to write, only for properties!");
}
}
}
}
| |
// ****************************************************************
// Copyright 2002-2003, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
namespace NUnit.Util
{
using System;
using System.Drawing;
using System.Globalization;
using System.ComponentModel;
/// <summary>
/// SettingsGroup is the base class representing a group
/// of user or system settings. All storge of settings
/// is delegated to a SettingsStorage.
/// </summary>
public class SettingsGroup : ISettings, IDisposable
{
#region Instance Fields
protected ISettingsStorage storage;
#endregion
#region Constructors
/// <summary>
/// Construct a settings group.
/// </summary>
/// <param name="storage">Storage for the group settings</param>
public SettingsGroup( ISettingsStorage storage )
{
this.storage = storage;
}
/// <summary>
/// Protected constructor for use by derived classes that
/// set the storage themselves or don't use a storage.
/// </summary>
protected SettingsGroup()
{
}
#endregion
#region Properties
public event SettingsEventHandler Changed;
/// <summary>
/// The storage used for the group settings
/// </summary>
public ISettingsStorage Storage
{
get { return storage; }
}
#endregion
#region ISettings Members
/// <summary>
/// Load the value of one of the group's settings
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <returns>Value of the setting or null</returns>
public object GetSetting( string settingName )
{
return storage.GetSetting( settingName );
}
/// <summary>
/// Load the value of one of the group's settings or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value to return if the seeting is not present</param>
/// <returns>Value of the setting or the default</returns>
public object GetSetting( string settingName, object defaultValue )
{
object result = GetSetting(settingName );
if ( result == null )
result = defaultValue;
return result;
}
/// <summary>
/// Load the value of one of the group's integer settings
/// in a type-safe manner or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value to return if the seeting is not present</param>
/// <returns>Value of the setting or the default</returns>
public int GetSetting(string settingName, int defaultValue)
{
object result = GetSetting(settingName);
if (result == null)
return defaultValue;
if (result is int)
return (int)result;
try
{
return Int32.Parse(result.ToString());
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Load the value of one of the group's float settings
/// in a type-safe manner or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value to return if the setting is not present</param>
/// <returns>Value of the setting or the default</returns>
public float GetSetting(string settingName, float defaultValue)
{
object result = GetSetting(settingName);
if (result == null)
return defaultValue;
if (result is float)
return (float)result;
try
{
return float.Parse(result.ToString());
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Load the value of one of the group's boolean settings
/// in a type-safe manner.
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value of the setting or the default</param>
/// <returns>Value of the setting</returns>
public bool GetSetting( string settingName, bool defaultValue )
{
object result = GetSetting(settingName );
if ( result == null )
return defaultValue;
// Handle legacy formats
// if ( result is int )
// return (int)result == 1;
//
// if ( result is string )
// {
// if ( (string)result == "1" ) return true;
// if ( (string)result == "0" ) return false;
// }
if ( result is bool )
return (bool) result ;
try
{
return Boolean.Parse( result.ToString() );
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Load the value of one of the group's string settings
/// in a type-safe manner or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value to return if the setting is not present</param>
/// <returns>Value of the setting or the default</returns>
public string GetSetting( string settingName, string defaultValue )
{
object result = GetSetting(settingName );
if ( result == null )
return defaultValue;
if ( result is string )
return (string) result;
else
return result.ToString();
}
/// <summary>
/// Load the value of one of the group's enum settings
/// in a type-safe manner or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultValue">Value to return if the setting is not present</param>
/// <returns>Value of the setting or the default</returns>
public System.Enum GetSetting(string settingName, System.Enum defaultValue)
{
object result = GetSetting(settingName);
if (result == null)
return defaultValue;
if (result is System.Enum)
return (System.Enum)result;
try
{
return (System.Enum)System.Enum.Parse(defaultValue.GetType(), result.ToString(), true);
}
catch
{
return defaultValue;
}
}
/// <summary>
/// Load the value of one of the group's Font settings
/// in a type-safe manner or return a default value
/// </summary>
/// <param name="settingName">Name of setting to load</param>
/// <param name="defaultFont">Value to return if the setting is not present</param>
/// <returns>Value of the setting or the default</returns>
public Font GetSetting(string settingName, Font defaultFont)
{
object result = GetSetting(settingName);
if (result == null)
return defaultFont;
if (result is Font)
return (Font)result;
try
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
return (Font)converter.ConvertFrom(null, CultureInfo.InvariantCulture, result.ToString());
}
catch
{
return defaultFont;
}
}
/// <summary>
/// Remove a setting from the group
/// </summary>
/// <param name="settingName">Name of the setting to remove</param>
public void RemoveSetting( string settingName )
{
storage.RemoveSetting( settingName );
if ( Changed != null )
Changed( this, new SettingsEventArgs( settingName ) );
}
/// <summary>
/// Remove a group of settings
/// </summary>
/// <param name="GroupName"></param>
public void RemoveGroup( string groupName )
{
storage.RemoveGroup( groupName );
}
/// <summary>
/// Save the value of one of the group's settings
/// </summary>
/// <param name="settingName">Name of the setting to save</param>
/// <param name="settingValue">Value to be saved</param>
public void SaveSetting( string settingName, object settingValue )
{
object oldValue = storage.GetSetting( settingName );
// Avoid signaling "changes" when there is not really a change
if ( oldValue != null )
{
if( oldValue is string && settingValue is string && (string)oldValue == (string)settingValue ||
oldValue is int && settingValue is int && (int)oldValue == (int)settingValue ||
oldValue is bool && settingValue is bool && (bool)oldValue == (bool)settingValue ||
oldValue is Enum && settingValue is Enum && oldValue.Equals(settingValue) )
return;
}
storage.SaveSetting( settingName, settingValue );
if ( Changed != null )
Changed( this, new SettingsEventArgs( settingName ) );
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose of this group by disposing of it's storage implementation
/// </summary>
public void Dispose()
{
if ( storage != null )
{
storage.Dispose();
storage = null;
}
}
#endregion
}
}
| |
// 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.
// File System.Web.UI.WebControls.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public delegate void AdCreatedEventHandler(Object sender, AdCreatedEventArgs e);
public delegate void AuthenticateEventHandler(Object sender, AuthenticateEventArgs e);
public enum AutoCompleteType
{
None = 0,
Disabled = 1,
Cellular = 2,
Company = 3,
Department = 4,
DisplayName = 5,
Email = 6,
FirstName = 7,
Gender = 8,
HomeCity = 9,
HomeCountryRegion = 10,
HomeFax = 11,
HomePhone = 12,
HomeState = 13,
HomeStreetAddress = 14,
HomeZipCode = 15,
Homepage = 16,
JobTitle = 17,
LastName = 18,
MiddleName = 19,
Notes = 20,
Office = 21,
Pager = 22,
BusinessCity = 23,
BusinessCountryRegion = 24,
BusinessFax = 25,
BusinessPhone = 26,
BusinessState = 27,
BusinessStreetAddress = 28,
BusinessUrl = 29,
BusinessZipCode = 30,
Search = 31,
}
public enum BorderStyle
{
NotSet = 0,
None = 1,
Dotted = 2,
Dashed = 3,
Solid = 4,
Double = 5,
Groove = 6,
Ridge = 7,
Inset = 8,
Outset = 9,
}
public enum BulletedListDisplayMode
{
Text = 0,
HyperLink = 1,
LinkButton = 2,
}
public delegate void BulletedListEventHandler(Object sender, BulletedListEventArgs e);
public enum BulletStyle
{
NotSet = 0,
Numbered = 1,
LowerAlpha = 2,
UpperAlpha = 3,
LowerRoman = 4,
UpperRoman = 5,
Disc = 6,
Circle = 7,
Square = 8,
CustomImage = 9,
}
public enum ButtonColumnType
{
LinkButton = 0,
PushButton = 1,
}
public enum ButtonType
{
Button = 0,
Image = 1,
Link = 2,
}
public enum CalendarSelectionMode
{
None = 0,
Day = 1,
DayWeek = 2,
DayWeekMonth = 3,
}
public delegate void CommandEventHandler(Object sender, CommandEventArgs e);
public enum ContentDirection
{
NotSet = 0,
LeftToRight = 1,
RightToLeft = 2,
}
public delegate void CreateUserErrorEventHandler(Object sender, CreateUserErrorEventArgs e);
public enum DataBoundControlMode
{
ReadOnly = 0,
Edit = 1,
Insert = 2,
}
public enum DataControlCellType
{
Header = 0,
Footer = 1,
DataCell = 2,
}
public enum DataControlRowState
{
Normal = 0,
Alternate = 1,
Selected = 2,
Edit = 4,
Insert = 8,
}
public enum DataControlRowType
{
Header = 0,
Footer = 1,
DataRow = 2,
Separator = 3,
Pager = 4,
EmptyDataRow = 5,
}
public delegate void DataGridCommandEventHandler(Object source, DataGridCommandEventArgs e);
public delegate void DataGridItemEventHandler(Object sender, DataGridItemEventArgs e);
public delegate void DataGridPageChangedEventHandler(Object source, DataGridPageChangedEventArgs e);
public delegate void DataGridSortCommandEventHandler(Object source, DataGridSortCommandEventArgs e);
public delegate void DataListCommandEventHandler(Object source, DataListCommandEventArgs e);
public delegate void DataListItemEventHandler(Object sender, DataListItemEventArgs e);
public enum DayNameFormat
{
Full = 0,
Short = 1,
FirstLetter = 2,
FirstTwoLetters = 3,
Shortest = 4,
}
public delegate void DayRenderEventHandler(Object sender, DayRenderEventArgs e);
public delegate void DetailsViewCommandEventHandler(Object sender, DetailsViewCommandEventArgs e);
public delegate void DetailsViewDeletedEventHandler(Object sender, DetailsViewDeletedEventArgs e);
public delegate void DetailsViewDeleteEventHandler(Object sender, DetailsViewDeleteEventArgs e);
public delegate void DetailsViewInsertedEventHandler(Object sender, DetailsViewInsertedEventArgs e);
public delegate void DetailsViewInsertEventHandler(Object sender, DetailsViewInsertEventArgs e);
public enum DetailsViewMode
{
ReadOnly = 0,
Edit = 1,
Insert = 2,
}
public delegate void DetailsViewModeEventHandler(Object sender, DetailsViewModeEventArgs e);
public delegate void DetailsViewPageEventHandler(Object sender, DetailsViewPageEventArgs e);
public delegate void DetailsViewUpdatedEventHandler(Object sender, DetailsViewUpdatedEventArgs e);
public delegate void DetailsViewUpdateEventHandler(Object sender, DetailsViewUpdateEventArgs e);
public enum FirstDayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Default = 7,
}
public enum FontSize
{
NotSet = 0,
AsUnit = 1,
Smaller = 2,
Larger = 3,
XXSmall = 4,
XSmall = 5,
Small = 6,
Medium = 7,
Large = 8,
XLarge = 9,
XXLarge = 10,
}
public delegate void FormViewCommandEventHandler(Object sender, FormViewCommandEventArgs e);
public delegate void FormViewDeletedEventHandler(Object sender, FormViewDeletedEventArgs e);
public delegate void FormViewDeleteEventHandler(Object sender, FormViewDeleteEventArgs e);
public delegate void FormViewInsertedEventHandler(Object sender, FormViewInsertedEventArgs e);
public delegate void FormViewInsertEventHandler(Object sender, FormViewInsertEventArgs e);
public enum FormViewMode
{
ReadOnly = 0,
Edit = 1,
Insert = 2,
}
public delegate void FormViewModeEventHandler(Object sender, FormViewModeEventArgs e);
public delegate void FormViewPageEventHandler(Object sender, FormViewPageEventArgs e);
public delegate void FormViewUpdatedEventHandler(Object sender, FormViewUpdatedEventArgs e);
public delegate void FormViewUpdateEventHandler(Object sender, FormViewUpdateEventArgs e);
public enum GridLines
{
None = 0,
Horizontal = 1,
Vertical = 2,
Both = 3,
}
public delegate void GridViewCancelEditEventHandler(Object sender, GridViewCancelEditEventArgs e);
public delegate void GridViewCommandEventHandler(Object sender, GridViewCommandEventArgs e);
public delegate void GridViewDeletedEventHandler(Object sender, GridViewDeletedEventArgs e);
public delegate void GridViewDeleteEventHandler(Object sender, GridViewDeleteEventArgs e);
public delegate void GridViewEditEventHandler(Object sender, GridViewEditEventArgs e);
public delegate void GridViewPageEventHandler(Object sender, GridViewPageEventArgs e);
public delegate void GridViewRowEventHandler(Object sender, GridViewRowEventArgs e);
public delegate void GridViewSelectEventHandler(Object sender, GridViewSelectEventArgs e);
public delegate void GridViewSortEventHandler(Object sender, GridViewSortEventArgs e);
public delegate void GridViewUpdatedEventHandler(Object sender, GridViewUpdatedEventArgs e);
public delegate void GridViewUpdateEventHandler(Object sender, GridViewUpdateEventArgs e);
public enum HorizontalAlign
{
NotSet = 0,
Left = 1,
Center = 2,
Right = 3,
Justify = 4,
}
public enum HotSpotMode
{
NotSet = 0,
Navigate = 1,
PostBack = 2,
Inactive = 3,
}
public enum ImageAlign
{
NotSet = 0,
Left = 1,
Right = 2,
Baseline = 3,
Top = 4,
Middle = 5,
Bottom = 6,
AbsBottom = 7,
AbsMiddle = 8,
TextTop = 9,
}
public delegate void ImageMapEventHandler(Object sender, ImageMapEventArgs e);
public enum ListItemType
{
Header = 0,
Footer = 1,
Item = 2,
AlternatingItem = 3,
SelectedItem = 4,
EditItem = 5,
Separator = 6,
Pager = 7,
}
public enum ListSelectionMode
{
Single = 0,
Multiple = 1,
}
public enum LiteralMode
{
Transform = 0,
PassThrough = 1,
Encode = 2,
}
public delegate void LoginCancelEventHandler(Object sender, LoginCancelEventArgs e);
public enum LoginFailureAction
{
Refresh = 0,
RedirectToLoginPage = 1,
}
public enum LoginTextLayout
{
TextOnLeft = 0,
TextOnTop = 1,
}
public enum LogoutAction
{
Refresh = 0,
Redirect = 1,
RedirectToLoginPage = 2,
}
public delegate void MailMessageEventHandler(Object sender, MailMessageEventArgs e);
public delegate void MenuEventHandler(Object sender, MenuEventArgs e);
public enum MenuRenderingMode
{
Default = 0,
Table = 1,
List = 2,
}
public delegate void MonthChangedEventHandler(Object sender, MonthChangedEventArgs e);
public enum NextPrevFormat
{
CustomText = 0,
ShortMonth = 1,
FullMonth = 2,
}
public delegate void ObjectDataSourceDisposingEventHandler(Object sender, ObjectDataSourceDisposingEventArgs e);
public delegate void ObjectDataSourceFilteringEventHandler(Object sender, ObjectDataSourceFilteringEventArgs e);
public delegate void ObjectDataSourceMethodEventHandler(Object sender, ObjectDataSourceMethodEventArgs e);
public delegate void ObjectDataSourceObjectEventHandler(Object sender, ObjectDataSourceEventArgs e);
public delegate void ObjectDataSourceSelectingEventHandler(Object sender, ObjectDataSourceSelectingEventArgs e);
public delegate void ObjectDataSourceStatusEventHandler(Object sender, ObjectDataSourceStatusEventArgs e);
public enum Orientation
{
Horizontal = 0,
Vertical = 1,
}
public enum PagerButtons
{
NextPrevious = 0,
Numeric = 1,
NextPreviousFirstLast = 2,
NumericFirstLast = 3,
}
public enum PagerMode
{
NextPrev = 0,
NumericPages = 1,
}
public enum PagerPosition
{
Bottom = 0,
Top = 1,
TopAndBottom = 2,
}
public enum PathDirection
{
RootToCurrent = 0,
CurrentToRoot = 1,
}
public enum RepeatDirection
{
Horizontal = 0,
Vertical = 1,
}
public delegate void RepeaterCommandEventHandler(Object source, RepeaterCommandEventArgs e);
public delegate void RepeaterItemEventHandler(Object sender, RepeaterItemEventArgs e);
public enum RepeatLayout
{
Table = 0,
Flow = 1,
UnorderedList = 2,
OrderedList = 3,
}
public enum ScrollBars
{
None = 0,
Horizontal = 1,
Vertical = 2,
Both = 3,
Auto = 4,
}
public delegate void SendMailErrorEventHandler(Object sender, SendMailErrorEventArgs e);
public delegate void ServerValidateEventHandler(Object source, ServerValidateEventArgs args);
public delegate void SiteMapNodeItemEventHandler(Object sender, SiteMapNodeItemEventArgs e);
public enum SiteMapNodeItemType
{
Root = 0,
Parent = 1,
Current = 2,
PathSeparator = 3,
}
public enum SortDirection
{
Ascending = 0,
Descending = 1,
}
public delegate void SqlDataSourceCommandEventHandler(Object sender, SqlDataSourceCommandEventArgs e);
public enum SqlDataSourceCommandType
{
Text = 0,
StoredProcedure = 1,
}
public delegate void SqlDataSourceFilteringEventHandler(Object sender, SqlDataSourceFilteringEventArgs e);
public enum SqlDataSourceMode
{
DataReader = 0,
DataSet = 1,
}
public delegate void SqlDataSourceSelectingEventHandler(Object sender, SqlDataSourceSelectingEventArgs e);
public delegate void SqlDataSourceStatusEventHandler(Object sender, SqlDataSourceStatusEventArgs e);
public enum TableCaptionAlign
{
NotSet = 0,
Top = 1,
Bottom = 2,
Left = 3,
Right = 4,
}
public enum TableHeaderScope
{
NotSet = 0,
Row = 1,
Column = 2,
}
public enum TableRowSection
{
TableHeader = 0,
TableBody = 1,
TableFooter = 2,
}
public enum TextAlign
{
Left = 1,
Right = 2,
}
public enum TextBoxMode
{
SingleLine = 0,
MultiLine = 1,
Password = 2,
}
public enum TitleFormat
{
Month = 0,
MonthYear = 1,
}
public delegate void TreeNodeEventHandler(Object sender, TreeNodeEventArgs e);
public enum TreeNodeSelectAction
{
Select = 0,
Expand = 1,
SelectExpand = 2,
None = 3,
}
public enum TreeNodeTypes
{
None = 0,
Root = 1,
Parent = 2,
Leaf = 4,
All = 7,
}
public enum TreeViewImageSet
{
Custom = 0,
XPFileExplorer = 1,
Msdn = 2,
WindowsHelp = 3,
Simple = 4,
Simple2 = 5,
BulletedList = 6,
BulletedList2 = 7,
BulletedList3 = 8,
BulletedList4 = 9,
Arrows = 10,
News = 11,
Contacts = 12,
Inbox = 13,
Events = 14,
Faq = 15,
}
public enum UnitType
{
Pixel = 1,
Point = 2,
Pica = 3,
Inch = 4,
Mm = 5,
Cm = 6,
Percentage = 7,
Em = 8,
Ex = 9,
}
public enum ValidationCompareOperator
{
Equal = 0,
NotEqual = 1,
GreaterThan = 2,
GreaterThanEqual = 3,
LessThan = 4,
LessThanEqual = 5,
DataTypeCheck = 6,
}
public enum ValidationDataType
{
String = 0,
Integer = 1,
Double = 2,
Date = 3,
Currency = 4,
}
public enum ValidationSummaryDisplayMode
{
List = 0,
BulletList = 1,
SingleParagraph = 2,
}
public enum ValidatorDisplay
{
None = 0,
Static = 1,
Dynamic = 2,
}
public enum VerticalAlign
{
NotSet = 0,
Top = 1,
Middle = 2,
Bottom = 3,
}
public delegate void WizardNavigationEventHandler(Object sender, WizardNavigationEventArgs e);
public enum WizardStepType
{
Auto = 0,
Complete = 1,
Finish = 2,
Start = 3,
Step = 4,
}
}
| |
using UnityEngine;
using System.Collections;
using UnityAnalyticsHeatmap;
public class PlayerSkills : MonoBehaviour
{
public class Charge
{
private Rigidbody2D m_entityBody;
private float m_startSpeed;
private float m_endSpeed;
private float m_progress = 0.0f;
private Vector2 m_destination;
public Charge(Rigidbody2D entityBody, float startSpeed, float endSpeed, Vector2 destination)
{
m_entityBody = entityBody;
m_startSpeed = startSpeed;
m_endSpeed = endSpeed;
m_destination = destination;
}
public bool update()
{
if (!m_entityBody)
return false;
Vector2 curPos = m_entityBody.transform.position;
Vector2 delta = m_destination - curPos;
m_entityBody.velocity = delta.normalized * FUtil.regress(m_startSpeed, m_endSpeed, Mathf.Clamp(m_progress, 0f, 1f));
m_progress += Time.deltaTime;
if(Physics2D.Linecast(curPos, curPos + delta.normalized * 0.5f, 1 << LayerMask.NameToLayer("Ground")))
{
return false;
}
if (delta.magnitude <= 0.4f)
{
//m_airCharge = false;
//m_marker.removeMark();
m_entityBody.velocity = delta.normalized * m_endSpeed;
return false;
}
return true;
}
}
[SerializeField]
float m_startChargeSpeed = 10.0f;
[SerializeField]
float m_endChargeSpeed = 4.0f;
[SerializeField]
float m_groundStartChargeSpeed = 5.0f;
[SerializeField]
float m_groundEndChargeSpeed = 1.0f;
private Rigidbody2D m_playerBody;
private DestinationMarker m_marker;
private Charge m_currentCharge;
private Vector2 m_airChargeDestination;
private Color m_chargeColor = new Color(0.0f / 255.0f, 255.0f / 255.0f, 0.0f, 1);
private Color m_idleColor = Color.white;
private const float m_boostEffectDuration = 0.5f;
private float m_boostEffectTimeLeft = 0.5f;
private bool m_boostEffectActive = false;
private ParticleSystem m_boostEffect;
private Transform m_cameraTarget;
private float m_cameraTargetSpeedMultiplier = 0.002f;
private Vector2 m_cameraTargetMaxPos = new Vector2(3.0f, 3.0f);
// Use this for initialization
void Start ()
{
m_playerBody = GetComponent<Rigidbody2D>();
m_marker = GetComponent<DestinationMarker>();
m_boostEffect = transform.Find("BoostEffect").GetComponent<ParticleSystem>();
m_cameraTarget = transform.FindChild("CameraTarget");
}
// Update is called once per frame
void Update ()
{
if(m_boostEffectActive)
{
m_boostEffectTimeLeft -= Time.deltaTime;
if (m_boostEffectTimeLeft <= 0.0f)
boostEffect(false);
}
/*
if(m_cameraTarget && m_playerBody)
{
float x = Mathf.Clamp(m_cameraTarget.localPosition.x + m_playerBody.velocity.x * m_cameraTargetSpeedMultiplier, -m_cameraTargetMaxPos.x, m_cameraTargetMaxPos.x);
float y = Mathf.Clamp(m_cameraTarget.localPosition.y + m_playerBody.velocity.y * m_cameraTargetSpeedMultiplier, -m_cameraTargetMaxPos.y, m_cameraTargetMaxPos.y);
m_cameraTarget.localPosition = new Vector2(x, 0.0f);
}
*/
}
void FixedUpdate()
{
if (m_currentCharge != null)
{
if(!m_currentCharge.update())
{
m_currentCharge = null;
m_marker.removeMark();
//changeFireColor(m_idleColor);
}
}
}
public void initCharge(Vector2 start, Vector2 target, bool grounded)
{
m_airChargeDestination = target;
m_marker.mark(target);
if(grounded)
{
AudioSource chargeSound = m_boostEffect.GetComponent<AudioSource>();
if (chargeSound && !chargeSound.isPlaying)
chargeSound.Play();
m_currentCharge = new Charge(m_playerBody, m_groundStartChargeSpeed, m_groundEndChargeSpeed, target);
}
else
{
m_currentCharge = new Charge(m_playerBody, m_startChargeSpeed, m_endChargeSpeed, target);
AudioSource chargeSound = GetComponent<AudioSource>();
if (chargeSound)
chargeSound.Play();
}
//changeFireColor(m_chargeColor);
boostEffect(!grounded);
}
private void changeFireColor(Color color)
{
var particleSystems = GetComponentsInChildren<ParticleSystem>();
foreach(var ps in particleSystems)
{
if(ps.name == "Flames")
{
ps.startColor = color;
}
}
}
private void boostEffect(bool trigger)
{
m_boostEffectTimeLeft = m_boostEffectDuration;
var particleSystems = GetComponentsInChildren<ParticleSystem>();
m_boostEffectActive = trigger;
//if (trigger)
//Instantiate(m_boostEffect, transform.position, Quaternion.identity);
m_boostEffect.enableEmission = trigger;
/*
foreach (var ps in particleSystems)
{
if (ps.name == "Fire")
{
ps.startColor = trigger ? m_chargeColor : m_idleColor;
ps.emissionRate = trigger ? 30 : 15;
}
if (ps.name == "Flames")
{
ps.startColor = trigger ? m_chargeColor : m_idleColor;
ps.maxParticles = trigger ? 50 : 25;
ps.emissionRate = trigger ? 45 : 25;
}
}
*/
}
public void OnTriggerExit2D(Collider2D other)
{
}
public void OnTriggerEnter2D(Collider2D other)
{
Burnable burnable = other.GetComponent<Burnable>();
if (GetComponent<SelfDestruction>() == null && burnable && !burnable.IsBurning())
{
HeatmapEvent.Send("BurnedVegetation2", transform.position, Time.timeSinceLevelLoad);
KHeatmap.Log("BurnedVegetation2", transform.position);
burnable.Burn();
}
//if (other.GetComponent<ChargeRecharge>())
//boostEffect(true);
}
public void OnCollisionExit2D(Collision2D collision)
{
}
public void OnCollisionEnter2D(Collision2D collision)
{
/*
Vector2 curPos = transform.position;
Vector2 delta = m_airChargeDestination - curPos;
if(m_playerBody.velocity.magnitude > m_endChargeSpeed)
m_playerBody.velocity = delta.normalized * m_endChargeSpeed;
m_currentCharge = null;
m_marker.removeMark();
*/
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;
namespace MapTableCreator
{
public partial class Form1 : Form
{
private Facet f;
private bool closed = false;
private bool stopcollect = false;
private bool handle_select = false;
private TextWriter errwr, outwr;
public Form1()
{
InitializeComponent();
}
class FileComparer : IComparer
{
private int GetValue(String s)
{
int indb = s.LastIndexOf("\\");
if (indb == -1)
indb = 0;
int ind = s.IndexOf("_", indb);
int ind2 = s.IndexOf("_", ind + 1);
int ind3 = s.IndexOf(".dat");
String num1 = s.Substring(ind+1, ind2 - ind-1);
String num2 = s.Substring(ind2+1, ind3 - ind2-1);
return Convert.ToInt32(num1) * 100 + Convert.ToInt32(num2);
}
int IComparer.Compare(Object a, Object b)
{
return GetValue((String)a).CompareTo(GetValue((String)b));
}
}
private void button1_Click(object sender, EventArgs e)
{
if (fbd.ShowDialog() == DialogResult.OK)
textBox2.Text = fbd.SelectedPath;
}
class ThreadParam
{
public String[] files;
public int num;
}
private void Inc()
{
progressBar1.Value++;
if ((progressBar1.Value % 100) == 0)
{
GC.Collect();
Application.DoEvents();
}
}
private delegate void IncDelegate();
private void MyThreadCalc(object Param)
{
ThreadParam tp = (ThreadParam)Param;
String[] files = tp.files;
foreach (String s in files)
{
Parser p = new Parser(s, errwr, outwr, writeOnlyCheck.Checked, DelimiterCheck.Checked, StaticCheck.Checked, TileCheck.Checked);
BlockFile b = p.Parse();
lock (f.blockfileslist)
{
if (numBlocks.Value > 0 && f.blockfileslist.Count >= numBlocks.Value)
{
stopcollect = true;
if (parseOnly.Checked)
break;
}
if (!stopcollect)
f.blockfileslist.Add(b);
}
if (closed)
break;
progressBar1.BeginInvoke(new IncDelegate(Inc));
}
}
private void button2_Click(object sender, EventArgs e)
{
handle_select = false;
this.blockbox.Text = "";
blocklist.DataSource = null;
bool genera = extendedCheck.Checked;
stopcollect = false;
groupBox1.Enabled = false;
groupBox2.Enabled = false;
f=new Facet();
blocklist.DataSource = null;
GC.Collect();
String[] files = Directory.GetFiles(textBox2.Text, "*.dat");
IComparer icomp = new FileComparer();
Array.Sort(files, icomp);
progressBar1.Minimum = 0;
progressBar1.Maximum = (parseOnly.Checked && numBlocks.Value>0) ? (int)numBlocks.Value : files.Length;
progressBar1.Value = 0;
errwr = new StreamWriter("error.log");
outwr = null;
if(genera)
outwr = new StreamWriter("outuput.log");
int div = (parseOnly.Checked && numBlocks.Value > 0) ? (int)numBlocks.Value : files.Length / 3;
if (div > 50)
{
bw1.RunWorkerAsync(files);
}
else
{
foreach (String s in files)
{
Parser p = new Parser(s, errwr, outwr, writeOnlyCheck.Checked, DelimiterCheck.Checked, StaticCheck.Checked, TileCheck.Checked);
BlockFile b = p.Parse();
if (numBlocks.Value > 0 && f.blockfileslist.Count >= numBlocks.Value)
{
stopcollect = true;
if (parseOnly.Checked)
break;
}
if (!stopcollect)
{
f.blockfiles.AddLast(b);
f.blockfileslist.Add(b);
}
Inc();
if (closed)
break;
}
bw1_RunWorkerCompleted(null, null);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
closed = true;
}
private void blocklist_SelectedIndexChanged(object sender, EventArgs e)
{
if (!handle_select)
return;
BlockFile bf = blocklist.SelectedItem as BlockFile;
blockbox.Text = bf.Dump();
}
private void button3_Click(object sender, EventArgs e)
{
GridForm frm = new GridForm(f);
frm.Show();
}
private void bw1_DoWork(object sender, DoWorkEventArgs e)
{
String[] files = (String[])e.Argument;
int realsize = (parseOnly.Checked && numBlocks.Value > 0) ? (int)numBlocks.Value : files.Length;
int div = realsize / 3;
ThreadParam puno = new ThreadParam();
puno.files = new string[div];
Array.Copy(files, 0, puno.files, 0, div);
puno.num = 1;
ThreadParam pdue = new ThreadParam();
pdue.files = new string[div];
Array.Copy(files, div, pdue.files, 0, div);
pdue.num = 2;
ThreadParam ptre = new ThreadParam();
ptre.files = new string[realsize - 2 * div];
Array.Copy(files, 2 * div, ptre.files, 0, realsize - 2 * div);
ptre.num = 3;
Thread t1 = new Thread(new ParameterizedThreadStart(MyThreadCalc));
Thread t2 = new Thread(new ParameterizedThreadStart(MyThreadCalc));
Thread t3 = new Thread(new ParameterizedThreadStart(MyThreadCalc));
t1.Start(puno);
t2.Start(pdue);
t3.Start(ptre);
t1.Join();
t2.Join();
t3.Join();
}
private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (sender != null)
{
f.blockfileslist.Sort();
foreach (BlockFile b in f.blockfileslist)
{
f.blockfiles.AddLast(b);
}
}
blocklist.DataSource = null;
blocklist.DataSource = f.blockfileslist;
blocklist.DisplayMember = "Name";
CurrencyManager cm=this.BindingContext[f.blockfileslist] as CurrencyManager;
if (cm != null)
cm.Refresh();
errwr.Close();
if (outwr != null)
outwr.Close();
StreamWriter table = new StreamWriter("table.txt");
foreach (ushort MLG in Parser.table.Keys)
{
ushort value;
Parser.table.TryGetValue(MLG, out value);
table.WriteLine(MLG + "->" + value);
}
table.Close();
handle_select = true;
MessageBox.Show("Completato", "UOKR Map Decoder");
groupBox1.Enabled = true;
groupBox2.Enabled = true;
}
}
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="CustomerInfo.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Users
{
using System;
using Data;
using Diagnostics;
using DomainModel.Addresses;
using DomainModel.Data;
using Validators.Interception;
/// <summary>
/// Customer info container.
/// </summary>
[Serializable]
public class CustomerInfo : DomainModel.Users.CustomerInfo, IEntity
{
/// <summary>
/// Gets or sets the billing address.
/// </summary>
/// <value>The billing address.</value>
[Entity(FieldName = "Billing")]
public override AddressInfo BillingAddress { get; [NotNullValue] set; }
/// <summary>
/// Gets or sets the shipping address.
/// </summary>
/// <value>The shipping address.</value>
[Entity(FieldName = "Shipping")]
public override AddressInfo ShippingAddress { get; [NotNullValue] set; }
/// <summary>
/// Gets or sets the customer id.
/// </summary>
/// <value>
/// The customer id.
/// </value>
[NotNull, Entity(FieldName = "Customer Id")]
public override string CustomerId
{
get
{
return base.CustomerId;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.CustomerId = value;
}
}
/// <summary>
/// Gets or sets the account id.
/// </summary>
/// <value>
/// The account id.
/// </value>
[NotNull, Entity(FieldName = "Account Id")]
public override string AccountId
{
get
{
return base.AccountId;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.AccountId = value;
}
}
/// <summary>
/// Gets or sets the type of the account.
/// </summary>
/// <value>
/// The type of the account.
/// </value>
[NotNull, Entity(FieldName = "Account Type")]
public override string AccountType
{
get
{
return base.AccountType;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.AccountType = value;
}
}
/// <summary>
/// Gets or sets the primary email.
/// </summary>
/// <value>The primary email.</value>
[NotNull, Entity(FieldName = "Email")]
public override string Email
{
get
{
return base.Email;
}
[EmailValue]
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.Email = value;
}
}
/// <summary>
/// Gets or sets the seconary email.
/// </summary>
/// <value>The seconary email.</value>
[NotNull, Entity(FieldName = "Email 2")]
public override string Email2
{
get
{
return base.Email2;
}
[EmailValue]
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.Email2 = value;
}
}
/// <summary>
/// Gets or sets the mobile number.
/// </summary>
/// <value>The mobile number.</value>
[NotNull, Entity(FieldName = "Mobile")]
public override string Mobile
{
get
{
return base.Mobile;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.Mobile = value;
}
}
/// <summary>
/// Gets or sets the phone number.
/// </summary>
/// <value>The phone number.</value>
[NotNull, Entity(FieldName = "Phone")]
public override string Phone
{
get
{
return base.Phone;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.Phone = value;
}
}
/// <summary>
/// Gets or sets the fax number.
/// </summary>
/// <value>The fax number.</value>
[NotNull, Entity(FieldName = "Fax")]
public override string Fax
{
get
{
return base.Fax;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.Fax = value;
}
}
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
/// <value>The name of the user.</value>
[NotNull, Entity(FieldName = "Nick Name")]
public override string NickName
{
get
{
return base.NickName;
}
[NotNullValue]
set
{
Assert.ArgumentNotNull(value, "value");
base.NickName = value;
}
}
#region Implementation of IEntity
/// <summary>
/// Gets or sets the alias.
/// </summary>
/// <value>The alias.</value>
public virtual string Alias { get; [NotNullValue] set; }
#endregion
}
}
| |
#region License
//
// InputElement.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// 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
#region Using directives
using System;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>InputElement</c> represents a self contained element
/// that will allow access to its child elements. If the next element
/// read from the <c>NodeReader</c> is not a child then this
/// will return null. The input element node also allows the attribute
/// values associated with the node to be accessed.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Stream.NodeReader
/// </seealso>
class InputElement : InputNode {
/// <summary>
/// This contains all the attributes associated with the element.
/// </summary>
private readonly InputNodeMap map;
/// <summary>
/// This is the node reader that reads from the XML document.
/// </summary>
private readonly NodeReader reader;
/// <summary>
/// This is the parent node for this XML input element node.
/// </summary>
private readonly InputNode parent;
/// <summary>
/// This is the XML element that this node provides access to.
/// </summary>
private readonly EventNode node;
/// <summary>
/// Constructor for the <c>InputElement</c> object. This
/// is used to create an input node that will provide access to
/// an XML element. All attributes associated with the element
/// given are extracted and exposed via the attribute node map.
/// </summary>
/// <param name="parent">
/// this is the parent XML element for this
/// </param>
/// <param name="reader">
/// this is the reader used to read XML elements
/// </param>
/// <param name="node">
/// this is the XML element wrapped by this node
/// </param>
public InputElement(InputNode parent, NodeReader reader, EventNode node) {
this.map = new InputNodeMap(this, node);
this.reader = reader;
this.parent = parent;
this.node = node;
}
/// <summary>
/// This is used to return the source object for this node. This
/// is used primarily as a means to determine which XML provider
/// is parsing the source document and producing the nodes. It
/// is useful to be able to determine the XML provider like this.
/// </summary>
/// <returns>
/// this returns the source of this input node
/// </returns>
public Object Source {
get {
return node.Source;
}
}
//public Object GetSource() {
// return node.Source;
//}
/// This is used to acquire the <c>Node</c> that is the
/// parent of this node. This will return the node that is
/// the direct parent of this node and allows for siblings to
/// make use of nodes with their parents if required.
/// </summary>
/// <returns>
/// this returns the parent node for this node
/// </returns>
public InputNode Parent {
get {
return parent;
}
}
//public InputNode GetParent() {
// return parent;
//}
/// This provides the position of this node within the document.
/// This allows the user of this node to report problems with
/// the location within the document, allowing the XML to be
/// debugged if it does not match the class schema.
/// </summary>
/// <returns>
/// this returns the position of the XML read cursor
/// </returns>
public Position Position {
get {
return new InputPosition(node);
}
}
//public Position GetPosition() {
// return new InputPosition(node);
//}
/// Returns the name of the node that this represents. This is
/// an immutable property and should not change for any node.
/// This provides the name without the name space part.
/// </summary>
/// <returns>
/// returns the name of the node that this represents
/// </returns>
public String Name {
get {
return node.Name;
}
}
//public String GetName() {
// return node.Name;
//}
/// This is used to acquire the namespace prefix for the node.
/// If there is no namespace prefix for the node then this will
/// return null. Acquiring the prefix enables the qualification
/// of the node to be determined. It also allows nodes to be
/// grouped by its prefix and allows group operations.
/// </summary>
/// <returns>
/// this returns the prefix associated with this node
/// </returns>
public String Prefix {
get {
return node.Prefix;
}
}
//public String GetPrefix() {
// return node.Prefix;
//}
/// This allows the namespace reference URI to be determined.
/// A reference is a globally unique string that allows the
/// node to be identified. Typically the reference will be a URI
/// but it can be any unique string used to identify the node.
/// This allows the node to be identified within the namespace.
/// </summary>
/// <returns>
/// this returns the associated namespace reference URI
/// </returns>
public String Reference {
get {
return node.Reference;
}
}
//public String GetReference() {
// return node.Reference;
//}
/// This method is used to determine if this node is the root
/// node for the XML document. The root node is the first node
/// in the document and has no sibling nodes. This is false
/// if the node has a parent node or a sibling node.
/// </summary>
/// <returns>
/// true if this is the root node within the document
/// </returns>
public bool IsRoot() {
return reader.IsRoot(this);
}
/// <summary>
/// This is used to determine if this node is an element. This
/// allows users of the framework to make a distinction between
/// nodes that represent attributes and nodes that represent
/// elements. This is particularly useful given that attribute
/// nodes do not maintain a node map of attributes.
/// </summary>
/// <returns>
/// this returns true as this instance is an element
/// </returns>
public bool IsElement() {
return true;
}
/// <summary>
/// Provides an attribute from the element represented. If an
/// attribute for the specified name does not exist within the
/// element represented then this method will return null.
/// </summary>
/// <param name="name">
/// this is the name of the attribute to retrieve
/// </param>
/// <returns>
/// this returns the value for the named attribute
/// </returns>
public InputNode GetAttribute(String name) {
return map.Get(name);
}
/// <summary>
/// This returns a map of the attributes contained within the
/// element. If no elements exist within the element then this
/// returns an empty map.
/// </summary>
/// <returns>
/// this returns a map of attributes for the element
/// </returns>
public NodeMap<InputNode> Attributes {
get {
return map;
}
}
//public NodeMap<InputNode> GetAttributes() {
// return map;
//}
/// Returns the value for the node that this represents. This
/// is an immutable value for the node and cannot be changed.
/// If there is a problem reading an exception is thrown.
/// </summary>
/// <returns>
/// the name of the value for this node instance
/// </returns>
public String Value {
get {
return reader.ReadValue(this);
}
}
//public String GetValue() {
// return reader.ReadValue(this);
//}
/// The method is used to acquire the next child attribute of this
/// element. If the next element from the <c>NodeReader</c>
/// is not a child node to the element that this represents then
/// this will return null, which ensures each element represents
/// a self contained collection of child nodes.
/// </summary>
/// <returns>
/// this returns the next child element of this node
/// </returns>
public InputNode Next {
get {
return reader.ReadElement(this);
}
}
//public InputNode GetNext() {
// return reader.ReadElement(this);
//}
/// The method is used to acquire the next child attribute of this
/// element. If the next element from the <c>NodeReader</c>
/// is not a child node to the element that this represents then
/// this will return null, also if the next element does not match
/// the specified name then this will return null.
/// </summary>
/// <param name="name">
/// this is the name expected fromt he next element
/// </param>
/// <returns>
/// this returns the next child element of this node
/// </returns>
public InputNode GetNext(String name) {
return reader.ReadElement(this, name);
}
/// <summary>
/// This method is used to skip all child elements from this
/// element. This allows elements to be effectively skipped such
/// that when parsing a document if an element is not required
/// then that element can be completely removed from the XML.
/// </summary>
public void Skip() {
reader.SkipElement(this);
}
/// <summary>
/// This is used to determine if this input node is empty. An
/// empty node is one with no attributes or children. This can
/// be used to determine if a given node represents an empty
/// entity, with which no extra data can be extracted.
/// </summary>
/// <returns>
/// this returns true if the node is an empty element
/// </returns>
public bool IsEmpty() {
if(!map.IsEmpty()) {
return false;
}
return reader.IsEmpty(this);
}
/// <summary>
/// This is the string representation of the element. It is
/// used for debugging purposes. When evaluating the element
/// the to string can be used to print out the element name.
/// </summary>
/// <returns>
/// this returns a text description of the element
/// </returns>
public String ToString() {
return String.format("element %s", Name);
}
}
}
| |
using UnityEngine.Rendering;
namespace UnityEngine.PostProcessing
{
public sealed class TaaComponent : PostProcessingComponentRenderTexture<AntialiasingModel>
{
static class Uniforms
{
internal static int _Jitter = Shader.PropertyToID("_Jitter");
internal static int _SharpenParameters = Shader.PropertyToID("_SharpenParameters");
internal static int _FinalBlendParameters = Shader.PropertyToID("_FinalBlendParameters");
internal static int _HistoryTex = Shader.PropertyToID("_HistoryTex");
internal static int _MainTex = Shader.PropertyToID("_MainTex");
}
const string k_ShaderString = "Hidden/Post FX/Temporal Anti-aliasing";
const int k_SampleCount = 8;
readonly RenderBuffer[] m_MRT = new RenderBuffer[2];
int m_SampleIndex = 0;
bool m_ResetHistory = true;
RenderTexture m_HistoryTexture;
public override bool active
{
get
{
return model.enabled
&& model.settings.method == AntialiasingModel.Method.Taa
&& SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)
&& SystemInfo.supportsMotionVectors
&& !context.interrupted;
}
}
public override DepthTextureMode GetCameraFlags()
{
return DepthTextureMode.Depth | DepthTextureMode.MotionVectors;
}
public void ResetHistory()
{
m_ResetHistory = true;
}
public void SetProjectionMatrix()
{
var settings = model.settings.taaSettings;
var jitter = GenerateRandomOffset();
jitter *= settings.jitterSpread;
context.camera.nonJitteredProjectionMatrix = context.camera.projectionMatrix;
context.camera.projectionMatrix = context.camera.orthographic
? GetOrthographicProjectionMatrix(jitter)
: GetPerspectiveProjectionMatrix(jitter);
#if UNITY_5_5_OR_NEWER
context.camera.useJitteredProjectionMatrixForTransparentRendering = false;
#endif
jitter.x /= context.width;
jitter.y /= context.height;
var material = context.materialFactory.Get(k_ShaderString);
material.SetVector(Uniforms._Jitter, jitter);
}
public void Render(RenderTexture source, RenderTexture destination)
{
var material = context.materialFactory.Get(k_ShaderString);
material.shaderKeywords = null;
var settings = model.settings.taaSettings;
if (m_ResetHistory || m_HistoryTexture == null || m_HistoryTexture.width != source.width || m_HistoryTexture.height != source.height)
{
if (m_HistoryTexture)
RenderTexture.ReleaseTemporary(m_HistoryTexture);
m_HistoryTexture = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
m_HistoryTexture.name = "TAA History";
Graphics.Blit(source, m_HistoryTexture, material, 2);
}
const float kMotionAmplification = 100f * 60f;
material.SetVector(Uniforms._SharpenParameters, new Vector4(settings.sharpen, 0f, 0f, 0f));
material.SetVector(Uniforms._FinalBlendParameters, new Vector4(settings.stationaryBlending, settings.motionBlending, kMotionAmplification, 0f));
material.SetTexture(Uniforms._MainTex, source);
material.SetTexture(Uniforms._HistoryTex, m_HistoryTexture);
var tempHistory = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
tempHistory.name = "TAA History";
m_MRT[0] = destination.colorBuffer;
m_MRT[1] = tempHistory.colorBuffer;
Graphics.SetRenderTarget(m_MRT, source.depthBuffer);
GraphicsUtils.Blit(material, context.camera.orthographic ? 1 : 0);
RenderTexture.ReleaseTemporary(m_HistoryTexture);
m_HistoryTexture = tempHistory;
m_ResetHistory = false;
}
float GetHaltonValue(int index, int radix)
{
float result = 0f;
float fraction = 1f / (float)radix;
while (index > 0)
{
result += (float)(index % radix) * fraction;
index /= radix;
fraction /= (float)radix;
}
return result;
}
Vector2 GenerateRandomOffset()
{
var offset = new Vector2(
GetHaltonValue(m_SampleIndex & 1023, 2),
GetHaltonValue(m_SampleIndex & 1023, 3));
if (++m_SampleIndex >= k_SampleCount)
m_SampleIndex = 0;
return offset;
}
// Adapted heavily from PlayDead's TAA code
// https://github.com/playdeadgames/temporal/blob/master/Assets/Scripts/Extensions.cs
Matrix4x4 GetPerspectiveProjectionMatrix(Vector2 offset)
{
float vertical = Mathf.Tan(0.5f * Mathf.Deg2Rad * context.camera.fieldOfView);
float horizontal = vertical * context.camera.aspect;
offset.x *= horizontal / (0.5f * context.width);
offset.y *= vertical / (0.5f * context.height);
float left = (offset.x - horizontal) * context.camera.nearClipPlane;
float right = (offset.x + horizontal) * context.camera.nearClipPlane;
float top = (offset.y + vertical) * context.camera.nearClipPlane;
float bottom = (offset.y - vertical) * context.camera.nearClipPlane;
var matrix = new Matrix4x4();
matrix[0, 0] = (2f * context.camera.nearClipPlane) / (right - left);
matrix[0, 1] = 0f;
matrix[0, 2] = (right + left) / (right - left);
matrix[0, 3] = 0f;
matrix[1, 0] = 0f;
matrix[1, 1] = (2f * context.camera.nearClipPlane) / (top - bottom);
matrix[1, 2] = (top + bottom) / (top - bottom);
matrix[1, 3] = 0f;
matrix[2, 0] = 0f;
matrix[2, 1] = 0f;
matrix[2, 2] = -(context.camera.farClipPlane + context.camera.nearClipPlane) / (context.camera.farClipPlane - context.camera.nearClipPlane);
matrix[2, 3] = -(2f * context.camera.farClipPlane * context.camera.nearClipPlane) / (context.camera.farClipPlane - context.camera.nearClipPlane);
matrix[3, 0] = 0f;
matrix[3, 1] = 0f;
matrix[3, 2] = -1f;
matrix[3, 3] = 0f;
return matrix;
}
Matrix4x4 GetOrthographicProjectionMatrix(Vector2 offset)
{
float vertical = context.camera.orthographicSize;
float horizontal = vertical * context.camera.aspect;
offset.x *= horizontal / (0.5f * context.width);
offset.y *= vertical / (0.5f * context.height);
float left = offset.x - horizontal;
float right = offset.x + horizontal;
float top = offset.y + vertical;
float bottom = offset.y - vertical;
return Matrix4x4.Ortho(left, right, bottom, top, context.camera.nearClipPlane, context.camera.farClipPlane);
}
public override void OnDisable()
{
if (m_HistoryTexture != null)
RenderTexture.ReleaseTemporary(m_HistoryTexture);
m_HistoryTexture = null;
m_SampleIndex = 0;
ResetHistory();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Automation;
using Microsoft.WindowsAzure.Management.Automation.Models;
namespace Microsoft.WindowsAzure.Management.Automation
{
public static partial class ConnectionTypeOperationsExtensions
{
/// <summary>
/// Create a connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create connectiontype
/// operation.
/// </param>
/// <returns>
/// The response model for the create connection type operation.
/// </returns>
public static ConnectionTypeCreateResponse Create(this IConnectionTypeOperations operations, string automationAccount, ConnectionTypeCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).CreateAsync(automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create connectiontype
/// operation.
/// </param>
/// <returns>
/// The response model for the create connection type operation.
/// </returns>
public static Task<ConnectionTypeCreateResponse> CreateAsync(this IConnectionTypeOperations operations, string automationAccount, ConnectionTypeCreateParameters parameters)
{
return operations.CreateAsync(automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IConnectionTypeOperations operations, string automationAccount, string connectionTypeName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).DeleteAsync(automationAccount, connectionTypeName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IConnectionTypeOperations operations, string automationAccount, string connectionTypeName)
{
return operations.DeleteAsync(automationAccount, connectionTypeName, CancellationToken.None);
}
/// <summary>
/// Retrieve the connectiontype identified by connectiontype name.
/// (see http://aka.ms/azureautomationsdk/connectiontypeoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// The response model for the get connection type operation.
/// </returns>
public static ConnectionTypeGetResponse Get(this IConnectionTypeOperations operations, string automationAccount, string connectionTypeName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).GetAsync(automationAccount, connectionTypeName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the connectiontype identified by connectiontype name.
/// (see http://aka.ms/azureautomationsdk/connectiontypeoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// The response model for the get connection type operation.
/// </returns>
public static Task<ConnectionTypeGetResponse> GetAsync(this IConnectionTypeOperations operations, string automationAccount, string connectionTypeName)
{
return operations.GetAsync(automationAccount, connectionTypeName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static ConnectionTypeListResponse List(this IConnectionTypeOperations operations, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).ListAsync(automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static Task<ConnectionTypeListResponse> ListAsync(this IConnectionTypeOperations operations, string automationAccount)
{
return operations.ListAsync(automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static ConnectionTypeListResponse ListNext(this IConnectionTypeOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static Task<ConnectionTypeListResponse> ListNextAsync(this IConnectionTypeOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
using System;
using System.Configuration;
using System.Runtime.Serialization;
using NServiceKit.Common.Web;
using NServiceKit.ServiceHost;
using NServiceKit.ServiceInterface.ServiceModel;
using NServiceKit.Text;
using NServiceKit.WebHost.Endpoints;
namespace NServiceKit.ServiceInterface.Auth
{
/// <summary>
/// Inject logic into existing services by introspecting the request and injecting your own
/// validation logic. Exceptions thrown will have the same behaviour as if the service threw it.
///
/// If a non-null object is returned the request will short-circuit and return that response.
/// </summary>
/// <param name="service">The instance of the service</param>
/// <param name="httpMethod">GET,POST,PUT,DELETE</param>
/// <param name="requestDto"></param>
/// <returns>Response DTO; non-null will short-circuit execution and return that response</returns>
public delegate object ValidateFn(IServiceBase service, string httpMethod, object requestDto);
/// <summary>An authentication.</summary>
[DataContract]
public class Auth : IReturn<AuthResponse>
{
/// <summary>Gets or sets the provider.</summary>
///
/// <value>The provider.</value>
[DataMember(Order=1)] public string provider { get; set; }
/// <summary>Gets or sets the state.</summary>
///
/// <value>The state.</value>
[DataMember(Order=2)] public string State { get; set; }
/// <summary>Gets or sets the oauth token.</summary>
///
/// <value>The oauth token.</value>
[DataMember(Order=3)] public string oauth_token { get; set; }
/// <summary>Gets or sets the oauth verifier.</summary>
///
/// <value>The oauth verifier.</value>
[DataMember(Order=4)] public string oauth_verifier { get; set; }
/// <summary>Gets or sets the name of the user.</summary>
///
/// <value>The name of the user.</value>
[DataMember(Order=5)] public string UserName { get; set; }
/// <summary>Gets or sets the password.</summary>
///
/// <value>The password.</value>
[DataMember(Order=6)] public string Password { get; set; }
/// <summary>Gets or sets the remember me.</summary>
///
/// <value>The remember me.</value>
[DataMember(Order=7)] public bool? RememberMe { get; set; }
/// <summary>Gets or sets the continue.</summary>
///
/// <value>The continue.</value>
[DataMember(Order=8)] public string Continue { get; set; }
// Thise are used for digest auth
[DataMember(Order=9)] public string nonce { get; set; }
/// <summary>Gets or sets URI of the document.</summary>
///
/// <value>The URI.</value>
[DataMember(Order=10)] public string uri { get; set; }
/// <summary>Gets or sets the response.</summary>
///
/// <value>The response.</value>
[DataMember(Order=11)] public string response { get; set; }
/// <summary>Gets or sets the qop.</summary>
///
/// <value>The qop.</value>
[DataMember(Order=12)] public string qop { get; set; }
/// <summary>Gets or sets the non-client.</summary>
///
/// <value>The non-client.</value>
[DataMember(Order=13)] public string nc { get; set; }
/// <summary>Gets or sets the cnonce.</summary>
///
/// <value>The cnonce.</value>
[DataMember(Order=14)] public string cnonce { get; set; }
}
/// <summary>An authentication response.</summary>
[DataContract]
public class AuthResponse
{
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.AuthResponse class.</summary>
public AuthResponse()
{
this.ResponseStatus = new ResponseStatus();
}
/// <summary>Gets or sets the identifier of the session.</summary>
///
/// <value>The identifier of the session.</value>
[DataMember(Order=1)] public string SessionId { get; set; }
/// <summary>Gets or sets the name of the user.</summary>
///
/// <value>The name of the user.</value>
[DataMember(Order=2)] public string UserName { get; set; }
/// <summary>Gets or sets URL of the referrer.</summary>
///
/// <value>The referrer URL.</value>
[DataMember(Order=3)] public string ReferrerUrl { get; set; }
/// <summary>Gets or sets the response status.</summary>
///
/// <value>The response status.</value>
[DataMember(Order=4)] public ResponseStatus ResponseStatus { get; set; }
}
/// <summary>An authentication service.</summary>
[DefaultRequest(typeof(Auth))]
public class AuthService : Service
{
/// <summary>The basic provider.</summary>
public const string BasicProvider = "basic";
/// <summary>The credentials provider.</summary>
public const string CredentialsProvider = "credentials";
/// <summary>The logout action.</summary>
public const string LogoutAction = "logout";
/// <summary>The digest provider.</summary>
public const string DigestProvider = "digest";
/// <summary>Gets or sets the current session factory.</summary>
///
/// <value>The current session factory.</value>
public static Func<IAuthSession> CurrentSessionFactory { get; set; }
/// <summary>Gets or sets the validate function.</summary>
///
/// <value>The validate function.</value>
public static ValidateFn ValidateFn { get; set; }
/// <summary>Gets the default o authentication provider.</summary>
///
/// <value>The default o authentication provider.</value>
public static string DefaultOAuthProvider { get; private set; }
/// <summary>Gets the default o authentication realm.</summary>
///
/// <value>The default o authentication realm.</value>
public static string DefaultOAuthRealm { get; private set; }
/// <summary>Gets the HTML redirect.</summary>
///
/// <value>The HTML redirect.</value>
public static string HtmlRedirect { get; internal set; }
/// <summary>Gets the authentication providers.</summary>
///
/// <value>The authentication providers.</value>
public static IAuthProvider[] AuthProviders { get; private set; }
static AuthService()
{
CurrentSessionFactory = () => new AuthUserSession();
}
/// <summary>Gets authentication provider.</summary>
///
/// <param name="provider">The provider.</param>
///
/// <returns>The authentication provider.</returns>
public static IAuthProvider GetAuthProvider(string provider)
{
if (AuthProviders == null || AuthProviders.Length == 0) return null;
if (provider == LogoutAction) return AuthProviders[0];
foreach (var authConfig in AuthProviders)
{
if (string.Compare(authConfig.Provider, provider,
StringComparison.InvariantCultureIgnoreCase) == 0)
return authConfig;
}
return null;
}
/// <summary>Initialises this object.</summary>
///
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
///
/// <param name="sessionFactory">The session factory.</param>
/// <param name="authProviders"> A variable-length parameters list containing authentication providers.</param>
public static void Init(Func<IAuthSession> sessionFactory, params IAuthProvider[] authProviders)
{
EndpointHost.AssertTestConfig();
if (authProviders.Length == 0)
throw new ArgumentNullException("authProviders");
DefaultOAuthProvider = authProviders[0].Provider;
DefaultOAuthRealm = authProviders[0].AuthRealm;
AuthProviders = authProviders;
if (sessionFactory != null)
CurrentSessionFactory = sessionFactory;
}
private void AssertAuthProviders()
{
if (AuthProviders == null || AuthProviders.Length == 0)
throw new ConfigurationErrorsException("No OAuth providers have been registered in your AppHost.");
}
/// <summary>Options the given request.</summary>
///
/// <param name="request">.</param>
public virtual void Options(Auth request) {}
/// <summary>Gets the given request.</summary>
///
/// <param name="request">.</param>
///
/// <returns>An object.</returns>
public virtual object Get(Auth request)
{
return Post(request);
}
/// <summary>Post this message.</summary>
///
/// <exception cref="NotFound"> Thrown when a not found error condition occurs.</exception>
/// <exception cref="HttpError">Thrown when a HTTP error error condition occurs.</exception>
///
/// <param name="request">.</param>
///
/// <returns>An object.</returns>
public virtual object Post(Auth request)
{
AssertAuthProviders();
if (ValidateFn != null)
{
var validationResponse = ValidateFn(this, HttpMethods.Get, request);
if (validationResponse != null) return validationResponse;
}
if (request.RememberMe.HasValue)
{
var opt = request.RememberMe.GetValueOrDefault(false)
? SessionOptions.Permanent
: SessionOptions.Temporary;
base.RequestContext.Get<IHttpResponse>()
.AddSessionOptions(base.RequestContext.Get<IHttpRequest>(), opt);
}
var provider = request.provider ?? AuthProviders[0].Provider;
var oAuthConfig = GetAuthProvider(provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
if (request.provider == LogoutAction)
return oAuthConfig.Logout(this, request);
var session = this.GetSession();
var isHtml = base.RequestContext.ResponseContentType.MatchesContentType(ContentType.Html);
try
{
var response = Authenticate(request, provider, session, oAuthConfig);
// The above Authenticate call may end an existing session and create a new one so we need
// to refresh the current session reference.
session = this.GetSession();
var referrerUrl = request.Continue
?? session.ReferrerUrl
?? this.RequestContext.GetHeader("Referer")
?? oAuthConfig.CallbackUrl;
var alreadyAuthenticated = response == null;
response = response ?? new AuthResponse {
UserName = session.UserAuthName,
SessionId = session.Id,
ReferrerUrl = referrerUrl,
};
if (isHtml)
{
if (alreadyAuthenticated)
return this.Redirect(referrerUrl.AddHashParam("s", "0"));
if (!(response is IHttpResult) && !String.IsNullOrEmpty(referrerUrl))
{
return new HttpResult(response) {
Location = referrerUrl
};
}
}
return response;
}
catch (HttpError ex)
{
var errorReferrerUrl = this.RequestContext.GetHeader("Referer");
if (isHtml && errorReferrerUrl != null)
{
errorReferrerUrl = errorReferrerUrl.SetQueryParam("error", ex.Message);
return HttpResult.Redirect(errorReferrerUrl);
}
throw;
}
}
/// <summary>
/// Public API entry point to authenticate via code
/// </summary>
/// <param name="request"></param>
/// <returns>null; if already autenticated otherwise a populated instance of AuthResponse</returns>
public virtual AuthResponse Authenticate(Auth request)
{
//Remove HTML Content-Type to avoid auth providers issuing browser re-directs
((HttpRequestContext)this.RequestContext).ResponseContentType = ContentType.PlainText;
var provider = request.provider ?? AuthProviders[0].Provider;
var oAuthConfig = GetAuthProvider(provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
if (request.provider == LogoutAction)
return oAuthConfig.Logout(this, request) as AuthResponse;
var result = Authenticate(request, provider, this.GetSession(), oAuthConfig);
var httpError = result as HttpError;
if (httpError != null)
throw httpError;
return result as AuthResponse;
}
/// <summary>
/// The specified <paramref name="session"/> may change as a side-effect of this method. If
/// subsequent code relies on current <see cref="IAuthSession"/> data be sure to reload
/// the session istance via <see cref="ServiceExtensions.GetSession(NServiceKit.ServiceInterface.IServiceBase,bool)"/>.
/// </summary>
private object Authenticate(Auth request, string provider, IAuthSession session, IAuthProvider oAuthConfig)
{
object response = null;
if (!oAuthConfig.IsAuthorized(session, session.GetOAuthTokens(provider), request))
{
response = oAuthConfig.Authenticate(this, session, request);
}
return response;
}
/// <summary>Deletes the given request.</summary>
///
/// <param name="request">.</param>
///
/// <returns>An object.</returns>
public virtual object Delete(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Delete, request);
if (response != null) return response;
}
this.RemoveSession();
return new AuthResponse();
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Point3D.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: 3D point implementation.
//
// See spec at http://avalon/medialayer/Specifications/Avalon3D%20API%20Spec.mht
//
// History:
// 06/02/2003 : t-gregr - Created
//
//---------------------------------------------------------------------------
using System.Windows;
using System.Windows.Media.Media3D;
using System;
namespace System.Windows.Media.Media3D
{
/// <summary>
/// Point3D - 3D point representation.
/// Defaults to (0,0,0).
/// </summary>
public partial struct Point3D
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor that sets point's initial values.
/// </summary>
/// <param name="x">Value of the X coordinate of the new point.</param>
/// <param name="y">Value of the Y coordinate of the new point.</param>
/// <param name="z">Value of the Z coordinate of the new point.</param>
public Point3D(double x, double y, double z)
{
_x = x;
_y = y;
_z = z;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Offset - update point position by adding offsetX to X, offsetY to Y, and offsetZ to Z.
/// </summary>
/// <param name="offsetX">Offset in the X direction.</param>
/// <param name="offsetY">Offset in the Y direction.</param>
/// <param name="offsetZ">Offset in the Z direction.</param>
public void Offset(double offsetX, double offsetY, double offsetZ)
{
_x += offsetX;
_y += offsetY;
_z += offsetZ;
}
/// <summary>
/// Point3D + Vector3D addition.
/// </summary>
/// <param name="point">Point being added.</param>
/// <param name="vector">Vector being added.</param>
/// <returns>Result of addition.</returns>
public static Point3D operator +(Point3D point, Vector3D vector)
{
return new Point3D(point._x + vector._x,
point._y + vector._y,
point._z + vector._z);
}
/// <summary>
/// Point3D + Vector3D addition.
/// </summary>
/// <param name="point">Point being added.</param>
/// <param name="vector">Vector being added.</param>
/// <returns>Result of addition.</returns>
public static Point3D Add(Point3D point, Vector3D vector)
{
return new Point3D(point._x + vector._x,
point._y + vector._y,
point._z + vector._z);
}
/// <summary>
/// Point3D - Vector3D subtraction.
/// </summary>
/// <param name="point">Point from which vector is being subtracted.</param>
/// <param name="vector">Vector being subtracted from the point.</param>
/// <returns>Result of subtraction.</returns>
public static Point3D operator -(Point3D point, Vector3D vector)
{
return new Point3D(point._x - vector._x,
point._y - vector._y,
point._z - vector._z);
}
/// <summary>
/// Point3D - Vector3D subtraction.
/// </summary>
/// <param name="point">Point from which vector is being subtracted.</param>
/// <param name="vector">Vector being subtracted from the point.</param>
/// <returns>Result of subtraction.</returns>
public static Point3D Subtract(Point3D point, Vector3D vector)
{
return new Point3D(point._x - vector._x,
point._y - vector._y,
point._z - vector._z);
}
/// <summary>
/// Subtraction.
/// </summary>
/// <param name="point1">Point from which we are subtracting the second point.</param>
/// <param name="point2">Point being subtracted.</param>
/// <returns>Vector between the two points.</returns>
public static Vector3D operator -(Point3D point1, Point3D point2)
{
return new Vector3D(point1._x - point2._x,
point1._y - point2._y,
point1._z - point2._z);
}
/// <summary>
/// Subtraction.
/// </summary>
/// <param name="point1">Point from which we are subtracting the second point.</param>
/// <param name="point2">Point being subtracted.</param>
/// <returns>Vector between the two points.</returns>
public static Vector3D Subtract(Point3D point1, Point3D point2)
{
Vector3D v = new Vector3D();
Subtract(ref point1, ref point2, out v);
return v;
}
/// <summary>
/// Faster internal version of Subtract that avoids copies
///
/// p1 and p2 to a passed by ref for perf and ARE NOT MODIFIED
/// </summary>
internal static void Subtract(ref Point3D p1, ref Point3D p2, out Vector3D result)
{
result._x = p1._x - p2._x;
result._y = p1._y - p2._y;
result._z = p1._z - p2._z;
}
/// <summary>
/// Point3D * Matrix3D multiplication.
/// </summary>
/// <param name="point">Point being transformed.</param>
/// <param name="matrix">Transformation matrix applied to the point.</param>
/// <returns>Result of the transformation matrix applied to the point.</returns>
public static Point3D operator *(Point3D point, Matrix3D matrix)
{
return matrix.Transform(point);
}
/// <summary>
/// Point3D * Matrix3D multiplication.
/// </summary>
/// <param name="point">Point being transformed.</param>
/// <param name="matrix">Transformation matrix applied to the point.</param>
/// <returns>Result of the transformation matrix applied to the point.</returns>
public static Point3D Multiply(Point3D point, Matrix3D matrix)
{
return matrix.Transform(point);
}
/// <summary>
/// Explicit conversion to Vector3D.
/// </summary>
/// <param name="point">Given point.</param>
/// <returns>Vector representing the point.</returns>
public static explicit operator Vector3D(Point3D point)
{
return new Vector3D(point._x, point._y, point._z);
}
/// <summary>
/// Explicit conversion to Point4D.
/// </summary>
/// <param name="point">Given point.</param>
/// <returns>4D point representing the 3D point.</returns>
public static explicit operator Point4D(Point3D point)
{
return new Point4D(point._x, point._y, point._z, 1.0);
}
#endregion Public Methods
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 5/19/2009 10:51:27 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// The pattern can act as both the base class for specific types of pattern as well as a wrapper class that allows
/// for an enumerated constructor that makes it easier to figure out what kinds of patterns can be created.
/// </summary>
public class Pattern : Descriptor, IPattern
{
#region IPattern Members
/// <summary>
/// Fires the item changed event
/// </summary>
public event EventHandler ItemChanged;
/// <summary>
/// Not Used
/// </summary>
public event EventHandler RemoveItem;
#endregion
#region Private Variables
private RectangleF _bounds;
private IPattern _innerPattern;
private ILineSymbolizer _outline;
private PatternType _patternType;
private bool _useOutline;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Pattern
/// </summary>
public Pattern()
{
_outline = new LineSymbolizer();
_outline.ItemChanged += OutlineItemChanged;
_useOutline = true;
}
/// <summary>
/// Creates a new pattern with the specified type
/// </summary>
/// <param name="type">The subclass of pattern to use as the internal pattern</param>
public Pattern(PatternType type)
{
SetType(type);
}
private void OutlineItemChanged(object sender, EventArgs e)
{
OnItemChanged();
}
#endregion
#region Methods
/// <summary>
/// Gets or sets the rectangular bounds. This controls how the gradient is drawn, and
/// should be set to the envelope of the entire layer being drawn
/// </summary>
public RectangleF Bounds
{
get { return _bounds; }
set { _bounds = value; }
}
/// <summary>
/// Gets a color that can be used to represent this pattern. In some cases, a color is not
/// possible, in which case, this returns Gray.
/// </summary>
/// <returns>A single System.Color that can be used to represent this pattern.</returns>
public virtual Color GetFillColor()
{
return Color.Gray;
}
/// <summary>
/// Sets the color that will attempt to be applied to the top pattern. If the pattern is
/// not colorable, this does nothing.
/// </summary>
public virtual void SetFillColor(Color color)
{
// Overridden in child classes
}
/// <summary>
/// Copies the properties defining the outline from the specified source onto this pattern.
/// </summary>
/// <param name="source">The source pattern to copy outline properties from.</param>
public void CopyOutline(IPattern source)
{
if (_innerPattern != null)
{
_innerPattern.CopyOutline(source);
return;
}
_outline = source.Outline.Copy();
_useOutline = source.UseOutline;
}
/// <summary>
/// Fills the specified graphics path with the pattern specified by this object
/// </summary>
/// <param name="g">The Graphics device to draw to</param>
/// <param name="gp">The GraphicsPath that describes the closed shape to fill</param>
public virtual void FillPath(Graphics g, GraphicsPath gp)
{
if (_innerPattern != null)
{
_innerPattern.FillPath(g, gp);
}
// Does nothing by default, and must be handled in sub-classes
}
/// <summary>
/// Draws the borders for this graphics path by sequentially drawing all
/// the strokes in the border symbolizer
/// </summary>
/// <param name="g">The Graphics device to draw to </param>
/// <param name="gp">The GraphicsPath that describes the outline to draw</param>
/// <param name="scaleWidth">The scaleWidth to use for scaling the line width </param>
public virtual void DrawPath(Graphics g, GraphicsPath gp, double scaleWidth)
{
if (_innerPattern != null)
{
_innerPattern.DrawPath(g, gp, scaleWidth);
return;
}
if (_useOutline && _outline != null)
{
_outline.DrawPath(g, gp, scaleWidth);
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the ILineSymbolizer that describes the outline symbology for this pattern.
/// </summary>
/// <remarks>
/// [TypeConverter(typeof(GeneralTypeConverter))]
/// [Editor(typeof(LineSymbolizerEditor), typeof(UITypeEditor))]
/// </remarks>
[Description("Gets or sets the ILineSymbolizer that describes the outline symbology for this pattern.")]
[Serialize("Outline")]
public ILineSymbolizer Outline
{
get
{
return _innerPattern != null ? _innerPattern.Outline : _outline;
}
set
{
if (_innerPattern != null) _innerPattern.Outline = value;
_outline = value;
}
}
/// <summary>
/// Gets or sets the pattern type. Setting this
/// </summary>
[Serialize("PatternType")]
public PatternType PatternType
{
get
{
if (_innerPattern != null) return _innerPattern.PatternType;
return _patternType;
}
set
{
// Sub-classes will have a null inner pattern that is defined by setting this.
if (_innerPattern == null)
{
_patternType = value;
return;
}
// When behaving as a wrapper, the inner pattern should be something other than null.
SetType(value);
}
}
/// <summary>
/// Gets or sets a boolean indicating whether or not the pattern should use the outline symbolizer.
/// </summary>
[Serialize("UseOutline")]
public bool UseOutline
{
get
{
if (_innerPattern != null) return _innerPattern.UseOutline;
return _useOutline;
}
set
{
if (_innerPattern != null)
{
_innerPattern.UseOutline = value;
return;
}
_useOutline = value;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Occurs when the item is changed
/// </summary>
protected virtual void OnItemChanged()
{
if (ItemChanged != null) ItemChanged(this, EventArgs.Empty);
}
/// <summary>
/// This is not currently used, but technically should cause the list of patterns to remove this pattern.
/// </summary>
protected virtual void OnRemoveItem()
{
if (RemoveItem != null) RemoveItem(this, EventArgs.Empty);
}
#endregion
#region Private Functions
private void SetType(PatternType type)
{
_patternType = type;
IPattern result = null;
switch (type)
{
case PatternType.Gradient:
result = new GradientPattern();
break;
case PatternType.Line:
break;
case PatternType.Marker:
break;
case PatternType.Picture:
result = new PicturePattern();
break;
case PatternType.Simple:
result = new SimplePattern();
break;
}
if (result != null) result.Outline = _innerPattern.Outline;
_innerPattern = result;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Security.Cryptography;
using Epi;
using Epi.Collections;
using Epi.DataSets;
using Epi.Resources;
namespace Epi
{
/// <summary>
/// Encapsulates all global information that persists in the config file.
/// </summary>
public partial class Configuration
{
private string configFilePath;
private DataSets.Config configDataSet;
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="configFilePath">Configuration file path.</param>
/// <param name="configDataSet">Configuration data.</param>
public Configuration(string configFilePath, DataSets.Config configDataSet)
{
this.configDataSet = configDataSet;
this.configFilePath = configFilePath;
}
#endregion Constructors
#region Public Constants
/// <summary>
/// Version of the current configuration schema. Used to spot schema differences.
/// </summary>
public const int CurrentSchemaVersion = 117;
#endregion
#region Public Properties
/// <summary>
/// Gets configuration file path.
/// </summary>
public string ConfigFilePath
{
get { return configFilePath; }
}
/// <summary>
/// Gets configuration settings
/// </summary>
public Config.SettingsRow Settings
{
get
{
return configDataSet.Settings[0];
}
}
/// <summary>
/// Gets the text encryption module
/// </summary>
public Config.TextEncryptionModuleRow TextEncryptionModule
{
get
{
if (configDataSet.TextEncryptionModule == null || configDataSet.TextEncryptionModule.Count == 0)
{
return null;
}
else
{
return configDataSet.TextEncryptionModule[0];
}
}
}
/// <summary>
/// Gets the file encryption module
/// </summary>
public Config.FileEncryptionModuleRow FileEncryptionModule
{
get
{
if (configDataSet.FileEncryptionModule == null || configDataSet.FileEncryptionModule.Count == 0)
{
return null;
}
else
{
return configDataSet.FileEncryptionModule[0];
}
}
}
/// <summary>
/// Return configuration version information
/// </summary>
public Config.VersionRow Version
{
get
{
return configDataSet.Version[0];
}
}
/// <summary>
/// Gets/sets the full path of the current project file.
/// </summary>
public string CurrentProjectFilePath
{
get
{
return ParentRowRecentProjects.CurrentProjectLocation ?? string.Empty;
}
set
{
ParentRowRecentProjects.CurrentProjectLocation = value;
//Save();
}
}
/// <summary>
/// Gets a datatable for recent projects
/// </summary>
public Config.RecentProjectDataTable RecentProjects
{
get
{
return configDataSet.RecentProject;
}
}
/// <summary>
/// Gets a datatable for recent views
/// </summary>
public Config.RecentViewDataTable RecentViews
{
get
{
return configDataSet.RecentView;
}
}
/// <summary>
/// Gets a datatable for recent views
/// </summary>
public Config.RecentDataSourceDataTable RecentDataSources
{
get
{
return configDataSet.RecentDataSource;
}
}
/// <summary>
/// Gets a datatable for recent organizations
/// </summary>
public Config.RecentOrganizationDataTable RecentOrganization
{
get
{
return configDataSet.RecentOrganization;
}
}
/// <summary>
/// Gets a datatable for data drivers
/// </summary>
public Config.DataDriverDataTable DataDrivers
{
get
{
return configDataSet.DataDriver;
}
}
/// <summary>
/// Gets a datatable for gadgets
/// </summary>
public Config.GadgetsDataTable Gadgets
{
get
{
return configDataSet.Gadgets;
}
}
/// <summary>
/// Gets a datatable for a gadget
/// </summary>
public Config.GadgetDataTable Gadget
{
get
{
return configDataSet.Gadget;
}
}
/// <summary>
/// Gets a datatable for file connections
/// </summary>
public Config.FileDataTable FileConnections
{
get
{
return configDataSet.File;
}
}
/// <summary>
/// Gets a datatable for data connections
/// </summary>
public Config.DatabaseDataTable DatabaseConnections
{
get
{
return configDataSet.Database;
}
}
/// <summary>
/// Gets a datatable for directories
/// </summary>
public Config.DirectoriesRow Directories
{
get
{
return configDataSet.Directories[0];
}
}
/// <summary>
/// Gets the collection of permanent variables
/// If the in-memory collection is null, it loads them from persistence.
/// </summary>
public Config.PermanentVariableDataTable PermanentVariables
{
get
{
return ConfigDataSet.PermanentVariable;
}
}
/// <summary>
/// Gets the collection of installed Epi Info modules
/// </summary>
public Config.ModuleDataTable Modules
{
get
{
return configDataSet.Module;
}
}
/// <summary>
/// Gets the internal config dataset
/// </summary>
public DataSets.Config ConfigDataSet
{
get
{
return configDataSet;
}
}
/// <summary>
/// Gets the row from config typed dataset containing the parent row for module rows
/// </summary>
public Config.ModulesRow ParentRowModules
{
get
{
if (configDataSet.Modules.Count < 1)
{
Config.ModulesRow newrow = configDataSet.Modules.NewModulesRow();
ConfigDataSet.Modules.Rows.Add(newrow);
}
return configDataSet.Modules[0];
}
}
/// <summary>
/// Parent row for connection rows
/// </summary>
public Config.ConnectionsRow ParentRowConnections
{
get
{
if (configDataSet.Projects.Count < 1)
{
Config.ConnectionsRow newrow = configDataSet.Connections.NewConnectionsRow();
ConfigDataSet.Connections.Rows.Add(newrow);
}
return configDataSet.Connections[0];
}
}
/// <summary>
/// Parent row for project rows
/// </summary>
public Config.ProjectsRow ParentRowRecentProjects
{
get
{
if (configDataSet.Projects.Count < 1)
{
Config.ProjectsRow newrow = configDataSet.Projects.NewProjectsRow();
newrow.CurrentProjectLocation = string.Empty;
ConfigDataSet.Projects.Rows.Add(newrow);
}
return configDataSet.Projects[0];
}
}
public static void AddNewDataDrivers()
{
try
{
AssertConfigurationLoaded();
Configuration defaultConfig = Configuration.CreateDefaultConfiguration();
current.configDataSet.DataDriver.Clear();
foreach (Epi.DataSets.Config.DataDriverRow row in defaultConfig.DataDrivers)
{
current.configDataSet.DataDriver.ImportRow(row);
}
current.configDataSet.DataDriver.AcceptChanges();
Save();
}
catch { }
}
/// <summary>
/// Parent row for gadgets
/// </summary>
public Config.GadgetsRow ParentRowGadgets
{
get
{
if (configDataSet.Gadgets.Count < 1)
{
Config.GadgetsRow newrow = configDataSet.Gadgets.NewGadgetsRow();
ConfigDataSet.Gadgets.Rows.Add(newrow);
}
return configDataSet.Gadgets[0];
}
}
/// <summary>
/// Parent row for recent view rows
/// </summary>
public Config.ViewsRow ParentRowRecentViews
{
get
{
if (configDataSet.Views.Count < 1)
{
Config.ViewsRow newrow = configDataSet.Views.NewViewsRow();
ConfigDataSet.Views.Rows.Add(newrow);
}
return configDataSet.Views[0];
}
}
/// <summary>
/// Parent row for project rows
/// </summary>
public Config.DataSourcesRow ParentRowRecentDataSources
{
get
{
if (configDataSet.DataSources.Count < 1)
{
Config.DataSourcesRow newrow = configDataSet.DataSources.NewDataSourcesRow();
ConfigDataSet.DataSources.Rows.Add(newrow);
}
return configDataSet.DataSources[0];
}
}
/// <summary>
/// Parent row for permanent vairables
/// </summary>
public Config.VariablesRow ParentRowPermanentVariables
{
get
{
if (configDataSet.Variables.Count < 1)
{
Config.VariablesRow newrow = configDataSet.Variables.NewVariablesRow();
ConfigDataSet.Variables.Rows.Add(newrow);
}
return configDataSet.Variables[0];
}
}
#endregion Public Properties
}//end class
}//end namespace
| |
using System;
using System.Collections.Generic;
using System.Text;
#if !FRB_MDX
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
#endif
using FlatRedBall.IO;
using FlatRedBall.Utilities;
namespace FlatRedBall.Graphics.Animation
{
#region XML Docs
/// <summary>
/// Represents a collection of AnimationFrames which can be used to perform
/// texture flipping animation on IAnimationChainAnimatables such as Sprites.
/// </summary>
#endregion
public partial class AnimationChain : List<AnimationFrame>, INameable, IEquatable<AnimationChain>
{
#region Fields
private string mName;
//private string mParentFileName;
internal int mIndexInLoadedAchx = -1;
#endregion
#region Properties
#region XML Docs
/// <summary>
/// Sets the frameTime of each AnimationFrame in the AnimationChain to the passed value.
/// </summary>
#endregion
public float FrameTime
{
set
{
foreach (AnimationFrame frame in this)
frame.FrameLength = value;
}
}
public int IndexInLoadedAchx
{
get { return mIndexInLoadedAchx; }
}
#region XML Docs
/// <summary>
/// Gets the last AnimationFrame of the AnimationChain or null if
/// there are no AnimationFrames.
/// </summary>
#endregion
public AnimationFrame LastFrame
{
get
{
if (this.Count == 0)
{
return null;
}
else
{
return this[this.Count - 1];
}
}
}
#region XML Docs
/// <summary>
/// The name of the AnimationChain.
/// </summary>
#endregion
public string Name
{
get { return mName; }
set { mName = value; }
}
private string mParentAchxFileName;
public string ParentAchxFileName
{
get { return mParentAchxFileName; }
set { mParentAchxFileName = value; }
}
private string mParentGifFileName;
public string ParentGifFileName
{
get { return mParentGifFileName; }
set { mParentGifFileName = value; }
}
#region XML Docs
/// <summary>
/// Returns the sum of the FrameLengths of all contained AnimationFrames.
/// </summary>
#endregion
public float TotalLength
{
get
{
float sum = 0;
for (int i = 0; i < this.Count; i++)
{
AnimationFrame af = this[i];
sum += af.FrameLength;
}
return sum;
}
}
#endregion
#region Methods
#region Constructors
#region XML Docs
/// <summary>
/// Creates an empty AnimationChain.
/// </summary>
#endregion
public AnimationChain()
: base()
{ }
#region XML Docs
/// <summary>
/// Creates a new AnimationChain with the argument capacity.
/// </summary>
/// <param name="capacity">Sets the initial capacity. Used to reduce memory allocation.</param>
#endregion
public AnimationChain(int capacity)
: base(capacity)
{ }
#endregion
#region Public Methods
public AnimationChain Clone()
{
AnimationChain animationChain = new AnimationChain();
foreach (AnimationFrame animationFrame in this)
{
animationChain.Add(animationFrame.Clone());
}
animationChain.ParentGifFileName = ParentGifFileName;
animationChain.ParentAchxFileName = ParentAchxFileName;
animationChain.mIndexInLoadedAchx = mIndexInLoadedAchx;
animationChain.mName = this.mName;
return animationChain;
}
#region XML Docs
/// <summary>
/// Searches for and returns the AnimationFrame with its Name matching
/// the nameToSearchFor argument, or null if none are found.
/// </summary>
/// <param name="nameToSearchFor">The name of the AnimationFrame to search for.</param>
/// <returns>The AnimationFrame with matching name, or null if none exists.</returns>
#endregion
public AnimationFrame FindByName(string nameToSearchFor)
{
for (int i = 0; i < this.Count; i++)
{
AnimationFrame af = this[i];
if (af.Texture.Name == nameToSearchFor)
return af;
}
return null;
}
#region XML Docs
/// <summary>
/// Returns the shortest absolute number of frames between the two argument frame numbers. This
/// method moves forward and backward and considers looping.
/// </summary>
/// <param name="frame1">The index of the first frame.</param>
/// <param name="frame2">The index of the second frame.</param>
/// <returns>The positive or negative number of frames between the two arguments.</returns>
#endregion
public int FrameToFrame(int frame1, int frame2)
{
int difference = frame2 - frame1;
if (difference > this.Count / 2.0)
difference -= this.Count;
else if (difference < -this.Count / 2.0)
difference += this.Count;
return difference;
}
public void ReplaceTexture(Texture2D oldTexture, Texture2D newTexture)
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Texture == oldTexture)
{
this[i].Texture = newTexture;
this[i].TextureName = newTexture.Name;
}
}
}
public override string ToString()
{
return Name + " (" + Count + ")";
}
#endregion
#endregion
#region IEquatable<AnimationChain> Members
bool IEquatable<AnimationChain>.Equals(AnimationChain other)
{
return this == other;
}
#endregion
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_186 : MapLoop
{
public M_186() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LTR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new L_ACT(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
//1000
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//2000
public class L_ACT : MapLoop
{
public L_ACT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ACT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
}
//2050
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_NM1_1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_BOR(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
}
//2075
public class L_NM1_1 : MapLoop
{
public L_NM1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new AM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DMA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2100
public class L_BOR : MapLoop
{
public L_BOR(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BOR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_SPK(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_LTR(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_UC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_UD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2150
public class L_NM1_2 : MapLoop
{
public L_NM1_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2200
public class L_SPK : MapLoop
{
public L_SPK(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SPK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CD2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NM1_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2250
public class L_NM1_3 : MapLoop
{
public L_NM1_3(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2300
public class L_LTR : MapLoop
{
public L_LTR(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LTR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CD2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2350
public class L_UC : MapLoop
{
public L_UC(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new UC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_HL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2400
public class L_HL : MapLoop
{
public L_HL(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new UQS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DMA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new EC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new IN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new EMS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new ASL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new TOA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TOV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new III() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UCS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new FH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CDS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CED() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_EFI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2450
public class L_EFI : MapLoop
{
public L_EFI(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2500
public class L_UD : MapLoop
{
public L_UD(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new UD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_EFI_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2550
public class L_EFI_1 : MapLoop
{
public L_EFI_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
// 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.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal class Stylesheet
{
private readonly ArrayList _imports = new ArrayList();
private Hashtable _modeManagers;
private readonly Hashtable _templateNameTable = new Hashtable();
private Hashtable _attributeSetTable;
private int _templateCount;
//private ArrayList preserveSpace;
private Hashtable _queryKeyTable;
private ArrayList _whitespaceList;
private bool _whitespace;
private readonly Hashtable _scriptObjectTypes = new Hashtable();
private TemplateManager _templates;
private class WhitespaceElement
{
private readonly int _key;
private readonly double _priority;
private bool _preserveSpace;
internal double Priority
{
get { return _priority; }
}
internal int Key
{
get { return _key; }
}
internal bool PreserveSpace
{
get { return _preserveSpace; }
}
internal WhitespaceElement(int Key, double priority, bool PreserveSpace)
{
_key = Key;
_priority = priority;
_preserveSpace = PreserveSpace;
}
internal void ReplaceValue(bool PreserveSpace)
{
_preserveSpace = PreserveSpace;
}
}
internal bool Whitespace { get { return _whitespace; } }
internal ArrayList Imports { get { return _imports; } }
internal Hashtable AttributeSetTable { get { return _attributeSetTable; } }
internal void AddSpace(Compiler compiler, string query, double Priority, bool PreserveSpace)
{
WhitespaceElement elem;
if (_queryKeyTable != null)
{
if (_queryKeyTable.Contains(query))
{
elem = (WhitespaceElement)_queryKeyTable[query];
elem.ReplaceValue(PreserveSpace);
return;
}
}
else
{
_queryKeyTable = new Hashtable();
_whitespaceList = new ArrayList();
}
int key = compiler.AddQuery(query);
elem = new WhitespaceElement(key, Priority, PreserveSpace);
_queryKeyTable[query] = elem;
_whitespaceList.Add(elem);
}
internal void SortWhiteSpace()
{
if (_queryKeyTable != null)
{
for (int i = 0; i < _whitespaceList.Count; i++)
{
for (int j = _whitespaceList.Count - 1; j > i; j--)
{
WhitespaceElement elem1, elem2;
elem1 = (WhitespaceElement)_whitespaceList[j - 1];
elem2 = (WhitespaceElement)_whitespaceList[j];
if (elem2.Priority < elem1.Priority)
{
_whitespaceList[j - 1] = elem2;
_whitespaceList[j] = elem1;
}
}
}
_whitespace = true;
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
if (stylesheet.Whitespace)
{
stylesheet.SortWhiteSpace();
_whitespace = true;
}
}
}
}
internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node)
{
// last one should win. I.E. We starting from the end. I.E. Lowest priority should go first
if (_whitespaceList != null)
{
for (int i = _whitespaceList.Count - 1; 0 <= i; i--)
{
WhitespaceElement elem = (WhitespaceElement)_whitespaceList[i];
if (proc.Matches(node, elem.Key))
{
return elem.PreserveSpace;
}
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
if (!stylesheet.PreserveWhiteSpace(proc, node))
return false;
}
}
return true;
}
internal void AddAttributeSet(AttributeSetAction attributeSet)
{
Debug.Assert(attributeSet.Name != null);
if (_attributeSetTable == null)
{
_attributeSetTable = new Hashtable();
}
Debug.Assert(_attributeSetTable != null);
if (_attributeSetTable.ContainsKey(attributeSet.Name) == false)
{
_attributeSetTable[attributeSet.Name] = attributeSet;
}
else
{
// merge the attribute-sets
((AttributeSetAction)_attributeSetTable[attributeSet.Name]).Merge(attributeSet);
}
}
internal void AddTemplate(TemplateAction template)
{
XmlQualifiedName mode = template.Mode;
//
// Ensure template has a unique name
//
Debug.Assert(_templateNameTable != null);
if (template.Name != null)
{
if (_templateNameTable.ContainsKey(template.Name) == false)
{
_templateNameTable[template.Name] = template;
}
else
{
throw XsltException.Create(SR.Xslt_DupTemplateName, template.Name.ToString());
}
}
if (template.MatchKey != Compiler.InvalidQueryKey)
{
if (_modeManagers == null)
{
_modeManagers = new Hashtable();
}
Debug.Assert(_modeManagers != null);
if (mode == null)
{
mode = XmlQualifiedName.Empty;
}
TemplateManager manager = (TemplateManager)_modeManagers[mode];
if (manager == null)
{
manager = new TemplateManager(this, mode);
_modeManagers[mode] = manager;
if (mode.IsEmpty)
{
Debug.Assert(_templates == null);
_templates = manager;
}
}
Debug.Assert(manager != null);
template.TemplateId = ++_templateCount;
manager.AddTemplate(template);
}
}
internal void ProcessTemplates()
{
if (_modeManagers != null)
{
IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator();
while (enumerator.MoveNext())
{
Debug.Assert(enumerator.Value is TemplateManager);
TemplateManager manager = (TemplateManager)enumerator.Value;
manager.ProcessTemplates();
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Process templates in imported stylesheet
//
stylesheet.ProcessTemplates();
}
}
}
internal void ReplaceNamespaceAlias(Compiler compiler)
{
if (_modeManagers != null)
{
IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator();
while (enumerator.MoveNext())
{
TemplateManager manager = (TemplateManager)enumerator.Value;
if (manager.templates != null)
{
for (int i = 0; i < manager.templates.Count; i++)
{
TemplateAction template = (TemplateAction)manager.templates[i];
template.ReplaceNamespaceAlias(compiler);
}
}
}
}
if (_templateNameTable != null)
{
IDictionaryEnumerator enumerator = _templateNameTable.GetEnumerator();
while (enumerator.MoveNext())
{
TemplateAction template = (TemplateAction)enumerator.Value;
template.ReplaceNamespaceAlias(compiler);
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
stylesheet.ReplaceNamespaceAlias(compiler);
}
}
}
internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator, XmlQualifiedName mode)
{
Debug.Assert(processor != null && navigator != null);
Debug.Assert(mode != null);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_modeManagers != null)
{
TemplateManager manager = (TemplateManager)_modeManagers[mode];
if (manager != null)
{
Debug.Assert(manager.Mode.Equals(mode));
action = manager.FindTemplate(processor, navigator);
}
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null)
{
action = FindTemplateImports(processor, navigator, mode);
}
return action;
}
internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode)
{
TemplateAction action = null;
//
// Do we have imported stylesheets?
//
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(processor, navigator, mode);
if (action != null)
{
return action;
}
}
}
return action;
}
internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator)
{
Debug.Assert(processor != null && navigator != null);
Debug.Assert(_templates == null && _modeManagers == null || _templates == _modeManagers[XmlQualifiedName.Empty]);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_templates != null)
{
action = _templates.FindTemplate(processor, navigator);
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null)
{
action = FindTemplateImports(processor, navigator);
}
return action;
}
internal TemplateAction FindTemplate(XmlQualifiedName name)
{
//Debug.Assert(this.templateNameTable == null);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_templateNameTable != null)
{
action = (TemplateAction)_templateNameTable[name];
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null && _imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(name);
if (action != null)
{
return action;
}
}
}
return action;
}
internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator)
{
TemplateAction action = null;
//
// Do we have imported stylesheets?
//
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(processor, navigator);
if (action != null)
{
return action;
}
}
}
return action;
}
internal Hashtable ScriptObjectTypes
{
get { return _scriptObjectTypes; }
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DotNetNuke.Services.GeneratedImage.ImageQuantization
{
/// <summary>
/// Abstarct class for Quantizers
/// </summary>
public abstract class Quantizer
{
/// <summary>
/// Construct the quantizer
/// </summary>
/// <param name="singlePass">If true, the quantization only needs to loop through the source pixels once</param>
/// <remarks>
/// If you construct this class with a true value for singlePass, then the code will, when quantizing your image,
/// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage'
/// and then 'QuantizeImage'.
/// </remarks>
public Quantizer(bool singlePass)
{
_singlePass = singlePass;
_pixelSize = Marshal.SizeOf(typeof (Color32));
}
/// <summary>
/// Quantize an image and return the resulting output bitmap
/// </summary>
/// <param name="source">The image to quantize</param>
/// <returns>A quantized version of the image</returns>
public Bitmap Quantize(Image source)
{
// Get the size of the source image
int height = source.Height;
int width = source.Width;
// And construct a rectangle from these dimensions
Rectangle bounds = new Rectangle(0, 0, width, height);
// First off take a 32bpp copy of the image
Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppArgb);
// And construct an 8bpp version
Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
// Now lock the bitmap into memory
using (Graphics g = Graphics.FromImage(copy))
{
g.PageUnit = GraphicsUnit.Pixel;
// Draw the source image onto the copy bitmap,
// which will effect a widening as appropriate.
g.DrawImage(source, bounds);
}
// Define a pointer to the bitmap data
BitmapData sourceData = null;
try
{
// Get the source image bits and lock into memory
sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Call the FirstPass function if not a single pass algorithm.
// For something like an octree quantizer, this will run through
// all image pixels, build a data structure, and create a palette.
if (!_singlePass)
FirstPass(sourceData, width, height);
// Then set the color palette on the output bitmap. I'm passing in the current palette
// as there's no way to construct a new, empty palette.
output.Palette = GetPalette(output.Palette);
// Then call the second pass which actually does the conversion
SecondPass(sourceData, output, width, height, bounds);
}
finally
{
// Ensure that the bits are unlocked
copy.UnlockBits(sourceData);
}
// Last but not least, return the output bitmap
return output;
}
/// <summary>
/// Execute the first pass through the pixels in the image
/// </summary>
/// <param name="sourceData">The source data</param>
/// <param name="width">The width in pixels of the image</param>
/// <param name="height">The height in pixels of the image</param>
protected virtual void FirstPass(BitmapData sourceData, int width, int height)
{
// Define the source data pointers. The source row is a byte to
// keep addition of the stride value easier (as this is in bytes)
IntPtr pSourceRow = sourceData.Scan0;
// Loop through each row
for (int row = 0; row < height; row++)
{
// Set the source pixel to the first pixel in this row
IntPtr pSourcePixel = pSourceRow;
// And loop through each column
for (int col = 0; col < width; col++)
{
InitialQuantizePixel(new Color32(pSourcePixel));
pSourcePixel = (IntPtr)((Int64)pSourcePixel + _pixelSize);
} // Now I have the pixel, call the FirstPassQuantize function...
// Add the stride to the source row
pSourceRow = (IntPtr)((long)pSourceRow + sourceData.Stride);
}
}
/// <summary>
/// Execute a second pass through the bitmap
/// </summary>
/// <param name="sourceData">The source bitmap, locked into memory</param>
/// <param name="output">The output bitmap</param>
/// <param name="width">The width in pixels of the image</param>
/// <param name="height">The height in pixels of the image</param>
/// <param name="bounds">The bounding rectangle</param>
protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds)
{
BitmapData outputData = null;
try
{
// Lock the output bitmap into memory
outputData = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
// Define the source data pointers. The source row is a byte to
// keep addition of the stride value easier (as this is in bytes)
IntPtr pSourceRow = sourceData.Scan0;
IntPtr pSourcePixel = pSourceRow;
IntPtr pPreviousPixel = pSourcePixel;
// Now define the destination data pointers
IntPtr pDestinationRow = outputData.Scan0;
IntPtr pDestinationPixel = pDestinationRow;
// And convert the first pixel, so that I have values going into the loop
byte pixelValue = QuantizePixel(new Color32(pSourcePixel));
// Assign the value of the first pixel
Marshal.WriteByte(pDestinationPixel, pixelValue);
// Loop through each row
for (int row = 0; row < height; row++)
{
// Set the source pixel to the first pixel in this row
pSourcePixel = pSourceRow;
// And set the destination pixel pointer to the first pixel in the row
pDestinationPixel = pDestinationRow;
// Loop through each pixel on this scan line
for (int col = 0; col < width; col++)
{
// Check if this is the same as the last pixel. If so use that value
// rather than calculating it again. This is an inexpensive optimisation.
if (Marshal.ReadByte(pPreviousPixel) != Marshal.ReadByte(pSourcePixel))
{
// Quantize the pixel
pixelValue = QuantizePixel(new Color32(pSourcePixel));
// And setup the previous pointer
pPreviousPixel = pSourcePixel;
}
// And set the pixel in the output
Marshal.WriteByte(pDestinationPixel, pixelValue);
pSourcePixel = (IntPtr)((long)pSourcePixel + _pixelSize);
pDestinationPixel = (IntPtr)((long)pDestinationPixel + 1);
}
// Add the stride to the source row
pSourceRow = (IntPtr)((long)pSourceRow + sourceData.Stride);
// And to the destination row
pDestinationRow = (IntPtr)((long)pDestinationRow + outputData.Stride);
}
}
finally
{
// Ensure that I unlock the output bits
output.UnlockBits(outputData);
}
}
/// <summary>
/// Override this to process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected virtual void InitialQuantizePixel(Color32 pixel)
{
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected abstract byte QuantizePixel(Color32 pixel);
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected abstract ColorPalette GetPalette(ColorPalette original);
/// <summary>
/// Flag used to indicate whether a single pass or two passes are needed for quantization.
/// </summary>
private bool _singlePass;
private int _pixelSize;
/// <summary>
/// Struct that defines a 32 bpp colour
/// </summary>
/// <remarks>
/// This struct is used to read data from a 32 bits per pixel image
/// in memory, and is ordered in this manner as this is the way that
/// the data is layed out in memory
/// </remarks>
[StructLayout(LayoutKind.Explicit)]
public struct Color32
{
public Color32(IntPtr pSourcePixel)
{
this = (Color32) Marshal.PtrToStructure(pSourcePixel, typeof(Color32));
}
/// <summary>
/// Holds the blue component of the colour
/// </summary>
[FieldOffset(0)]
public byte Blue;
/// <summary>
/// Holds the green component of the colour
/// </summary>
[FieldOffset(1)]
public byte Green;
/// <summary>
/// Holds the red component of the colour
/// </summary>
[FieldOffset(2)]
public byte Red;
/// <summary>
/// Holds the alpha component of the colour
/// </summary>
[FieldOffset(3)]
public byte Alpha;
/// <summary>
/// Permits the color32 to be treated as an int32
/// </summary>
[FieldOffset(0)]
public int ARGB;
/// <summary>
/// Return the color for this Color32 object
/// </summary>
public Color Color
{
get { return Color.FromArgb(Alpha, Red, Green, Blue); }
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using Aurora.Framework.Servers.HttpServer;
using OpenMetaverse.StructuredData;
using OpenSim.Services.Interfaces;
using RegionFlags = OpenMetaverse.RegionFlags;
namespace Aurora.Modules.Estate
{
public class EstateManagementModule : IEstateModule
{
private delegate void LookupUUIDS(List<UUID> uuidLst);
private IScene m_scene;
private EstateTerrainXferHandler TerrainUploader;
public event ChangeDelegate OnRegionInfoChange;
public event ChangeDelegate OnEstateInfoChange;
public event MessageDelegate OnEstateMessage;
#region Packet Data Responders
private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
uint sun = 0;
if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime)
sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800;
UUID estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
//if (m_scene.Permissions.IsGod(remote_client.AgentId))
// estateOwner = remote_client.AgentId;
remote_client.SendDetailedEstateData(invoice,
m_scene.RegionInfo.EstateSettings.EstateName,
m_scene.RegionInfo.EstateSettings.EstateID,
m_scene.RegionInfo.EstateSettings.ParentEstateID,
GetEstateFlags(),
sun,
m_scene.RegionInfo.RegionSettings.Covenant,
m_scene.RegionInfo.RegionSettings.CovenantLastUpdated,
m_scene.RegionInfo.EstateSettings.AbuseEmail,
estateOwner);
remote_client.SendEstateList(invoice,
(int)EstateTools.EstateAccessReplyDelta.EstateManagers,
m_scene.RegionInfo.EstateSettings.EstateManagers,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)EstateTools.EstateAccessReplyDelta.AllowedUsers,
m_scene.RegionInfo.EstateSettings.EstateAccess,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)EstateTools.EstateAccessReplyDelta.AllowedGroups,
m_scene.RegionInfo.EstateSettings.EstateGroups,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice,
m_scene.RegionInfo.EstateSettings.EstateBans,
m_scene.RegionInfo.EstateSettings.EstateID);
}
private void estateSetRegionInfoHandler(IClientAPI remoteClient, bool blockTerraform, bool noFly, bool allowDamage, bool AllowLandResell, int maxAgents, float objectBonusFactor,
int matureLevel, bool restrictPushObject, bool allowParcelChanges)
{
m_scene.RegionInfo.RegionSettings.BlockTerraform = blockTerraform;
m_scene.RegionInfo.RegionSettings.BlockFly = noFly;
m_scene.RegionInfo.RegionSettings.AllowDamage = allowDamage;
m_scene.RegionInfo.RegionSettings.RestrictPushing = restrictPushObject;
m_scene.RegionInfo.RegionSettings.AllowLandResell = AllowLandResell;
m_scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents;
m_scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor;
if (matureLevel <= 13)
m_scene.RegionInfo.RegionSettings.Maturity = 0;
else if (matureLevel <= 21)
m_scene.RegionInfo.RegionSettings.Maturity = 1;
else
m_scene.RegionInfo.RegionSettings.Maturity = 2;
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = allowParcelChanges;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public OSDMap OnRegisterCaps(UUID agentID, IHttpServer server)
{
OSDMap retVal = new OSDMap();
retVal["DispatchRegionInfo"] = CapsUtil.CreateCAPS("DispatchRegionInfo", "");
#if (!ISWIN)
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["DispatchRegionInfo"],
delegate(Hashtable m_dhttpMethod)
{
return DispatchRegionInfo(m_dhttpMethod, retVal["DispatchRegionInfo"], agentID);
}));
#else
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["DispatchRegionInfo"],
m_dhttpMethod =>
DispatchRegionInfo(m_dhttpMethod, retVal["DispatchRegionInfo"],
agentID)));
#endif
retVal["EstateChangeInfo"] = CapsUtil.CreateCAPS("EstateChangeInfo", "");
#if (!ISWIN)
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["EstateChangeInfo"],
delegate(Hashtable m_dhttpMethod)
{
return EstateChangeInfo(m_dhttpMethod, retVal["EstateChangeInfo"], agentID);
}));
#else
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["EstateChangeInfo"],
m_dhttpMethod =>
EstateChangeInfo(m_dhttpMethod, retVal["EstateChangeInfo"],
agentID)));
#endif
return retVal;
}
private Hashtable EstateChangeInfo(Hashtable m_dhttpMethod, UUID capuuid, UUID agentID)
{
if (!m_scene.Permissions.CanIssueEstateCommand(agentID, false))
return new Hashtable();
OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml((string)m_dhttpMethod["requestbody"]);
string estate_name = rm["estate_name"].AsString();
bool allow_direct_teleport = rm["allow_direct_teleport"].AsBoolean();
bool allow_voice_chat = rm["allow_voice_chat"].AsBoolean();
bool deny_age_unverified = rm["deny_age_unverified"].AsBoolean();
bool deny_anonymous = rm["deny_anonymous"].AsBoolean();
UUID invoice = rm["invoice"].AsUUID();
bool is_externally_visible = rm["is_externally_visible"].AsBoolean();
bool is_sun_fixed = rm["is_sun_fixed"].AsBoolean();
string owner_abuse_email = rm["owner_abuse_email"].AsString();
double sun_hour = rm["sun_hour"].AsReal ();
m_scene.RegionInfo.EstateSettings.EstateName = estate_name;
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = allow_direct_teleport;
m_scene.RegionInfo.EstateSettings.AllowVoice = allow_voice_chat;
m_scene.RegionInfo.EstateSettings.DenyAnonymous = deny_anonymous;
m_scene.RegionInfo.EstateSettings.DenyIdentified = deny_age_unverified;
m_scene.RegionInfo.EstateSettings.PublicAccess = is_externally_visible;
m_scene.RegionInfo.EstateSettings.FixedSun = is_sun_fixed;
m_scene.RegionInfo.EstateSettings.AbuseEmail = owner_abuse_email;
if (sun_hour == 0)
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = true;
m_scene.RegionInfo.EstateSettings.SunPosition = 0;
}
else
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = false;
m_scene.RegionInfo.EstateSettings.SunPosition = sun_hour;
}
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
TriggerEstateSunUpdate();
IClientAPI remoteClient;
m_scene.ClientManager.TryGetValue(agentID, out remoteClient);
sendDetailedEstateData(remoteClient, invoice);
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(new OSDMap());
return responsedata;
}
private Hashtable DispatchRegionInfo(Hashtable m_dhttpMethod, UUID capuuid, UUID agentID)
{
if (!m_scene.Permissions.CanIssueEstateCommand(agentID, false))
return new Hashtable();
OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml((string)m_dhttpMethod["requestbody"]);
int agent_limit = rm["agent_limit"].AsInteger();
bool allow_damage = rm["allow_damage"].AsBoolean();
bool allow_land_resell = rm["allow_land_resell"].AsBoolean();
bool allow_parcel_changes = rm["allow_parcel_changes"].AsBoolean();
bool block_fly = rm["block_fly"].AsBoolean();
bool block_parcel_search = rm["block_parcel_search"].AsBoolean();
bool block_terraform = rm["block_terraform"].AsBoolean();
long prim_bonus = rm["prim_bonus"].AsLong();
bool restrict_pushobject = rm["restrict_pushobject"].AsBoolean();
int sim_access = rm["sim_access"].AsInteger();
int minimum_agent_age = 0;
if (rm.ContainsKey("minimum_agent_age"))
minimum_agent_age = rm["minimum_agent_age"].AsInteger();
m_scene.RegionInfo.RegionSettings.BlockTerraform = block_terraform;
m_scene.RegionInfo.RegionSettings.BlockFly = block_fly;
m_scene.RegionInfo.RegionSettings.AllowDamage = allow_damage;
m_scene.RegionInfo.RegionSettings.RestrictPushing = restrict_pushobject;
m_scene.RegionInfo.RegionSettings.AllowLandResell = allow_land_resell;
m_scene.RegionInfo.RegionSettings.AgentLimit = agent_limit;
m_scene.RegionInfo.RegionSettings.ObjectBonus = prim_bonus;
m_scene.RegionInfo.RegionSettings.MinimumAge = minimum_agent_age;
if (sim_access <= 13)
m_scene.RegionInfo.RegionSettings.Maturity = 0;
else if (sim_access <= 21)
m_scene.RegionInfo.RegionSettings.Maturity = 1;
else
m_scene.RegionInfo.RegionSettings.Maturity = 2;
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = allow_parcel_changes;
m_scene.RegionInfo.RegionSettings.BlockShowInSearch = block_parcel_search;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "";
return responsedata;
}
public void setEstateTerrainBaseTexture(int level, UUID texture)
{
setEstateTerrainBaseTexture(null, level, texture);
sendRegionHandshakeToAll();
}
public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int level, UUID texture)
{
if (texture == UUID.Zero)
return;
switch (level)
{
case 0:
m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
}
public void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue)
{
setEstateTerrainTextureHeights(null, corner, lowValue, highValue);
}
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
{
if (m_scene.Permissions.CanIssueEstateCommand(client.AgentId, true))
{
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
}
}
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
{
m_scene.RegionInfo.RegionSettings.Save ();
TriggerRegionInfoChange ();
sendRegionHandshakeToAll ();
//sendRegionInfoPacketToAll ();
}
public void setRegionTerrainSettings(UUID AgentID, float WaterHeight,
float TerrainRaiseLimit, float TerrainLowerLimit,
bool UseEstateSun, bool UseFixedSun, float SunHour,
bool UseGlobal, bool EstateFixedSun, float EstateSunHour)
{
if (AgentID == UUID.Zero || m_scene.Permissions.CanIssueEstateCommand(AgentID, false))
{
// Water Height
m_scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight;
//Update physics so that the water stuff works after a height change.
ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
if (terrainModule != null)
terrainModule.UpdateWaterHeight(m_scene.RegionInfo.RegionSettings.WaterHeight);
// Terraforming limits
m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit;
m_scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit;
// Time of day / fixed sun
m_scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun;
m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
m_scene.RegionInfo.RegionSettings.SunPosition = SunHour;
TriggerEstateSunUpdate();
//MainConsole.Instance.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
//MainConsole.Instance.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
sendRegionInfoPacketToAll();
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
}
private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
{
IRestartModule restartModule = m_scene.RequestModuleInterface<IRestartModule>();
if (restartModule != null)
{
List<int> times = new List<int>();
while (timeInSeconds > 0)
{
times.Add(timeInSeconds);
if (timeInSeconds > 300)
timeInSeconds -= 120;
else if (timeInSeconds > 30)
timeInSeconds -= 30;
else
timeInSeconds -= 15;
}
restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), true);
}
}
private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID)
{
m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
m_scene.RegionInfo.RegionSettings.CovenantLastUpdated = Util.UnixTimeSinceEpoch();
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private enum AccessDeltaRequest
{
ApplyToAllEstates = 1 << 0,
ApplyToManagedEstates = 1 << 1,
AddAllowedUser = 1 << 2,
RemoveAllowedUser = 1 << 3,
AddAllowedGroup = 1 << 4,
RemoveAllowedGroup = 1 << 5,
AddBannedUser = 1 << 6,
RemoveBannedUser = 1 << 7,
AddEstateManager = 1 << 8,
RemoveEstateManager = 1 << 9,
MoreToCome = 1 << 10
}
private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
{
// EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc.
if (user == m_scene.RegionInfo.EstateSettings.EstateOwner)
return; // never process EO
if ((estateAccessType & (int)AccessDeltaRequest.AddAllowedUser) != 0) // User add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.AddEstateUser (user);
estate.Save ();
}
}
}
m_scene.RegionInfo.EstateSettings.AddEstateUser(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.RemoveAllowedUser) != 0) // User remove
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.RemoveEstateUser (user);
estate.Save ();
}
}
}
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.AddAllowedGroup) != 0) // Group add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.AddEstateGroup (user);
estate.Save ();
}
}
}
m_scene.RegionInfo.EstateSettings.AddEstateGroup(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.RemoveAllowedGroup) != 0) // Group remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.RemoveEstateGroup (user);
estate.Save ();
}
}
}
m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.AddBannedUser) != 0) // Ban add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
EstateBan[] innerbanlistcheck = estate.EstateBans;
#if (!ISWIN)
bool inneralreadyInList = false;
foreach (EstateBan t in innerbanlistcheck)
{
if (user == t.BannedUserID)
{
inneralreadyInList = true;
break;
}
}
#else
bool inneralreadyInList = innerbanlistcheck.Any(t => user == t.BannedUserID);
#endif
if (!inneralreadyInList)
{
EstateBan item = new EstateBan {BannedUserID = user, EstateID = estate.EstateID};
IScenePresence SP = m_scene.GetScenePresence (user);
item.BannedHostAddress = (SP != null) ? ((System.Net.IPEndPoint)SP.ControllingClient.GetClientEP ()).Address.ToString () : "0.0.0.0";
item.BannedHostIPMask = (SP != null) ? ((System.Net.IPEndPoint)SP.ControllingClient.GetClientEP ()).Address.ToString () : "0.0.0.0";
item.BannedHostNameMask = (SP != null) ? ((System.Net.IPEndPoint)SP.ControllingClient.GetClientEP ()).Address.ToString () : "0.0.0.0";
estate.AddBan (item);
estate.Save ();
}
}
}
}
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
#if (!ISWIN)
bool alreadyInList = false;
foreach (EstateBan t in banlistcheck)
{
if (user == t.BannedUserID)
{
alreadyInList = true;
break;
}
}
#else
bool alreadyInList = banlistcheck.Any(t => user == t.BannedUserID);
#endif
if (!alreadyInList)
{
EstateBan item = new EstateBan
{
BannedUserID = user,
EstateID = m_scene.RegionInfo.EstateSettings.EstateID,
BannedHostAddress = "0.0.0.0"
};
IScenePresence SP = m_scene.GetScenePresence (user);
item.BannedHostIPMask = (SP != null) ? ((System.Net.IPEndPoint)SP.ControllingClient.GetClientEP()).Address.ToString() : "0.0.0.0";
m_scene.RegionInfo.EstateSettings.AddBan(item);
//Trigger the event
m_scene.AuroraEventManager.FireGenericEventHandler("BanUser", user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
if (SP != null)
{
if (!SP.IsChildAgent)
{
IEntityTransferModule transferModule = m_scene.RequestModuleInterface<IEntityTransferModule>();
if (transferModule != null)
transferModule.TeleportHome(user, SP.ControllingClient);
}
else
{
//Close them in the sim
IEntityTransferModule transferModule = SP.Scene.RequestModuleInterface<IEntityTransferModule> ();
if (transferModule != null)
transferModule.IncomingCloseAgent (SP.Scene, SP.UUID);
}
}
}
else
{
remote_client.SendAlertMessage("User is already on the region ban list");
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.RemoveBannedUser) != 0) // Ban remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
EstateBan[] innerbanlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool inneralreadyInList = false;
EstateBan innerlistitem = null;
foreach (EstateBan t in innerbanlistcheck)
{
if (user == t.BannedUserID)
{
inneralreadyInList = true;
innerlistitem = t;
break;
}
}
if (inneralreadyInList)
{
m_scene.RegionInfo.EstateSettings.RemoveBan (innerlistitem.BannedUserID);
}
estate.Save ();
}
}
}
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
EstateBan listitem = null;
foreach (EstateBan t in banlistcheck)
{
if (user == t.BannedUserID)
{
alreadyInList = true;
listitem = t;
break;
}
}
//Trigger the event
m_scene.AuroraEventManager.FireGenericEventHandler("UnBanUser", user);
if (alreadyInList)
{
m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("User is not on the region ban list");
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.AddEstateManager) != 0) // Manager add
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.AddEstateManager (user);
estate.Save ();
}
}
}
m_scene.RegionInfo.EstateSettings.AddEstateManager(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.RemoveEstateManager) != 0) // Manager remove
{
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
IEstateConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IEstateConnector> ();
if ((estateAccessType & 1) != 0 && connector != null) // All estates
{
List<EstateSettings> estateIDs = connector.GetEstates (remote_client.AgentId);
foreach (EstateSettings estate in estateIDs)
{
if (estate.EstateID != m_scene.RegionInfo.EstateSettings.EstateID)
{
estate.RemoveEstateManager (user);
estate.Save ();
}
}
}
m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & (int)AccessDeltaRequest.MoreToCome) == 0) //1024 means more than one is being sent
{
remote_client.SendEstateList(invoice, (int)EstateTools.EstateAccessReplyDelta.AllowedUsers, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice, (int)EstateTools.EstateAccessReplyDelta.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice, (int)EstateTools.EstateAccessReplyDelta.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
}
}
private void SendSimulatorBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = m_scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInRegion(senderID, senderName, message);
}
private void SendEstateBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
TriggerEstateMessage(senderID, senderName, message);
}
private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics)
{
m_scene.RegionInfo.RegionSettings.DisablePhysics = physics;
m_scene.RegionInfo.RegionSettings.DisableScripts = scripted;
m_scene.RegionInfo.RegionSettings.DisableCollisions = collisionEvents;
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
SetSceneCoreDebug(scripted, collisionEvents, physics);
}
public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
{
if (m_scene.RegionInfo.RegionSettings.DisableScripts == !ScriptEngine)
{
if (ScriptEngine)
{
MainConsole.Instance.Info("[SCENEDEBUG]: Stopping all Scripts in Scene");
IScriptModule mod = m_scene.RequestModuleInterface<IScriptModule>();
mod.StopAllScripts();
}
else
{
MainConsole.Instance.Info("[SCENEDEBUG]: Starting all Scripts in Scene");
ISceneEntity[] entities = m_scene.Entities.GetEntities ();
foreach (ISceneEntity ent in entities)
{
ent.CreateScriptInstances(0, false, StateSource.NewRez, UUID.Zero);
}
}
m_scene.RegionInfo.RegionSettings.DisableScripts = !ScriptEngine;
}
if (m_scene.RegionInfo.RegionSettings.DisablePhysics == !PhysicsEngine)
{
m_scene.RegionInfo.RegionSettings.DisablePhysics = !PhysicsEngine;
}
if (m_scene.RegionInfo.RegionSettings.DisableCollisions == !CollisionEvents)
{
m_scene.RegionInfo.RegionSettings.DisableCollisions = !CollisionEvents;
m_scene.PhysicsScene.DisableCollisions = m_scene.RegionInfo.RegionSettings.DisableCollisions;
}
}
private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
if (prey != UUID.Zero)
{
IScenePresence s = m_scene.GetScenePresence (prey);
if (s != null)
{
IEntityTransferModule transferModule = m_scene.RequestModuleInterface<IEntityTransferModule>();
if (transferModule != null)
transferModule.TeleportHome(prey, s.ControllingClient);
}
}
}
private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
m_scene.ForEachScenePresence(delegate(IScenePresence sp)
{
if (sp.UUID != senderID)
{
IScenePresence p = m_scene.GetScenePresence (sp.UUID);
// make sure they are still there, we could be working down a long list
// Also make sure they are actually in the region
if (p != null && !p.IsChildAgent)
{
IEntityTransferModule transferModule = m_scene.RequestModuleInterface<IEntityTransferModule>();
if (transferModule != null)
transferModule.TeleportHome(p.UUID, p.ControllingClient);
}
}
});
}
private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
{
if (TerrainUploader != null)
{
lock (TerrainUploader)
{
if (XferID == TerrainUploader.XferID)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
remoteClient.SendAlertMessage("Terrain Upload aborted by the client");
}
}
}
}
private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient)
{
lock (TerrainUploader)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
}
remoteClient.SendAlertMessage("Terrain Upload Complete. Loading....");
ITerrainModule terr = m_scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
MainConsole.Instance.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
try
{
FileInfo x = new FileInfo(filename);
if (x.Extension == ".oar") // It's an oar file
{
bool check = false;
while (!check)
{
if (File.Exists(filename))
{
filename = "duplicate" + filename;
}
else
check = true;
}
FileStream input = new FileStream(filename, FileMode.CreateNew);
input.Write(terrainData, 0, terrainData.Length);
input.Close();
MainConsole.Instance.RunCommand("load oar " + filename);
remoteClient.SendAlertMessage("Your oar file was loaded. It may take a few moments to appear.");
}
else
{
MemoryStream terrainStream = new MemoryStream(terrainData);
terr.LoadFromStream(filename, terrainStream);
terrainStream.Close();
remoteClient.SendAlertMessage("Your terrain was loaded as a ." + x.Extension + " file. It may take a few moments to appear.");
}
}
catch (IOException e)
{
MainConsole.Instance.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e);
remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space.");
return;
}
catch (SecurityException e)
{
MainConsole.Instance.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e);
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (UnauthorizedAccessException e)
{
MainConsole.Instance.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e);
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e);
remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again");
}
}
else
{
remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module");
}
}
private void handleUploadTerrain(IClientAPI remote_client, string clientFileName)
{
if (TerrainUploader == null)
{
remote_client.SendAlertMessage("Uploading terrain file...");
TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName);
lock (TerrainUploader)
{
remote_client.OnXferReceive += TerrainUploader.XferReceive;
remote_client.OnAbortXfer += AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone += HandleTerrainApplication;
}
TerrainUploader.RequestStartXfer(remote_client);
}
else
{
remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!");
}
}
private void handleTerrainRequest(IClientAPI remote_client, string clientFileName)
{
// Save terrain here
ITerrainModule terr = m_scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
MainConsole.Instance.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
terr.SaveToFile(Util.dataDir() + "/terrain.raw");
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open);
byte[] bdata = new byte[input.Length];
input.Read(bdata, 0, (int)input.Length);
remote_client.SendAlertMessage("Terrain file written, starting download...");
IXfer xfer = m_scene.RequestModuleInterface<IXfer>();
if(xfer != null)
xfer.AddNewFile("terrain.raw", bdata);
// Tell client about it
MainConsole.Instance.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name);
remote_client.SendInitiateDownload("terrain.raw", clientFileName);
}
}
private void HandleRegionInfoRequest(IClientAPI remote_client)
{
RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs
{
billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor,
estateID = m_scene.RegionInfo.EstateSettings.EstateID,
maxAgents = (byte) m_scene.RegionInfo.RegionSettings.AgentLimit,
objectBonusFactor =
(float) m_scene.RegionInfo.RegionSettings.ObjectBonus,
parentEstateID = m_scene.RegionInfo.EstateSettings.ParentEstateID,
pricePerMeter = m_scene.RegionInfo.EstateSettings.PricePerMeter,
redirectGridX = m_scene.RegionInfo.EstateSettings.RedirectGridX,
redirectGridY = m_scene.RegionInfo.EstateSettings.RedirectGridY,
regionFlags = GetRegionFlags(),
simAccess = m_scene.RegionInfo.AccessLevel,
sunHour = (float) m_scene.RegionInfo.RegionSettings.SunPosition,
terrainLowerLimit =
(float) m_scene.RegionInfo.RegionSettings.TerrainLowerLimit,
terrainRaiseLimit =
(float) m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
useEstateSun = m_scene.RegionInfo.RegionSettings.UseEstateSun,
waterHeight =
(float) m_scene.RegionInfo.RegionSettings.WaterHeight,
simName = m_scene.RegionInfo.RegionName,
regionType = m_scene.RegionInfo.RegionType
};
remote_client.SendRegionInfoToEstateMenu(args);
}
private void HandleEstateCovenantRequest(IClientAPI remote_client)
{
remote_client.SendEstateCovenantInformation(m_scene.RegionInfo.RegionSettings.Covenant,
m_scene.RegionInfo.RegionSettings.CovenantLastUpdated);
}
private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient)
{
if (!m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false))
return;
Dictionary<uint, float> SceneData = new Dictionary<uint,float>();
if (reportType == (uint)EstateTools.LandStatReportType.TopColliders)
{
SceneData = m_scene.PhysicsScene.GetTopColliders();
}
else if (reportType == (uint)EstateTools.LandStatReportType.TopScripts)
{
IScriptModule scriptModule = m_scene.RequestModuleInterface<IScriptModule>();
SceneData = scriptModule.GetTopScripts(m_scene.RegionInfo.RegionID);
}
List<LandStatReportItem> SceneReport = new List<LandStatReportItem>();
lock (SceneData)
{
foreach (uint obj in SceneData.Keys)
{
ISceneChildEntity prt = m_scene.GetSceneObjectPart (obj);
if (prt != null)
{
if (prt.ParentEntity != null)
{
ISceneEntity sog = prt.ParentEntity;
LandStatReportItem lsri = new LandStatReportItem
{
Location = sog.AbsolutePosition,
Score = SceneData[obj],
TaskID = sog.UUID,
TaskLocalID = sog.LocalId,
TaskName = prt.Name,
TimeModified = sog.RootChild.Rezzed
};
UserAccount account =
m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, sog.OwnerID);
lsri.OwnerName = account != null ? account.Name : "Unknown";
if (filter.Length != 0)
{
//Its in the filter, don't check it
if (requestFlags == 2) //Owner name
{
if (!lsri.OwnerName.Contains(filter))
continue;
}
if (requestFlags == 4) //Object name
{
if (!lsri.TaskName.Contains(filter))
continue;
}
}
SceneReport.Add(lsri);
}
}
}
}
remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray());
}
private static void LookupUUIDSCompleted(IAsyncResult iar)
{
LookupUUIDS icon = (LookupUUIDS)iar.AsyncState;
icon.EndInvoke(iar);
}
private void LookupUUID(List<UUID> uuidLst)
{
LookupUUIDS d = LookupUUIDsAsync;
d.BeginInvoke(uuidLst,
LookupUUIDSCompleted,
d);
}
private void LookupUUIDsAsync(List<UUID> uuidLst)
{
UUID[] uuidarr;
lock (uuidLst)
{
uuidarr = uuidLst.ToArray();
}
foreach (UUID t in uuidarr)
{
m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, t);
// we drop it. It gets cached though... so we're ready for the next request.
}
}
private enum SimWideDeletesFlags
{
ReturnObjectsOtherEstate = 1,
ReturnObjects = 2,
OthersLandNotUserOnly = 3,
ScriptedPrimsOnly = 4
}
public void SimWideDeletes(IClientAPI client, int flags, UUID targetID)
{
if (m_scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
{
List<ISceneEntity> prims = new List<ISceneEntity> ();
IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>();
if (parcelManagement != null)
{
int containsScript = (flags & (int)SimWideDeletesFlags.ScriptedPrimsOnly);
foreach (ILandObject selectedParcel in parcelManagement.AllParcels())
{
if ((flags & (int)SimWideDeletesFlags.OthersLandNotUserOnly) == (int)SimWideDeletesFlags.OthersLandNotUserOnly)
{
if (selectedParcel.LandData.OwnerID != targetID)//Check to make sure it isn't their land
prims.AddRange (selectedParcel.GetPrimsOverByOwner (targetID, containsScript));
}
//Other estates flag doesn't seem to get sent by the viewer, so don't touch it
//else if ((flags & (int)SimWideDeletesFlags.ReturnObjectsOtherEstate) == (int)SimWideDeletesFlags.ReturnObjectsOtherEstate)
// prims.AddRange (selectedParcel.GetPrimsOverByOwner (targetID, containsScript));
else// if ((flags & (int)SimWideDeletesFlags.ReturnObjects) == (int)SimWideDeletesFlags.ReturnObjects)//Return them all
prims.AddRange (selectedParcel.GetPrimsOverByOwner (targetID, containsScript));
}
}
ILLClientInventory inventoryModule = m_scene.RequestModuleInterface<ILLClientInventory>();
if (inventoryModule != null)
inventoryModule.ReturnObjects(prims.ToArray(), UUID.Zero);
}
else
{
client.SendAlertMessage("You do not have permissions to return objects in this sim.");
}
}
#endregion
#region Outgoing Packets
public void sendRegionInfoPacketToAll()
{
m_scene.ForEachScenePresence(delegate(IScenePresence sp)
{
if (!sp.IsChildAgent)
HandleRegionInfoRequest(sp.ControllingClient);
});
}
public void sendRegionHandshake(IClientAPI remoteClient)
{
RegionHandshakeArgs args = new RegionHandshakeArgs
{isEstateManager = m_scene.Permissions.IsGod(remoteClient.AgentId)};
if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && m_scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId)
args.isEstateManager = true;
else if (m_scene.RegionInfo.EstateSettings.IsEstateManager(remoteClient.AgentId))
args.isEstateManager = true;
args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor;
args.terrainStartHeight0 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SW;
args.terrainHeightRange0 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SW;
args.terrainStartHeight1 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NW;
args.terrainHeightRange1 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NW;
args.terrainStartHeight2 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SE;
args.terrainHeightRange2 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SE;
args.terrainStartHeight3 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NE;
args.terrainHeightRange3 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NE;
args.simAccess = m_scene.RegionInfo.AccessLevel;
args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
args.regionFlags = GetRegionFlags();
args.regionName = m_scene.RegionInfo.RegionName;
args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
args.terrainBase0 = UUID.Zero;
args.terrainBase1 = UUID.Zero;
args.terrainBase2 = UUID.Zero;
args.terrainBase3 = UUID.Zero;
if (!m_scene.RegionInfo.RegionSettings.UsePaintableTerrain)
{
args.terrainDetail0 = m_scene.RegionInfo.RegionSettings.TerrainTexture1;
args.terrainDetail1 = m_scene.RegionInfo.RegionSettings.TerrainTexture2;
args.terrainDetail2 = m_scene.RegionInfo.RegionSettings.TerrainTexture3;
args.terrainDetail3 = m_scene.RegionInfo.RegionSettings.TerrainTexture4;
}
else
{
args.terrainDetail0 = m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture;
args.terrainDetail1 = m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture;
args.terrainDetail2 = m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture;
args.terrainDetail3 = m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture;
AssetBase paintAsset = m_scene.AssetService.Get(m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture.ToString());
if (paintAsset == null)
{
paintAsset = new AssetBase(m_scene.RegionInfo.RegionSettings.PaintableTerrainTexture,
"PaintableTerrainTexture-" + m_scene.RegionInfo.RegionID,
AssetType.Texture, UUID.Zero) {Flags = AssetFlags.Deletable};
AssetBase defaultTexture = m_scene.AssetService.Get(RegionSettings.DEFAULT_TERRAIN_TEXTURE_2.ToString());//Nice grass
if (defaultTexture == null)
//Erm... what to do!
return;
paintAsset.Data = defaultTexture.Data;//Eventually we need to replace this with an interpolation of the existing textures!
paintAsset.ID = m_scene.AssetService.Store(paintAsset);
}
}
args.RegionType = Utils.StringToBytes(m_scene.RegionInfo.RegionType);
remoteClient.SendRegionHandshake(m_scene.RegionInfo,args);
}
public void sendRegionHandshakeToAll()
{
m_scene.ForEachClient(sendRegionHandshake);
}
public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2)
{
if (parms2 == 0)
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = true;
m_scene.RegionInfo.EstateSettings.SunPosition = 0.0;
}
else
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = false;
m_scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0;
}
m_scene.RegionInfo.EstateSettings.FixedSun = (parms1 & 0x00000010) != 0;
m_scene.RegionInfo.EstateSettings.PublicAccess = (parms1 & 0x00008000) != 0;
m_scene.RegionInfo.EstateSettings.AllowVoice = (parms1 & 0x10000000) != 0;
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = (parms1 & 0x00100000) != 0;
m_scene.RegionInfo.EstateSettings.DenyAnonymous = (parms1 & 0x00800000) != 0;
m_scene.RegionInfo.EstateSettings.DenyIdentified = (parms1 & 0x01000000) != 0;
m_scene.RegionInfo.EstateSettings.DenyTransacted = (parms1 & 0x02000000) != 0;
m_scene.RegionInfo.EstateSettings.DenyMinors = (parms1 & 0x40000000) != 0;
m_scene.RegionInfo.RegionSettings.BlockShowInSearch = (parms1 & (uint)RegionFlags.BlockParcelSearch) == (uint)RegionFlags.BlockParcelSearch;
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
TriggerEstateSunUpdate();
sendDetailedEstateData(remoteClient, invoice);
}
#endregion
#region IRegionModule Members
public void Initialise(IConfigSource source)
{
}
#region Console Commands
public void consoleSetTerrainTexture(string[] args)
{
string num = args[3];
string uuid = args[4];
int x = (args.Length > 5 ? int.Parse(args[5]) : -1);
int y = (args.Length > 6 ? int.Parse(args[6]) : -1);
if (x == -1 || (m_scene.RegionInfo.RegionLocX / Constants.RegionSize) == x)
{
if (y == -1 || (m_scene.RegionInfo.RegionLocY / Constants.RegionSize) == y)
{
int corner = int.Parse(num);
UUID texture = UUID.Parse(uuid);
MainConsole.Instance.Debug("[ESTATEMODULE] Setting terrain textures for " + m_scene.RegionInfo.RegionName +
string.Format(" (C#{0} = {1})", corner, texture));
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
}
}
public void consoleSetTerrainHeights(string[] args)
{
string num = args[3];
string min = args[4];
string max = args[5];
int x = (args.Length > 6 ? int.Parse(args[6]) : -1);
int y = (args.Length > 7 ? int.Parse(args[7]) : -1);
if (x == -1 || (m_scene.RegionInfo.RegionLocX / Constants.RegionSize) == x)
{
if (y == -1 || (m_scene.RegionInfo.RegionLocY / Constants.RegionSize) == y)
{
int corner = int.Parse(num);
float lowValue = float.Parse(min, Culture.NumberFormatInfo);
float highValue = float.Parse(max, Culture.NumberFormatInfo);
MainConsole.Instance.Debug("[ESTATEMODULE] Setting terrain heights " + m_scene.RegionInfo.RegionName +
string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue));
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionHandshakeToAll();
}
}
}
#endregion
public void AddRegion (IScene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IEstateModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
scene.EventManager.OnRegisterCaps += OnRegisterCaps;
scene.EventManager.OnClosingClient += OnClosingClient;
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand (
"set terrain texture",
"set terrain texture [number] [uuid] [x] [y]",
"Sets the terrain [number] to [uuid], if [x] or [y] are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in [x] or [y] to wildcard" +
" that coordinate.",
consoleSetTerrainTexture);
MainConsole.Instance.Commands.AddCommand (
"set terrain heights",
"set terrain heights [corner] [min] [max] [x] [y]",
"Sets the terrain texture heights on corner #[corner] to [min]/[max], if [x] or [y] are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in [x] or [y] to wildcard" +
" that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3.",
consoleSetTerrainHeights);
}
}
public void RemoveRegion (IScene scene)
{
m_scene.UnregisterModuleInterface<IEstateModule>(this);
m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
m_scene.EventManager.OnRequestChangeWaterHeight -= changeWaterHeight;
scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
scene.EventManager.OnClosingClient -= OnClosingClient;
}
public void RegionLoaded (IScene scene)
{
// Sets up the sun module based no the saved Estate and Region Settings
// DO NOT REMOVE or the sun will stop working
TriggerEstateSunUpdate();
}
public Type ReplaceableInterface
{
get { return null; }
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "EstateManagementModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region Other Functions
public void changeWaterHeight(float height)
{
setRegionTerrainSettings(UUID.Zero, height,
(float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
(float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
m_scene.RegionInfo.RegionSettings.FixedSun,
(float)m_scene.RegionInfo.RegionSettings.SunPosition,
m_scene.RegionInfo.EstateSettings.UseGlobalTime,
m_scene.RegionInfo.EstateSettings.FixedSun,
(float)m_scene.RegionInfo.EstateSettings.SunPosition);
sendRegionInfoPacketToAll();
}
#endregion
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest += sendDetailedEstateData;
client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings += setRegionTerrainSettings;
client.OnEstateRestartSimRequest += handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo += handleEstateChangeInfo;
client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain += handleTerrainRequest;
client.OnUploadTerrain += handleUploadTerrain;
client.OnSimWideDeletes += SimWideDeletes;
client.OnRegionInfoRequest += HandleRegionInfoRequest;
client.OnEstateCovenantRequest += HandleEstateCovenantRequest;
client.OnLandStatRequest += HandleLandStatRequest;
sendRegionHandshake(client);
}
private void OnClosingClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest -= sendDetailedEstateData;
client.OnSetEstateFlagsRequest -= estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture -= setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture -= setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights -= setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest -= handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings -= setRegionTerrainSettings;
client.OnEstateRestartSimRequest -= handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest -= handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo -= handleEstateChangeInfo;
client.OnUpdateEstateAccessDeltaRequest -= handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest -= SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest -= SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest -= handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest -= handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest -= handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain -= handleTerrainRequest;
client.OnUploadTerrain -= handleUploadTerrain;
client.OnSimWideDeletes -= SimWideDeletes;
client.OnRegionInfoRequest -= HandleRegionInfoRequest;
client.OnEstateCovenantRequest -= HandleEstateCovenantRequest;
client.OnLandStatRequest -= HandleLandStatRequest;
}
public uint GetRegionFlags()
{
RegionFlags flags = RegionFlags.None;
// Fully implemented
//
if (m_scene.RegionInfo.RegionSettings.AllowDamage)
flags |= RegionFlags.AllowDamage;
if (m_scene.RegionInfo.RegionSettings.BlockTerraform)
flags |= RegionFlags.BlockTerraform;
if (!m_scene.RegionInfo.RegionSettings.AllowLandResell)
flags |= RegionFlags.BlockLandResell;
if (m_scene.RegionInfo.RegionSettings.DisableCollisions)
flags |= RegionFlags.SkipCollisions;
if (m_scene.RegionInfo.RegionSettings.DisableScripts)
flags |= RegionFlags.SkipScripts;
if (m_scene.RegionInfo.RegionSettings.DisablePhysics)
flags |= RegionFlags.SkipPhysics;
if (m_scene.RegionInfo.RegionSettings.BlockFly)
flags |= RegionFlags.NoFly;
if (m_scene.RegionInfo.RegionSettings.RestrictPushing)
flags |= RegionFlags.RestrictPushObject;
if (m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide)
flags |= RegionFlags.AllowParcelChanges;
if (m_scene.RegionInfo.RegionSettings.BlockShowInSearch)
flags |= RegionFlags.BlockParcelSearch;
if (m_scene.RegionInfo.RegionSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.RegionSettings.Sandbox)
flags |= RegionFlags.Sandbox;
if (m_scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (m_scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (m_scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (m_scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
// Omitted
//
// Omitted: SkipUpdateInterestList Region does not update agent prim interest lists. Internal debugging option.
// Omitted: NullLayer Unknown: Related to the availability of an overview world map tile.(Think mainland images when zoomed out.)
// Omitted: SkipAgentAction Unknown: Related to region debug flags. Possibly to skip processing of agent interaction with world.
return (uint)flags;
}
public uint GetEstateFlags()
{
RegionFlags flags = RegionFlags.None;
if (m_scene.RegionInfo.EstateSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.EstateSettings.PublicAccess)
flags |= (RegionFlags.PublicAllowed |
RegionFlags.ExternallyVisible);
if (m_scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
flags |= RegionFlags.AllowDirectTeleport;
if (m_scene.RegionInfo.EstateSettings.DenyAnonymous)
flags |= RegionFlags.DenyAnonymous;
if (m_scene.RegionInfo.EstateSettings.DenyIdentified)
flags |= RegionFlags.DenyIdentified;
if (m_scene.RegionInfo.EstateSettings.DenyTransacted)
flags |= RegionFlags.DenyTransacted;
if (m_scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner)
flags |= RegionFlags.AbuseEmailToEstateOwner;
if (m_scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (m_scene.RegionInfo.EstateSettings.EstateSkipScripts)
flags |= RegionFlags.EstateSkipScripts;
if (m_scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
if (m_scene.RegionInfo.EstateSettings.TaxFree)
flags |= RegionFlags.TaxFree;
if (m_scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (m_scene.RegionInfo.EstateSettings.AllowParcelChanges)
flags |= RegionFlags.AllowParcelChanges;
if (m_scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (m_scene.RegionInfo.EstateSettings.DenyMinors)
flags |= (RegionFlags)(1 << 30);
return (uint)flags;
}
public bool IsManager(UUID avatarID)
{
if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner)
return true;
List<UUID> ems = new List<UUID>(m_scene.RegionInfo.EstateSettings.EstateManagers);
if (ems.Contains(avatarID))
return true;
return false;
}
protected void TriggerRegionInfoChange()
{
ChangeDelegate change = OnRegionInfoChange;
if (change != null)
change(m_scene.RegionInfo.RegionID);
}
protected void TriggerEstateInfoChange()
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(m_scene.RegionInfo.RegionID);
}
protected void TriggerEstateMessage(UUID fromID, string fromName, string message)
{
MessageDelegate onmessage = OnEstateMessage;
IDialogModule module = m_scene.RequestModuleInterface<IDialogModule>();
if (onmessage != null)
onmessage(m_scene.RegionInfo.RegionID, fromID, fromName, message);
else if (module != null)
module.SendGeneralAlert(message);
}
public void TriggerEstateSunUpdate()
{
if (m_scene.RegionInfo.EstateSettings == null)
return;
float sun;
if (m_scene.RegionInfo.RegionSettings.UseEstateSun)
{
sun = (float)m_scene.RegionInfo.EstateSettings.SunPosition;
if (m_scene.RegionInfo.EstateSettings.UseGlobalTime)
{
ISunModule sunModule = m_scene.RequestModuleInterface<ISunModule>();
if(sunModule != null)
sun = sunModule.GetCurrentSunHour();
}
//
m_scene.EventManager.TriggerEstateToolsSunUpdate(
m_scene.RegionInfo.RegionHandle,
m_scene.RegionInfo.EstateSettings.FixedSun,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
sun);
}
else
{
// Use the Sun Position from the Region Settings
sun = (float)m_scene.RegionInfo.RegionSettings.SunPosition/* - 6.0f*/;
m_scene.EventManager.TriggerEstateToolsSunUpdate(
m_scene.RegionInfo.RegionHandle,
m_scene.RegionInfo.RegionSettings.FixedSun,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
sun);
}
}
}
}
| |
/***************************************************************************
copyright : (C) 2005 by Brian Nickel
email : brian.nickel@gmail.com
based on : textidentificationframe.cpp from TagLib
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/
using System.Collections;
using System;
namespace TagLib.Id3v2
{
public class TextIdentificationFrame : Frame
{
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
StringType text_encoding;
StringList field_list;
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public TextIdentificationFrame (ByteVector type, StringType encoding) : base (type)
{
field_list = new StringList ();
text_encoding = encoding;
}
public TextIdentificationFrame (ByteVector data) : base (data)
{
field_list = new StringList ();
text_encoding = StringType.UTF8;
SetData (data, 0);
}
public void SetText (StringList l)
{
field_list.Clear ();
field_list.Add (l);
}
public override void SetText (String s)
{
field_list.Clear ();
field_list.Add (s);
}
public override string ToString ()
{
return field_list.ToString ();
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
public StringList FieldList
{
get {return new StringList (field_list);}
}
public StringType TextEncoding
{
get {return text_encoding;}
set {text_encoding = value;}
}
//////////////////////////////////////////////////////////////////////////
// protected methods
//////////////////////////////////////////////////////////////////////////
protected override void ParseFields (ByteVector data)
{
// read the string data type (the first byte of the field data)
text_encoding = (StringType) data [0];
field_list.Clear ();
field_list.Add (data.ToString (text_encoding, 1).Split (new char []{'\0'}));
}
protected override ByteVector RenderFields ()
{
ByteVector v = new ByteVector ((byte) text_encoding);
for (int i = 0; i < field_list.Count; i++)
{
// Since the field list is null delimited, if this is not the
// first element in the list, append the appropriate delimiter
// for this encoding.
if (i !=0)
v.Add (TextDelimiter (text_encoding));
v.Add (ByteVector.FromString (field_list [i], text_encoding));
}
return v;
}
protected internal TextIdentificationFrame (ByteVector data, int offset, FrameHeader h) : base (h)
{
field_list = new StringList ();
text_encoding = StringType.UTF8;
ParseFields (FieldData (data, offset));
}
}
public class UserTextIdentificationFrame : TextIdentificationFrame
{
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public UserTextIdentificationFrame (StringType encoding) : base ("TXXX", encoding)
{
StringList l = new StringList ();
l.Add ((string)null);
l.Add ((string)null);
base.SetText (l);
}
public UserTextIdentificationFrame (ByteVector data) : base (data)
{
CheckFields ();
}
public override string ToString ()
{
return "[" + Description + "] " + FieldList.ToString ();
}
public override void SetText (string text)
{
StringList l = new StringList (Description);
l.Add (text);
base.SetText (l);
}
new public void SetText (StringList fields)
{
StringList l = new StringList (Description);
l.Add (fields);
base.SetText (l);
}
public static UserTextIdentificationFrame Find (Tag tag, string description)
{
foreach (UserTextIdentificationFrame f in tag.GetFrames ("TXXX"))
if (f != null && f.Description == description)
return f;
return null;
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
public string Description
{
get {return !base.FieldList.IsEmpty ? base.FieldList [0] : null;}
set
{
StringList l = new StringList (base.FieldList);
if (l.IsEmpty)
l.Add (value);
else
l [0] = value;
base.SetText (l);
}
}
new public StringList FieldList
{
get
{
StringList l = new StringList (base.FieldList);
if (!l.IsEmpty)
l.RemoveAt (0);
return l;
}
}
//////////////////////////////////////////////////////////////////////////
// private methods
//////////////////////////////////////////////////////////////////////////
private void CheckFields ()
{
int fields = base.FieldList.Count;
if (fields == 0)
Description = "";
if(fields <= 1)
SetText ("");
}
//////////////////////////////////////////////////////////////////////////
// protected methods
//////////////////////////////////////////////////////////////////////////
protected internal UserTextIdentificationFrame (ByteVector data, int offset, FrameHeader h) : base (data, offset, h)
{
CheckFields ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inforigami.Regalo.Core
{
public class ConsoleLogger : ILogger
{
private readonly object _syncLock = new object();
private DateTime _lastLogDateTime;
public bool ShowDebugMessages { get; set; }
public TimeSpan QuietTime { get; set; }
public ConsoleLogger()
{
ShowDebugMessages = false;
QuietTime = TimeSpan.FromMinutes(1);
}
public void Debug(object sender, string format, params object[] args)
{
if (!ShowDebugMessages) return;
Write(sender, Severity.Debug, string.Format(format, args));
}
public void Info(object sender, string format, params object[] args)
{
Write(sender, Severity.Information, string.Format(format, args));
}
public void Warn(object sender, string format, params object[] args)
{
Write(sender, Severity.Warning, string.Format(format, args));
}
public void Error(object sender, Exception exception, string format, params object[] args)
{
var message = string.Format(format, args);
var exceptionText = GetExceptionReport(exception);
message += "\r\n" + exceptionText;
Write(sender, Severity.Exception, message);
}
public void Error(object sender, string format, params object[] args)
{
Write(sender, Severity.Error, string.Format(format, args));
}
private string GetExceptionReport(Exception exception)
{
var report = new StringBuilder("*** Exception Report ***").AppendLine();
var exceptions = GetExceptions(exception).Reverse().ToArray();
foreach (var ex in exceptions)
{
report.AppendLine(FormatException(ex));
if (ex != exceptions.Last())
{
report.AppendLine(" - Inner Exception of:").AppendLine();
}
else if(exceptions.Length > 1)
{
report.AppendLine(" (Top-most exception)");
}
}
return report.ToString();
}
private IEnumerable<Exception> GetExceptions(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
do
{
yield return exception;
} while ((exception = exception.InnerException) != null);
}
private string FormatException(Exception ex)
{
var result = new StringBuilder();
result.AppendFormat(" Type: \"{0}\"", ex.GetType().Name).AppendLine();
result.AppendFormat(" Message: \"{0}\"", ex.Message).AppendLine();
result.AppendFormat("{0}", ex.StackTrace).AppendLine();
return result.ToString();
}
private void Write(object sender, Severity severity, string message)
{
lock (_syncLock)
{
var timeSinceLastWrite = TimeSinceLastWrite();
if (timeSinceLastWrite > QuietTime)
{
WriteQuietTimeMessage(timeSinceLastWrite);
}
WriteTimestamp();
WriteDivider();
WriteSeverity(severity);
WriteDivider();
WriteSender(sender);
WriteDivider();
WriteMessage(message);
Console.WriteLine();
_lastLogDateTime = DateTime.Now;
}
}
private void WriteQuietTimeMessage(TimeSpan timeSinceLastWrite)
{
WriteText("<<<");
Console.WriteLine();
WriteTimeSinceLastWrite(timeSinceLastWrite);
Console.WriteLine();
WriteText(">>>");
Console.WriteLine();
Console.WriteLine();
}
private void WriteMessage(string message)
{
WriteText(message);
}
private void WriteSender(object sender)
{
var senderName = $"\"{sender.GetType().Name}\"";
WriteText(senderName);
}
private void WriteTimeSinceLastWrite(TimeSpan since)
{
WriteText($"Quiet period of {since}");
}
private void WriteTimestamp()
{
WriteText(DateTimeOffset.Now.ToString("s").Replace("T", " "), ConsoleColor.White, null);
}
private void WriteSeverity(Severity severity)
{
ConsoleColor foreground = Console.ForegroundColor;
ConsoleColor background = Console.BackgroundColor;
string severityName = "";
switch (severity)
{
case Severity.Debug:
foreground = ConsoleColor.Black;
background = ConsoleColor.Cyan;
severityName = "DEBUG";
break;
case Severity.Information:
foreground = ConsoleColor.White;
background = ConsoleColor.DarkGreen;
severityName = "INFO";
break;
case Severity.Warning:
foreground = ConsoleColor.White;
background = ConsoleColor.DarkYellow;
severityName = "WARN";
break;
case Severity.Error:
foreground = ConsoleColor.White;
background = ConsoleColor.Red;
severityName = "ERROR";
break;
case Severity.Exception:
foreground = ConsoleColor.White;
background = ConsoleColor.Red;
severityName = "PANIC";
break;
}
severityName = severityName.PadRight(5, ' ');
WriteText(severityName, foreground, background);
}
private void WriteDivider()
{
Console.Write('\t');
}
private void WriteText(string text, ConsoleColor? foreground, ConsoleColor? background)
{
var prevForeground = Console.ForegroundColor;
var prevBackground = Console.BackgroundColor;
try
{
Console.ForegroundColor = foreground ?? prevForeground;
Console.BackgroundColor = background ?? prevBackground;
WriteText(text);
}
finally
{
Console.ForegroundColor = prevForeground;
Console.BackgroundColor = prevBackground;
}
}
private void WriteText(string text)
{
Console.Write(text);
}
private TimeSpan TimeSinceLastWrite()
{
if (_lastLogDateTime > DateTime.MinValue)
{
return DateTime.Now - _lastLogDateTime;
}
return TimeSpan.Zero;
}
private enum Severity
{
Debug,
Information,
Warning,
Error,
Exception
}
}
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX.Dynamics
{
public class RigidBody : CollisionObject
{
private static float _linearAirDamping = 1;
//'temporarily' global variables
private static float _rigidBodyDeactivationTime = 2;
private static bool _disableDeactivation = false;
private static float _linearSleepingThreshold = 0.8f;
private static float _angularSleepingThreshold = 1.0f;
private static int _uniqueId = 0;
private Matrix _invInertiaTensorWorld;
private Vector3 _linearVelocity;
private Vector3 _angularVelocity;
private float _inverseMass;
private float _angularFactor;
private Vector3 _gravity;
private Vector3 _invInertiaLocal;
private Vector3 _totalForce;
private Vector3 _totalTorque;
private float _linearDamping;
private float _angularDamping;
//m_optionalMotionState allows to automatic synchronize the world transform for active objects
private MotionState _optionalMotionState;
//for experimental overriding of friction/contact solver func
private ContactSolverType _contactSolverType;
private ContactSolverType _frictionSolverType;
private int _debugBodyId;
//Bullet 2.20b has experimental damping code to reduce jitter just before objects fall asleep/deactivate
//doesn't work very well yet (value 0 disabled this damping)
//note there this influences deactivation thresholds!
private float _clippedAngvelThresholdSqr = 0.01f;
private float _clippedLinearThresholdSqr = 0.01f;
private float _jitterVelocityDampingFactor = 0.7f;
public RigidBody(float mass, MotionState motionState, CollisionShape collisionShape, Vector3 localInertia, float linearDamping, float angularDamping, float friction, float restitution)
{
_optionalMotionState = motionState;
_angularFactor = 1;
_angularDamping = 0.5f;
if (motionState != null)
{
motionState.GetWorldTransform(out _worldTransform);
}
else
{
WorldTransform = Matrix.Identity;
}
InterpolationWorldTransform = WorldTransform;
InterpolationLinearVelocity = new Vector3();
InterpolationAngularVelocity = new Vector3();
//moved to btCollisionObject
Friction = friction;
Restitution = restitution;
CollisionShape = collisionShape;
_debugBodyId = UniqueID++;
//m_internalOwner is to allow upcasting from collision object to rigid body
Owner = this;
SetMassProps(mass, localInertia);
SetDamping(linearDamping, angularDamping);
UpdateInertiaTensor();
}
public int DebugBodyID { get { return _debugBodyId; } set { _debugBodyId = value; } }
public ContactSolverType ContactSolverType { get { return _contactSolverType; } set { _contactSolverType = value; } }
public ContactSolverType FrictionSolverType { get { return _frictionSolverType; } set { _frictionSolverType = value; } }
public float AngularFactor { get { return _angularFactor; } set { _angularFactor = value; } }
//is this rigidbody added to a btCollisionWorld/btDynamicsWorld/btBroadphase?
public bool IsInWorld { get { return Broadphase != null; } }
public Vector3 Gravity
{
get { return _gravity; }
set
{
if (_inverseMass != 0.0f)
{
_gravity = value * (1.0f / _inverseMass);
}
}
}
public Matrix InvInertiaTensorWorld { get { return _invInertiaTensorWorld; } }
public float InverseMass { get { return _inverseMass; } }
public Vector3 InvInertiaDiagLocal { get { return _invInertiaLocal; } set { _invInertiaLocal = value; } }
public Vector3 CenterOfMassPosition { get { return WorldTransform.Translation; } }
public Quaternion Orientation { get { return Quaternion.CreateFromRotationMatrix(WorldTransform); } }
public Matrix CenterOfMassTransform
{
get { return WorldTransform; }
set
{
InterpolationWorldTransform = value;
InterpolationLinearVelocity = LinearVelocity;
InterpolationAngularVelocity = AngularVelocity;
WorldTransform = value;
UpdateInertiaTensor();
}
}
public Vector3 LinearVelocity
{
get { return _linearVelocity; }
set
{
if (CollisionFlags == CollisionOptions.StaticObject)
throw new BulletException("Static objects can't have linear velocity!");
_linearVelocity = value;
}
}
public Vector3 AngularVelocity
{
get { return _angularVelocity; }
set
{
if (CollisionFlags == CollisionOptions.StaticObject)
throw new BulletException("Static objects can't have angular velocity!");
_angularVelocity = value;
}
}
//MotionState allows to automatic synchronize the world transform for active objects
public MotionState MotionState
{
get { return _optionalMotionState; }
set
{
_optionalMotionState = value;
if (_optionalMotionState != null)
value.GetWorldTransform(out _worldTransform);
}
}
public static float LinearAirDamping { get { return _linearAirDamping; } set { _linearAirDamping = value; } }
public static float RigidBodyDeactivationTime { get { return _rigidBodyDeactivationTime; } set { _rigidBodyDeactivationTime = value; } }
public static bool DisableDeactivation { get { return _disableDeactivation; } set { _disableDeactivation = value; } }
public static float LinearSleepingThreshold { get { return _linearSleepingThreshold; } set { _linearSleepingThreshold = value; } }
public static float AngularSleepingThreshold { get { return _angularSleepingThreshold; } set { _angularSleepingThreshold = value; } }
public static int UniqueID { get { return _uniqueId; } set { _uniqueId = value; } }
public void ProceedToTransform(Matrix newTrans)
{
CenterOfMassTransform = newTrans;
}
//to keep collision detection and dynamics separate we don't store a rigidbody pointer
//but a rigidbody is derived from btCollisionObject, so we can safely perform an upcast
public static RigidBody Upcast(CollisionObject colObj)
{
return colObj.Owner as RigidBody;
}
// continuous collision detection needs prediction
public void PredictIntegratedTransform(float step, ref Matrix predictedTransform)
{
if ((_angularVelocity.LengthSquared() < _clippedAngvelThresholdSqr) &&
(_linearVelocity.LengthSquared() < _clippedLinearThresholdSqr))
{
_angularVelocity *= _jitterVelocityDampingFactor;
_linearVelocity *= _jitterVelocityDampingFactor;
}
TransformUtil.IntegrateTransform(WorldTransform, _linearVelocity, _angularVelocity, step, ref predictedTransform);
}
public void SaveKinematicState(float step)
{
//todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
if (step != 0)
{
//if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
if (MotionState != null)
MotionState.GetWorldTransform(out _worldTransform);
TransformUtil.CalculateVelocity(InterpolationWorldTransform, WorldTransform, step, ref _linearVelocity, ref _angularVelocity);
InterpolationLinearVelocity = _linearVelocity;
InterpolationAngularVelocity = _angularVelocity;
InterpolationWorldTransform = WorldTransform;
}
}
public void ApplyForces(float step)
{
if (IsStaticOrKinematicObject)
return;
ApplyCentralForce(_gravity);
_linearVelocity *= (1 - step * LinearAirDamping * _linearDamping) < 0.0f ? 0.0f : (1.0f < (1 - step * LinearAirDamping * _linearDamping) ? 1.0f : (1 - step * LinearAirDamping * _linearDamping));
_angularVelocity *= (1 - step * _angularDamping) < 0.0f ? 0.0f : (1.0f < (1 - step * _angularDamping) ? 1.0f : (1 - step * _angularDamping));
float speed = _linearVelocity.Length();
if (speed < _linearDamping)
{
float dampVel = 0.005f;
if (speed > dampVel)
{
Vector3 dir = _linearVelocity;
dir.Normalize();
_linearVelocity -= dir * dampVel;
}
else
{
_linearVelocity = new Vector3();
}
}
float angSpeed = _angularVelocity.Length();
if (angSpeed < _angularDamping)
{
float angDampVel = 0.005f;
if (angSpeed > angDampVel)
{
Vector3 dir = _angularVelocity;
dir.Normalize();
_angularVelocity -= dir * angDampVel;
}
else
{
_angularVelocity = new Vector3();
}
}
}
public void SetDamping(float linDamping, float angDamping)
{
_linearDamping = linDamping < 0.0f ? 0.0f : (1.0f < linDamping ? 1.0f : linDamping);
_angularDamping = angDamping < 0.0f ? 0.0f : (1.0f < angDamping ? 1.0f : angDamping);
}
public void SetMassProps(float mass, Vector3 inertia)
{
if (mass == 0)
{
CollisionFlags |= CollisionOptions.StaticObject;
_inverseMass = 0;
}
else
{
CollisionFlags &= (~CollisionOptions.StaticObject);
_inverseMass = 1.0f / mass;
}
_invInertiaLocal = new Vector3(inertia.X != 0.0f ? 1.0f / inertia.X : 0.0f,
inertia.Y != 0.0f ? 1.0f / inertia.Y : 0.0f,
inertia.Z != 0.0f ? 1.0f / inertia.Z : 0.0f);
}
public void IntegrateVelocities(float step)
{
if (IsStaticOrKinematicObject)
return;
_linearVelocity += _totalForce * (_inverseMass * step);
_angularVelocity += Vector3.TransformNormal(_totalTorque, _invInertiaTensorWorld) * step;
float MAX_ANGVEL = Microsoft.Xna.Framework.MathHelper.PiOver2;
/// clamp angular velocity. collision calculations will fail on higher angular velocities
float angvel = _angularVelocity.Length();
if (angvel * step > MAX_ANGVEL)
{
_angularVelocity *= (MAX_ANGVEL / step) / angvel;
}
ClearForces();
}
public void ApplyCentralForce(Vector3 force)
{
_totalForce += force;
}
public void ApplyTorque(Vector3 torque)
{
_totalTorque += torque;
}
public void ApplyForce(Vector3 force, Vector3 rel_pos)
{
ApplyCentralForce(force);
ApplyTorque(Vector3.Cross(rel_pos, force));
}
public void ApplyCentralImpulse(Vector3 impulse)
{
_linearVelocity += impulse * _inverseMass;
}
public void ApplyTorqueImpulse(Vector3 torque)
{
_angularVelocity += Vector3.TransformNormal(torque, _invInertiaTensorWorld);
}
public void ApplyImpulse(Vector3 impulse, Vector3 rel_pos)
{
if (_inverseMass != 0)
{
ApplyCentralImpulse(impulse);
if (_angularFactor != 0)
ApplyTorqueImpulse(Vector3.Cross(rel_pos, impulse) * _angularFactor);
}
}
public void InternalApplyImpulse(Vector3 linearComponent, Vector3 angularComponent, float impulseMagnitude)
{
if (_inverseMass != 0)
{
_linearVelocity += linearComponent * impulseMagnitude;
if (_angularFactor != 0)
_angularVelocity += angularComponent * impulseMagnitude * _angularFactor;
}
}
public void ClearForces()
{
_totalForce = new Vector3();
_totalTorque = new Vector3();
}
public void UpdateInertiaTensor()
{
Matrix temp = WorldTransform;
temp.Translation = Vector3.Zero;
_invInertiaTensorWorld = MatrixOperations.Multiply(MatrixOperations.Scaled(WorldTransform, _invInertiaLocal), Matrix.Transpose(temp));
}
public Vector3 GetVelocityInLocalPoint(Vector3 relPos)
{
//we also calculate lin/ang velocity for kinematic objects
return _linearVelocity + Vector3.Cross(_angularVelocity, relPos);
//for kinematic objects, we could also use use:
// return (m_worldTransform(rel_pos) - m_interpolationWorldTransform(rel_pos)) / m_kinematicTimeStep;
}
public void Translate(Vector3 v)
{
Matrix m = WorldTransform;
m.Translation += v;
WorldTransform = m;
}
public void GetAabb(out Vector3 aabbMin, out Vector3 aabbMax)
{
CollisionShape.GetAabb(WorldTransform, out aabbMin, out aabbMax);
}
public float ComputeImpulseDenominator(Vector3 pos, Vector3 normal)
{
Vector3 r0 = pos - CenterOfMassPosition;
Vector3 c0 = Vector3.Cross(r0, normal);
Vector3 vec = Vector3.Cross(Vector3.TransformNormal(c0, InvInertiaTensorWorld), r0);
return _inverseMass + Vector3.Dot(normal, vec);
}
public float ComputeAngularImpulseDenominator(Vector3 axis)
{
Vector3 vec = Vector3.TransformNormal(axis, InvInertiaTensorWorld);
return Vector3.Dot(axis, vec);
}
public void UpdateDeactivation(float timeStep)
{
if ((ActivationState == ActivationState.IslandSleeping) || (ActivationState == ActivationState.DisableDeactivation))
return;
if ((LinearVelocity.LengthSquared() < LinearSleepingThreshold * LinearSleepingThreshold) &&
(AngularVelocity.LengthSquared() < AngularSleepingThreshold * AngularSleepingThreshold))
{
DeactivationTime += timeStep;
}
else
{
DeactivationTime = 0;
ActivationState = ActivationState.Nothing;
}
}
public bool WantsSleeping()
{
if (ActivationState == ActivationState.DisableDeactivation)
return false;
//disable deactivation
if (DisableDeactivation || (RigidBodyDeactivationTime == 0))
return false;
if ((ActivationState == ActivationState.IslandSleeping) || (ActivationState == ActivationState.WantsDeactivation))
return true;
if (DeactivationTime > RigidBodyDeactivationTime)
{
return true;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Azure.Batch.Unit.Tests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BatchTestCommon;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Common;
using Microsoft.Azure.Batch.FileStaging;
using TestUtilities;
using Xunit;
using Xunit.Abstractions;
using Protocol = Microsoft.Azure.Batch.Protocol;
public class PropertyUnitTests
{
private readonly ITestOutputHelper testOutputHelper;
private readonly ObjectFactory defaultObjectFactory;
private readonly ObjectFactory customizedObjectFactory;
private readonly ObjectComparer objectComparer;
private readonly IList<ComparerPropertyMapping> proxyPropertyToObjectModelMapping;
private const int TestRunCount = 1000;
public PropertyUnitTests(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
//Define the factories
this.defaultObjectFactory = new ObjectFactory();
this.proxyPropertyToObjectModelMapping = new List<ComparerPropertyMapping>()
{
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "AutoScaleEnabled", "EnableAutoScale"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "VirtualMachineSize", "VmSize"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "Statistics", "Stats"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "VirtualMachineSize", "VmSize"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "AutoScaleEnabled", "EnableAutoScale"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "AutoScaleEnabled", "EnableAutoScale"),
new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "VirtualMachineSize", "VmSize"),
new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "MaxTasksPerComputeNode", "MaxTasksPerNode"),
new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"),
new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSFamily", "OsFamily"),
new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "TaskExecutionInformation"),
new ComparerPropertyMapping(typeof(AutoPoolSpecification), typeof(Protocol.Models.AutoPoolSpecification), "PoolSpecification", "Pool"),
new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeId", "NodeId"),
new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeUrl", "NodeUrl"),
new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobPreparationTaskExecutionInformation", "JobPreparationTaskExecutionInfo"),
new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobReleaseTaskExecutionInformation", "JobReleaseTaskExecutionInfo"),
new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "UsageStatistics", "UsageStats"),
new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "ResourceStatistics", "ResourceStats"),
new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "UserCpuTime", "UserCPUTime"),
new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "KernelCpuTime", "KernelCPUTime"),
new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "SucceededTaskCount", "NumSucceededTasks"),
new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "FailedTaskCount", "NumFailedTasks"),
new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "TaskRetryCount", "NumTaskRetries"),
new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "UserCpuTime", "UserCPUTime"),
new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "KernelCpuTime", "KernelCPUTime"),
new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "SucceededTaskCount", "NumSucceededTasks"),
new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "FailedTaskCount", "NumFailedTasks"),
new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "TaskRetryCount", "NumTaskRetries"),
new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageCpuPercentage", "AvgCPUPercentage"),
new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageMemoryGiB", "AvgMemoryGiB"),
new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageDiskGiB", "AvgDiskGiB"),
new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "UserCpuTime", "UserCPUTime"),
new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "KernelCpuTime", "KernelCPUTime"),
new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "PoolInformation", "PoolInfo"),
new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "ExecutionInformation", "ExecutionInfo"),
new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "Statistics", "Stats"),
new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.JobAddParameter), "PoolInformation", "PoolInfo"),
new ComparerPropertyMapping(typeof(JobSpecification), typeof(Protocol.Models.JobSpecification), "PoolInformation", "PoolInfo"),
new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "ExecutionInformation", "ExecutionInfo"),
new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "Statistics", "Stats"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "AffinityInformation", "AffinityInfo"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ExecutionInformation", "ExecutionInfo"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ComputeNodeInformation", "NodeInfo"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "Statistics", "Stats"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "AffinityInformation", "AffinityInfo"),
new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "ComputeNodeInformation", "NodeInfo"),
new ComparerPropertyMapping(typeof(ExitConditions), typeof(Protocol.Models.ExitConditions), "Default", "DefaultProperty"),
new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "ExecutionInfo"),
new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "IPAddress", "IpAddress"),
new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "VirtualMachineSize", "VmSize"),
new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "StartTaskInformation", "StartTaskInfo"),
new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeId", "NodeId"),
new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeUrl", "NodeUrl"),
new ComparerPropertyMapping(typeof(JobPreparationTask), typeof(Protocol.Models.JobPreparationTask), "RerunOnComputeNodeRebootAfterSuccess", "RerunOnNodeRebootAfterSuccess"),
new ComparerPropertyMapping(typeof(ImageReference), typeof(Protocol.Models.ImageReference), "SkuId", "Sku"),
new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "NodeAgentSkuId", "NodeAgentSKUId"),
new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "OSDisk", "OsDisk"),
new ComparerPropertyMapping(typeof(TaskSchedulingPolicy), typeof(Protocol.Models.TaskSchedulingPolicy), "ComputeNodeFillType", "NodeFillType"),
};
Random rand = new Random();
Func<object> omTaskRangeBuilder = () =>
{
int rangeLimit1 = rand.Next(0, int.MaxValue);
int rangeLimit2 = rand.Next(0, int.MaxValue);
return new TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2));
};
Func<object> iFileStagingProviderBuilder = () => null;
Func<object> batchClientBehaviorBuilder = () => null;
Func<object> taskRangeBuilder = () =>
{
int rangeLimit1 = rand.Next(0, int.MaxValue);
int rangeLimit2 = rand.Next(0, int.MaxValue);
return new Protocol.Models.TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2));
};
ObjectFactoryConstructionSpecification certificateReferenceSpecification = new ObjectFactoryConstructionSpecification(
typeof(Protocol.Models.CertificateReference),
() => BuildCertificateReference(rand));
ObjectFactoryConstructionSpecification authenticationTokenSettingsSpecification = new ObjectFactoryConstructionSpecification(
typeof(Protocol.Models.AuthenticationTokenSettings),
() => BuildAuthenticationTokenSettings(rand));
ObjectFactoryConstructionSpecification taskRangeSpecification = new ObjectFactoryConstructionSpecification(
typeof(Protocol.Models.TaskIdRange),
taskRangeBuilder);
ObjectFactoryConstructionSpecification omTaskRangeSpecification = new ObjectFactoryConstructionSpecification(
typeof(TaskIdRange),
omTaskRangeBuilder);
ObjectFactoryConstructionSpecification batchClientBehaviorSpecification = new ObjectFactoryConstructionSpecification(
typeof(BatchClientBehavior),
batchClientBehaviorBuilder);
ObjectFactoryConstructionSpecification fileStagingProviderSpecification = new ObjectFactoryConstructionSpecification(
typeof(IFileStagingProvider),
iFileStagingProviderBuilder);
this.customizedObjectFactory = new ObjectFactory(new List<ObjectFactoryConstructionSpecification>
{
certificateReferenceSpecification,
authenticationTokenSettingsSpecification,
taskRangeSpecification,
omTaskRangeSpecification,
fileStagingProviderSpecification,
batchClientBehaviorSpecification
});
// We need a custom comparison rule for certificate references because they are a different type in the proxy vs
// the object model (string in proxy, flags enum in OM
ComparisonRule certificateReferenceComparisonRule = ComparisonRule.Create<CertificateVisibility?, List<Protocol.Models.CertificateVisibility?>>(
typeof(CertificateReference),
typeof(Protocol.Models.CertificateReference), // This is the type that hold the target property
(visibility, proxyVisibility) =>
{
CertificateVisibility? convertedProxyVisibility = UtilitiesInternal.ParseCertificateVisibility(proxyVisibility);
//Treat null as None for the purposes of comparison:
bool areEqual = convertedProxyVisibility == visibility || !visibility.HasValue && convertedProxyVisibility == CertificateVisibility.None;
return areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("Certificate visibility doesn't match");
},
type1PropertyName: "Visibility",
type2PropertyName: "Visibility");
ComparisonRule accessScopeComparisonRule = ComparisonRule.Create<AccessScope, List<Protocol.Models.AccessScope?>>(
typeof(AuthenticationTokenSettings),
typeof(Protocol.Models.AuthenticationTokenSettings), // This is the type that hold the target property
(scope, proxyVisibility) =>
{
AccessScope convertedProxyVisibility = UtilitiesInternal.ParseAccessScope(proxyVisibility);
//Treat null as None for the purposes of comparison:
bool areEqual = convertedProxyVisibility == scope || convertedProxyVisibility == AccessScope.None;
return areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("AccessScope doesn't match");
},
type1PropertyName: "Access",
type2PropertyName: "Access");
this.objectComparer = new ObjectComparer(
comparisonRules: new List<ComparisonRule>() { certificateReferenceComparisonRule, accessScopeComparisonRule },
propertyMappings: this.proxyPropertyToObjectModelMapping,
shouldThrowOnPropertyReadException: e => !(e.InnerException is InvalidOperationException) || !e.InnerException.Message.Contains("while the object is in the Unbound"));
}
private Protocol.Models.CertificateReference BuildCertificateReference(Random rand)
{
//Build cert visibility (which is a required property)
IList values = Enum.GetValues(typeof(CertificateVisibility));
IList<object> valuesToSelect = new List<object>();
foreach (object value in values)
{
valuesToSelect.Add(value);
}
int valuesToPick = rand.Next(0, values.Count);
CertificateVisibility? visibility = null;
// If valuesToPick is 0, we want to allow visibility to be null (since null is a valid value)
// so only set visibility to be None if valuesToPick > 0
if (valuesToPick > 0)
{
visibility = CertificateVisibility.None;
for (int i = 0; i < valuesToPick; i++)
{
int selectedValueIndex = rand.Next(valuesToSelect.Count);
object selectedValue = valuesToSelect[selectedValueIndex];
visibility |= (CertificateVisibility)selectedValue;
valuesToSelect.RemoveAt(selectedValueIndex);
}
}
Protocol.Models.CertificateReference reference = this.defaultObjectFactory.GenerateNew<Protocol.Models.CertificateReference>();
//Set certificate visibility since it is required
reference.Visibility = visibility == null ? null : UtilitiesInternal.CertificateVisibilityToList(visibility.Value);
return reference;
}
private Protocol.Models.AuthenticationTokenSettings BuildAuthenticationTokenSettings(Random rand)
{
//Build access scope (which is a required property)
IList values = Enum.GetValues(typeof(AccessScope));
IList<object> valuesToSelect = new List<object>();
foreach (object value in values)
{
valuesToSelect.Add(value);
}
int valuesToPick = rand.Next(0, values.Count);
AccessScope? accessScope = null;
// If valuesToPick is 0, we want to allow access scope to be null (since null is a valid value)
// so only set access scope to be None if valuesToPick > 0
if (valuesToPick > 0)
{
accessScope = AccessScope.None;
for (int i = 0; i < valuesToPick; i++)
{
int selectedValueIndex = rand.Next(valuesToSelect.Count);
object selectedValue = valuesToSelect[selectedValueIndex];
accessScope |= (AccessScope)selectedValue;
valuesToSelect.RemoveAt(selectedValueIndex);
}
}
Protocol.Models.AuthenticationTokenSettings tokenSettings = this.defaultObjectFactory.GenerateNew<Protocol.Models.AuthenticationTokenSettings>();
//Set access scope since it is required
tokenSettings.Access = accessScope == null ? null : UtilitiesInternal.AccessScopeToList(accessScope.Value);
return tokenSettings;
}
#region Reflection based tests
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundCloudPoolProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.CloudPool poolModel =
this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudPool>();
CloudPool boundPool = new CloudPool(client, poolModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundPool, poolModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundCloudJobProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.CloudJob jobModel =
this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudJob>();
CloudJob boundJob = new CloudJob(client.JobOperations.ParentBatchClient, jobModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJob, jobModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundCloudJobScheduleProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.CloudJobSchedule jobScheduleModel =
this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudJobSchedule>();
CloudJobSchedule boundJobSchedule = new CloudJobSchedule(client, jobScheduleModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJobSchedule, jobScheduleModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundCloudTaskProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.CloudTask taskModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudTask>();
CloudTask boundTask = new CloudTask(client, "Foo", taskModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundTask, taskModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundComputeNodeProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.ComputeNode computeNodeModel =
this.customizedObjectFactory.GenerateNew<Protocol.Models.ComputeNode>();
ComputeNode boundComputeNode = new ComputeNode(client, "Foo", computeNodeModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundComputeNode, computeNodeModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundCertificateProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.Certificate certificateModel =
this.customizedObjectFactory.GenerateNew<Protocol.Models.Certificate>();
Certificate boundCertificate = new Certificate(client, certificateModel, client.CustomBehaviors);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundCertificate, certificateModel);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestRandomBoundPrepReleaseTaskExecutionInformationProperties()
{
using (BatchClient client = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
for (int i = 0; i < TestRunCount; i++)
{
Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation jobPrepReleaseExecutionInfo =
this.customizedObjectFactory.GenerateNew<Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation>();
JobPreparationAndReleaseTaskExecutionInformation boundJobPrepReleaseExecutionInfo =
new JobPreparationAndReleaseTaskExecutionInformation(jobPrepReleaseExecutionInfo);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJobPrepReleaseExecutionInfo, jobPrepReleaseExecutionInfo);
Assert.True(result.Equal, result.Message);
}
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestIReadOnlyMakesPropertiesReadOnly()
{
//Use reflection to traverse the set of objects in the DLL, find those that implement IReadOnly, and ensure that IReadOnly works for all
//properties of those objects.
Type iReadOnlyType = typeof(IReadOnly);
List<Type> typesWithIReadOnlyBase = GetTypesWhichImplementInterface(iReadOnlyType.GetTypeInfo().Assembly, iReadOnlyType, requirePublicConstructor: false).ToList();
foreach (Type type in typesWithIReadOnlyBase)
{
this.testOutputHelper.WriteLine("Reading/Setting properties of type: {0}", type.ToString());
//Create an instance of that type
IReadOnly objectUnderTest = this.customizedObjectFactory.CreateInstance<IReadOnly>(type);
//Mark this object as readonly
objectUnderTest.IsReadOnly = true;
//Get the properties for the object under test
IEnumerable<PropertyInfo> properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties.Where(p => p.Name != "CustomBehaviors"))
{
if (property.CanWrite)
{
this.testOutputHelper.WriteLine("Attempting to write property: {0}", property.Name);
//Attempt to write
//Note that for value types null is mapped to default(valueType). See: https://msdn.microsoft.com/en-us/library/xb5dd1f1%28v=vs.110%29.aspx
TargetInvocationException e = Assert.Throws<TargetInvocationException>(() => property.SetValue(objectUnderTest, null));
Assert.IsType<InvalidOperationException>(e.InnerException);
}
if (property.CanRead)
{
this.testOutputHelper.WriteLine("Attempting to read property: {0}", property.Name);
//Attempt to read
try
{
property.GetValue(objectUnderTest);
}
catch (TargetInvocationException e)
{
var inner = e.InnerException as InvalidOperationException;
if (inner != null)
{
if (!inner.Message.Contains("while the object is in the Unbound state"))
{
throw;
}
}
else
{
throw;
}
}
}
}
this.testOutputHelper.WriteLine(string.Empty);
}
Assert.True(typesWithIReadOnlyBase.Count > 0);
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestGetTransportObjectDoesntMissProperties()
{
const int objectsToValidate = 100;
//Use reflection to traverse the set of objects in the DLL, find those that implement ITransportObjectProvider, ensure that GetTransportObject works for all
//properties of those objects.
Type iTransportObjectProviderType = typeof(ITransportObjectProvider<>);
IEnumerable<Type> types = GetTypesWhichImplementInterface(iTransportObjectProviderType.GetTypeInfo().Assembly, iTransportObjectProviderType, requirePublicConstructor: false);
foreach (Type type in types)
{
this.testOutputHelper.WriteLine("Generating {0} objects of type {1}", objectsToValidate, type);
for (int i = 0; i < objectsToValidate; i++)
{
object o = this.customizedObjectFactory.GenerateNew(type);
Type concreteInterfaceType = o.GetType().GetInterfaces().First(iFace =>
iFace.GetTypeInfo().IsGenericType &&
iFace.GetGenericTypeDefinition() == iTransportObjectProviderType);
//object protocolObject = concreteInterfaceType.GetMethod("GetTransportObject").Invoke(o, BindingFlags.Instance | BindingFlags.NonPublic, null, null, null);
object protocolObject = concreteInterfaceType.GetMethod("GetTransportObject").Invoke(o, null);
ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(o, protocolObject);
Assert.True(result.Equal, result.Message);
}
}
}
private static IEnumerable<Type> GetTypesWhichImplementInterface(Assembly assembly, Type interfaceType, bool requirePublicConstructor)
{
Func<Type, bool> requirePublicConstructorFunc;
if (requirePublicConstructor)
{
requirePublicConstructorFunc = (t => t.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Any());
}
else
{
requirePublicConstructorFunc = (t => true);
}
if (!interfaceType.GetTypeInfo().IsGenericType)
{
return assembly.GetTypes().Where(t =>
interfaceType.IsAssignableFrom(t) &&
!t.GetTypeInfo().IsInterface &&
t.GetTypeInfo().IsVisible &&
requirePublicConstructorFunc(t));
}
else
{
return assembly.GetTypes().Where(t =>
t.GetInterfaces().Any(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == interfaceType) &&
!t.GetTypeInfo().IsInterface &&
t.GetTypeInfo().IsVisible &&
requirePublicConstructorFunc(t));
}
}
#endregion
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void Bug1432987CloudTaskTaskConstraints()
{
using (BatchClient batchCli = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
{
CloudTask badTask = new CloudTask("bug1432987TaskConstraints", "hostname");
TaskConstraints isThisBroken = badTask.Constraints;
TaskConstraints trySettingThem = new TaskConstraints(null, null, null);
badTask.Constraints = trySettingThem;
TaskConstraints readThemBack = badTask.Constraints;
}
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestCertificateReferenceVisibilityGet()
{
CertificateReference certificateReference = new CertificateReference();
Assert.Null(certificateReference.Visibility);
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestResourceFilePropertiesArePropagatedToTransportObject()
{
const string filePath = "Foo";
const string blobPath = "Bar";
const string mode = "0700";
ResourceFile resourceFile = new ResourceFile(blobPath, filePath, mode);
Protocol.Models.ResourceFile protoFile = resourceFile.GetTransportObject();
Assert.Equal(filePath, protoFile.FilePath);
Assert.Equal(blobPath, protoFile.BlobSource);
Assert.Equal(mode, protoFile.FileMode);
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestAutoPoolSpecificationUnboundConstraints()
{
const string idPrefix = "Bar";
const bool keepAlive = false;
const PoolLifetimeOption poolLifetimeOption = PoolLifetimeOption.Job;
PoolSpecification poolSpecification = new PoolSpecification();
AutoPoolSpecification autoPoolSpecification = new AutoPoolSpecification();
//Properties should start out as their defaults
Assert.Equal(default(string), autoPoolSpecification.AutoPoolIdPrefix);
Assert.Equal(default(bool?), autoPoolSpecification.KeepAlive);
Assert.Equal(default(PoolLifetimeOption), autoPoolSpecification.PoolLifetimeOption);
Assert.Equal(default(PoolSpecification), autoPoolSpecification.PoolSpecification);
Assert.False(((IModifiable)autoPoolSpecification).HasBeenModified);
//Should be able to set all properties
autoPoolSpecification.AutoPoolIdPrefix = idPrefix;
autoPoolSpecification.KeepAlive = keepAlive;
autoPoolSpecification.PoolLifetimeOption = poolLifetimeOption;
autoPoolSpecification.PoolSpecification = poolSpecification;
Assert.True(((IModifiable)autoPoolSpecification).HasBeenModified);
Protocol.Models.AutoPoolSpecification protoAutoPoolSpecification = autoPoolSpecification.GetTransportObject();
((IReadOnly)autoPoolSpecification).IsReadOnly = true; //Forces read-onlyness
//After MarkReadOnly, the original object should be unsettable
Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.AutoPoolIdPrefix = "bar");
Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.KeepAlive = false);
Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.PoolLifetimeOption = PoolLifetimeOption.JobSchedule);
InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.PoolSpecification = new PoolSpecification());
this.testOutputHelper.WriteLine(e.ToString());
//After GetProtocolObject, the child objects should be unreadable too
Assert.Throws<InvalidOperationException>(() => poolSpecification.MaxTasksPerComputeNode = 4);
//The original data should be on the protocol specification
Assert.Equal(idPrefix, protoAutoPoolSpecification.AutoPoolIdPrefix);
Assert.Equal(keepAlive, protoAutoPoolSpecification.KeepAlive);
Assert.Equal(poolLifetimeOption, UtilitiesInternal.MapEnum<Protocol.Models.PoolLifetimeOption, PoolLifetimeOption>(protoAutoPoolSpecification.PoolLifetimeOption));
}
[Fact]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void TestAutoPoolSpecificationBoundConstraints()
{
Protocol.Models.AutoPoolSpecification protoAutoPoolSpecification = new Protocol.Models.AutoPoolSpecification
{
KeepAlive = true,
PoolLifetimeOption = Protocol.Models.PoolLifetimeOption.JobSchedule,
AutoPoolIdPrefix = "Matt",
Pool = new Protocol.Models.PoolSpecification
{
CloudServiceConfiguration = new Protocol.Models.CloudServiceConfiguration(
"4"),
ResizeTimeout = TimeSpan.FromDays(1),
StartTask = new Protocol.Models.StartTask
{
CommandLine = "Bar"
}
}
};
AutoPoolSpecification autoPoolSpecification = new AutoPoolSpecification(protoAutoPoolSpecification);
//Assert that the wrapped properties are equal as we expect
Assert.Equal(protoAutoPoolSpecification.AutoPoolIdPrefix, autoPoolSpecification.AutoPoolIdPrefix);
Assert.Equal(protoAutoPoolSpecification.KeepAlive, autoPoolSpecification.KeepAlive);
Assert.Equal(UtilitiesInternal.MapEnum<Protocol.Models.PoolLifetimeOption, PoolLifetimeOption>(protoAutoPoolSpecification.PoolLifetimeOption), autoPoolSpecification.PoolLifetimeOption);
Assert.NotNull(autoPoolSpecification.PoolSpecification);
Assert.NotNull(protoAutoPoolSpecification.Pool.CloudServiceConfiguration);
Assert.Equal(protoAutoPoolSpecification.Pool.CloudServiceConfiguration.OsFamily, autoPoolSpecification.PoolSpecification.CloudServiceConfiguration.OSFamily);
Assert.Equal(protoAutoPoolSpecification.Pool.ResizeTimeout, autoPoolSpecification.PoolSpecification.ResizeTimeout);
Assert.NotNull(autoPoolSpecification.PoolSpecification.StartTask);
Assert.Equal(protoAutoPoolSpecification.Pool.StartTask.CommandLine, autoPoolSpecification.PoolSpecification.StartTask.CommandLine);
//When we change a property on the underlying object PoolSpecification, AutoPoolSpecification should notice the change
Assert.False(((IModifiable)autoPoolSpecification).HasBeenModified);
autoPoolSpecification.PoolSpecification.ResizeTimeout = TimeSpan.FromSeconds(122);
Assert.True(((IModifiable)autoPoolSpecification).HasBeenModified);
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Placement
{
internal class ActivationCountPlacementDirector : RandomPlacementDirector, ISiloStatisticsChangeListener
{
private class CachedLocalStat
{
public SiloAddress Address { get; private set; }
public SiloRuntimeStatistics SiloStats { get; private set; }
public int ActivationCount { get { return activationCount; } }
private int activationCount;
internal CachedLocalStat(SiloAddress address, SiloRuntimeStatistics siloStats)
{
Address = address;
SiloStats = siloStats;
}
public void IncrementActivationCount(int delta)
{
Interlocked.Add(ref activationCount, delta);
}
}
// internal for unit tests
internal Func<PlacementStrategy, GrainId, IPlacementContext, Task<PlacementResult>> SelectSilo;
// Track created activations on this silo between statistic intervals.
private readonly ConcurrentDictionary<SiloAddress, CachedLocalStat> localCache = new ConcurrentDictionary<SiloAddress, CachedLocalStat>();
private readonly TraceLogger logger;
private readonly bool useLocalCache = true;
// For: SelectSiloPowerOfK
private readonly SafeRandom random = new SafeRandom();
private int chooseHowMany = 2;
public ActivationCountPlacementDirector()
{
logger = TraceLogger.GetLogger(this.GetType().Name);
}
public void Initialize(GlobalConfiguration globalConfig)
{
DeploymentLoadPublisher.Instance.SubscribeToStatisticsChangeEvents(this);
SelectSilo = SelectSiloPowerOfK;
if (globalConfig.ActivationCountBasedPlacementChooseOutOf <= 0)
throw new ArgumentException("GlobalConfig.ActivationCountBasedPlacementChooseOutOf is " + globalConfig.ActivationCountBasedPlacementChooseOutOf);
chooseHowMany = globalConfig.ActivationCountBasedPlacementChooseOutOf;
}
private static bool IsSiloOverloaded(SiloRuntimeStatistics stats)
{
return stats.IsOverloaded || stats.CpuUsage >= 100;
}
private int SiloLoad_ByActivations(CachedLocalStat cachedStats)
{
return useLocalCache ?
cachedStats.ActivationCount + cachedStats.SiloStats.ActivationCount :
cachedStats.SiloStats.ActivationCount;
}
private int SiloLoad_ByRecentActivations(CachedLocalStat cachedStats)
{
return useLocalCache ?
cachedStats.ActivationCount + cachedStats.SiloStats.RecentlyUsedActivationCount :
cachedStats.SiloStats.RecentlyUsedActivationCount;
}
private Task<PlacementResult> MakePlacement(PlacementStrategy strategy, GrainId grain, IPlacementContext context, CachedLocalStat minLoadedSilo)
{
// Increment placement by number of silos instead of by one.
// This is our trick to get more balanced placement, accounting to the probable
// case when multiple silos place on the same silo at the same time, before stats are refreshed.
minLoadedSilo.IncrementActivationCount(localCache.Count);
return Task.FromResult(PlacementResult.SpecifyCreation(
minLoadedSilo.Address,
strategy,
context.GetGrainTypeName(grain)));
}
public Task<PlacementResult> SelectSiloPowerOfK(PlacementStrategy strategy, GrainId grain, IPlacementContext context)
{
// Exclude overloaded silos
var relevantSilos = new List<CachedLocalStat>();
foreach (CachedLocalStat current in localCache.Values)
{
if (IsSiloOverloaded(current.SiloStats)) continue;
relevantSilos.Add(current);
}
if (relevantSilos.Count > 0)
{
int chooseFrom = Math.Min(relevantSilos.Count, chooseHowMany);
var chooseFromThoseSilos = new List<CachedLocalStat>();
while (chooseFromThoseSilos.Count < chooseFrom)
{
int index = random.Next(relevantSilos.Count);
var pickedSilo = relevantSilos[index];
relevantSilos.RemoveAt(index);
chooseFromThoseSilos.Add(pickedSilo);
}
CachedLocalStat minLoadedSilo = chooseFromThoseSilos.First();
foreach (CachedLocalStat s in chooseFromThoseSilos)
{
if (SiloLoad_ByRecentActivations(s) < SiloLoad_ByRecentActivations(minLoadedSilo))
minLoadedSilo = s;
}
return MakePlacement(strategy, grain, context, minLoadedSilo);
}
var debugLog = string.Format("Unable to select a candidate from {0} silos: {1}", localCache.Count,
Utils.EnumerableToString(
localCache,
kvp => String.Format("SiloAddress = {0} -> {1}", kvp.Key.ToString(), kvp.Value.ToString())));
logger.Warn(ErrorCode.Placement_ActivationCountBasedDirector_NoSilos, debugLog);
throw new OrleansException(debugLog);
}
/// <summary>
/// Selects the best match from list of silos, updates local statistics.
/// </summary>
/// <note>
/// This is equivalent with SelectSiloPowerOfK() with chooseHowMany = #Silos
/// </note>
private Task<PlacementResult> SelectSiloGreedy(PlacementStrategy strategy, GrainId grain, IPlacementContext context)
{
int minLoad = int.MaxValue;
CachedLocalStat minLoadedSilo = null;
foreach (CachedLocalStat current in localCache.Values)
{
if (IsSiloOverloaded(current.SiloStats)) continue;
int load = SiloLoad_ByRecentActivations(current);
if (load >= minLoad) continue;
minLoadedSilo = current;
minLoad = load;
}
if (minLoadedSilo != null)
return MakePlacement(strategy, grain, context, minLoadedSilo);
var debugLog = string.Format("Unable to select a candidate from {0} silos: {1}", localCache.Count,
Utils.EnumerableToString(
localCache,
kvp => String.Format("SiloAddress = {0} -> {1}", kvp.Key.ToString(), kvp.Value.ToString())));
logger.Warn(ErrorCode.Placement_ActivationCountBasedDirector_NoSilos, debugLog);
throw new OrleansException(debugLog);
}
internal override Task<PlacementResult> OnAddActivation(
PlacementStrategy strategy, GrainId grain, IPlacementContext context)
{
return SelectSilo(strategy, grain, context);
}
public void SiloStatisticsChangeNotification(SiloAddress updatedSilo, SiloRuntimeStatistics newSiloStats)
{
// just create a new empty CachedLocalStat and throw the old one.
var updatedCacheEntry = new CachedLocalStat(updatedSilo, newSiloStats);
localCache.AddOrUpdate(updatedSilo, k => updatedCacheEntry, (k, v) => updatedCacheEntry);
}
public void RemoveSilo(SiloAddress removedSilo)
{
CachedLocalStat ignore;
localCache.TryRemove(removedSilo, out ignore);
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// .NET Compact Framework 1.0 has no support for System.Web.Mail
// SSCLI 1.0 has no support for System.Web.Mail
#if !NETCF && !SSCLI
using System;
using System.IO;
#if NET_2_0
using System.Net.Mail;
#else
using System.Web.Mail;
#endif
using log4net.Layout;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Send an e-mail when a specific logging event occurs, typically on errors
/// or fatal errors.
/// </summary>
/// <remarks>
/// <para>
/// The number of logging events delivered in this e-mail depend on
/// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
/// <see cref="SmtpAppender"/> keeps only the last
/// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its
/// cyclic buffer. This keeps memory requirements at a reasonable level while
/// still delivering useful application context.
/// </para>
/// <note type="caution">
/// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime.
/// For these features to be enabled you need to ensure that you are using a version of
/// the log4net assembly that is built against the MS .NET 1.1 framework and that you are
/// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending
/// unauthenticated messages to a server listening on port 25 (the default) is supported.
/// </note>
/// <para>
/// Authentication is supported by setting the <see cref="Authentication"/> property to
/// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
/// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
/// and <see cref="Password"/> properties must also be set.
/// </para>
/// <para>
/// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class SmtpAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public SmtpAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string To
{
get { return m_to; }
set { m_to = value; }
}
/// <summary>
/// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses
/// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions).
/// </summary>
/// <value>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </value>
/// <remarks>
/// <para>
/// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
/// </para>
/// <para>
/// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
/// </para>
/// </remarks>
public string Cc
{
get { return m_cc; }
set { m_cc = value; }
}
/// <summary>
/// Gets or sets a semicolon-delimited list of recipient e-mail addresses
/// that will be blind carbon copied.
/// </summary>
/// <value>
/// A semicolon-delimited list of e-mail addresses.
/// </value>
/// <remarks>
/// <para>
/// A semicolon-delimited list of recipient e-mail addresses.
/// </para>
/// </remarks>
public string Bcc
{
get { return m_bcc; }
set { m_bcc = value; }
}
/// <summary>
/// Gets or sets the e-mail address of the sender.
/// </summary>
/// <value>
/// The e-mail address of the sender.
/// </value>
/// <remarks>
/// <para>
/// The e-mail address of the sender.
/// </para>
/// </remarks>
public string From
{
get { return m_from; }
set { m_from = value; }
}
/// <summary>
/// Gets or sets the subject line of the e-mail message.
/// </summary>
/// <value>
/// The subject line of the e-mail message.
/// </value>
/// <remarks>
/// <para>
/// The subject line of the e-mail message.
/// </para>
/// </remarks>
public string Subject
{
get { return m_subject; }
set { m_subject = value; }
}
/// <summary>
/// Gets or sets the name of the SMTP relay mail server to use to send
/// the e-mail messages.
/// </summary>
/// <value>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </value>
/// <remarks>
/// <para>
/// The name of the e-mail relay server. If SmtpServer is not set, the
/// name of the local SMTP server is used.
/// </para>
/// </remarks>
public string SmtpHost
{
get { return m_smtpHost; }
set { m_smtpHost = value; }
}
/// <summary>
/// Obsolete
/// </summary>
/// <remarks>
/// Use the BufferingAppenderSkeleton Fix methods instead
/// </remarks>
/// <remarks>
/// <para>
/// Obsolete property.
/// </para>
/// </remarks>
[Obsolete("Use the BufferingAppenderSkeleton Fix methods")]
public bool LocationInfo
{
get { return false; }
set { ; }
}
/// <summary>
/// The mode to use to authentication with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>,
/// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>.
/// The default value is <see cref="SmtpAuthentication.None"/>. When using
/// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/>
/// and <see cref="Password"/> to use to authenticate.
/// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
/// thread, if impersonating, or the process will be used to authenticate.
/// </para>
/// </remarks>
public SmtpAuthentication Authentication
{
get { return m_authentication; }
set { m_authentication = value; }
}
/// <summary>
/// The username to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the username will be ignored.
/// </para>
/// </remarks>
public string Username
{
get { return m_username; }
set { m_username = value; }
}
/// <summary>
/// The password to use to authenticate with the SMTP server
/// </summary>
/// <remarks>
/// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// A <see cref="Username"/> and <see cref="Password"/> must be specified when
/// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>,
/// otherwise the password will be ignored.
/// </para>
/// </remarks>
public string Password
{
get { return m_password; }
set { m_password = value; }
}
/// <summary>
/// The port on which the SMTP server is listening
/// </summary>
/// <remarks>
/// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note>
/// <para>
/// The port on which the SMTP server is listening. The default
/// port is <c>25</c>. The Port can only be changed when running on
/// the MS .NET 1.1 runtime.
/// </para>
/// </remarks>
public int Port
{
get { return m_port; }
set { m_port = value; }
}
/// <summary>
/// Gets or sets the priority of the e-mail message
/// </summary>
/// <value>
/// One of the <see cref="MailPriority"/> values.
/// </value>
/// <remarks>
/// <para>
/// Sets the priority of the e-mails generated by this
/// appender. The default priority is <see cref="MailPriority.Normal"/>.
/// </para>
/// <para>
/// If you are using this appender to report errors then
/// you may want to set the priority to <see cref="MailPriority.High"/>.
/// </para>
/// </remarks>
public MailPriority Priority
{
get { return m_mailPriority; }
set { m_mailPriority = value; }
}
#if NET_2_0
/// <summary>
/// Enable or disable use of SSL when sending e-mail message
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public bool EnableSsl
{
get { return m_enableSsl; }
set { m_enableSsl = value; }
}
/// <summary>
/// Gets or sets the reply-to e-mail address.
/// </summary>
/// <remarks>
/// This is available on MS .NET 2.0 runtime and higher
/// </remarks>
public string ReplyTo
{
get { return m_replyTo; }
set { m_replyTo = value; }
}
#endif
#endregion // Public Instance Properties
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Sends the contents of the cyclic buffer as an e-mail message.
/// </summary>
/// <param name="events">The logging events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for(int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
SendEmail(writer.ToString());
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
#endregion // Override implementation of BufferingAppenderSkeleton
#region Override implementation of AppenderSkeleton
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // Override implementation of AppenderSkeleton
#region Protected Methods
/// <summary>
/// Send the email message
/// </summary>
/// <param name="messageBody">the body text to include in the mail</param>
virtual protected void SendEmail(string messageBody)
{
#if NET_2_0
// .NET 2.0 has a new API for SMTP email System.Net.Mail
// This API supports credentials and multiple hosts correctly.
// The old API is deprecated.
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (!String.IsNullOrEmpty(m_smtpHost))
{
smtpClient.Host = m_smtpHost;
}
smtpClient.Port = m_port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = m_enableSsl;
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Body = messageBody;
mailMessage.From = new MailAddress(m_from);
mailMessage.To.Add(m_to);
if (!String.IsNullOrEmpty(m_cc))
{
mailMessage.CC.Add(m_cc);
}
if (!String.IsNullOrEmpty(m_bcc))
{
mailMessage.Bcc.Add(m_bcc);
}
if (!String.IsNullOrEmpty(m_replyTo))
{
// .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
// 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !NET_4_0
mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
}
mailMessage.Subject = m_subject;
mailMessage.Priority = m_mailPriority;
// TODO: Consider using SendAsync to send the message without blocking. This would be a change in
// behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors.
smtpClient.Send(mailMessage);
}
#else
// .NET 1.x uses the System.Web.Mail API for sending Mail
MailMessage mailMessage = new MailMessage();
mailMessage.Body = messageBody;
mailMessage.From = m_from;
mailMessage.To = m_to;
if (m_cc != null && m_cc.Length > 0)
{
mailMessage.Cc = m_cc;
}
if (m_bcc != null && m_bcc.Length > 0)
{
mailMessage.Bcc = m_bcc;
}
mailMessage.Subject = m_subject;
mailMessage.Priority = m_mailPriority;
#if NET_1_1
// The Fields property on the MailMessage allows the CDO properties to be set directly.
// This property is only available on .NET Framework 1.1 and the implementation must understand
// the CDO properties. For details of the fields available in CDO see:
//
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp
//
try
{
if (m_authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password);
}
else if (m_authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2);
}
// Set the port if not the default value
if (m_port != 25)
{
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port);
}
}
catch(MissingMethodException missingMethodException)
{
// If we were compiled against .NET 1.1 but are running against .NET 1.0 then
// we will get a MissingMethodException when accessing the MailMessage.Fields property.
ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException);
}
#else
if (m_authentication != SmtpAuthentication.None)
{
ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
if (m_port != 25)
{
ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
}
#endif // if NET_1_1
if (m_smtpHost != null && m_smtpHost.Length > 0)
{
SmtpMail.SmtpServer = m_smtpHost;
}
SmtpMail.Send(mailMessage);
#endif // if NET_2_0
}
#endregion // Protected Methods
#region Private Instance Fields
private string m_to;
private string m_cc;
private string m_bcc;
private string m_from;
private string m_subject;
private string m_smtpHost;
// authentication fields
private SmtpAuthentication m_authentication = SmtpAuthentication.None;
private string m_username;
private string m_password;
// server port, default port 25
private int m_port = 25;
private MailPriority m_mailPriority = MailPriority.Normal;
#if NET_2_0
private bool m_enableSsl = false;
private string m_replyTo;
#endif
#endregion // Private Instance Fields
#region SmtpAuthentication Enum
/// <summary>
/// Values for the <see cref="SmtpAppender.Authentication"/> property.
/// </summary>
/// <remarks>
/// <para>
/// SMTP authentication modes.
/// </para>
/// </remarks>
public enum SmtpAuthentication
{
/// <summary>
/// No authentication
/// </summary>
None,
/// <summary>
/// Basic authentication.
/// </summary>
/// <remarks>
/// Requires a username and password to be supplied
/// </remarks>
Basic,
/// <summary>
/// Integrated authentication
/// </summary>
/// <remarks>
/// Uses the Windows credentials from the current thread or process to authenticate.
/// </remarks>
Ntlm
}
#endregion // SmtpAuthentication Enum
}
}
#endif // !NETCF && !SSCLI
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//
// Presharp uses the c# pragma mechanism to supress its warnings.
// These are not recognised by the base compiler so we need to explictly
// disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp
// for details.
//
#pragma warning disable 1634, 1691 // unknown message, unknown pragma
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// Wraps and manages the lifetime of a native crypto handle passed back from the native InfoCard API.
//
internal abstract class CryptoHandle : IDisposable
{
bool m_isDisposed;
InternalRefCountedHandle m_internalHandle;
//
// Summary:
// Creates a new CryptoHandle. ParamType has information as to what
// nativeParameters has to be marshaled into.
//
protected CryptoHandle(InternalRefCountedHandle nativeHandle, DateTime expiration, IntPtr nativeParameters, Type paramType)
{
m_internalHandle = nativeHandle;
m_internalHandle.Initialize(expiration, Marshal.PtrToStructure(nativeParameters, paramType));
}
//
// Summary:
// This constructor creates a new CryptoHandle instance with the same InternalRefCountedHandle and adds
// a ref count to that InternalRefCountedHandle.
//
protected CryptoHandle(InternalRefCountedHandle internalHandle)
{
m_internalHandle = internalHandle;
m_internalHandle.AddRef();
}
public InternalRefCountedHandle InternalHandle
{
get
{
ThrowIfDisposed();
return m_internalHandle;
}
}
public DateTime Expiration
{
get
{
ThrowIfDisposed();
return m_internalHandle.Expiration;
}
}
public object Parameters
{
get
{
ThrowIfDisposed();
return m_internalHandle.Parameters;
}
}
//
// Summary:
// Creates a new CryptoHandle with same InternalRefCountedCryptoHandle.
//
public CryptoHandle Duplicate()
{
ThrowIfDisposed();
return OnDuplicate();
}
//
// Summary:
// Allows subclasses to create a duplicate of their particular class.
//
protected abstract CryptoHandle OnDuplicate();
protected void ThrowIfDisposed()
{
if (m_isDisposed)
{
throw IDT.ThrowHelperError(new ObjectDisposedException(SR.GetString(SR.ClientCryptoSessionDisposed)));
}
}
public void Dispose()
{
if (m_isDisposed)
{
return;
}
m_internalHandle.Release();
m_internalHandle = null;
m_isDisposed = true;
}
//
// Summary:
// Given a pointer to a native cryptosession this method creates the appropriate CryptoHandle type.
//
static internal CryptoHandle Create(InternalRefCountedHandle nativeHandle)
{
CryptoHandle handle = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
nativeHandle.DangerousAddRef(ref mustRelease);
RpcInfoCardCryptoHandle hCrypto =
(RpcInfoCardCryptoHandle)Marshal.PtrToStructure(nativeHandle.DangerousGetHandle(),
typeof(RpcInfoCardCryptoHandle));
DateTime expiration = DateTime.FromFileTimeUtc(hCrypto.expiration);
switch (hCrypto.type)
{
case RpcInfoCardCryptoHandle.HandleType.Asymmetric:
handle = new AsymmetricCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Symmetric:
handle = new SymmetricCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Transform:
handle = new TransformCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Hash:
handle = new HashCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
default:
IDT.DebugAssert(false, "Invalid crypto operation type");
throw IDT.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.GeneralExceptionMessage)));
}
return handle;
}
finally
{
if (mustRelease)
{
nativeHandle.DangerousRelease();
}
}
}
}
//
// Summary:
// This class manages the lifetime of a native crypto handle through ref counts. Any number of CryptoHandles
// may refer to a single InternalRefCountedHandle, but once they are all disposed this object will dispose
// itself as well.
//
internal class InternalRefCountedHandle : SafeHandle
{
int m_refcount = 0;
DateTime m_expiration;
object m_parameters = null;
[DllImport("infocardapi.dll",
EntryPoint = "CloseCryptoHandle",
CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall,
ExactSpelling = true,
SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool CloseCryptoHandle([In] IntPtr hKey);
private InternalRefCountedHandle()
: base(IntPtr.Zero, true)
{
m_refcount = 1;
}
public void Initialize(DateTime expiration, object parameters)
{
m_expiration = expiration;
m_parameters = parameters;
}
//
// Summary:
// The deserialized parameters specific to a particular type of CryptoHandle.
//
public object Parameters
{
get
{
ThrowIfInvalid();
return m_parameters;
}
}
//
// Summary:
// The expiration of this CryptoHandle
//
public DateTime Expiration
{
get
{
ThrowIfInvalid();
return m_expiration;
}
}
public void AddRef()
{
ThrowIfInvalid();
Interlocked.Increment(ref m_refcount);
}
public void Release()
{
ThrowIfInvalid();
int refcount = Interlocked.Decrement(ref m_refcount);
if (0 == refcount)
{
Dispose();
}
}
private void ThrowIfInvalid()
{
if (IsInvalid)
{
throw IDT.ThrowHelperError(new ObjectDisposedException("InternalRefCountedHandle"));
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
protected override bool ReleaseHandle()
{
#pragma warning suppress 56523
return CloseCryptoHandle(base.handle);
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
namespace Eto.Forms
{
/// <summary>
/// Interface to access common properties of both <see cref="MenuItem"/> and <see cref="ToolItem"/>.
/// </summary>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface ICommandItem
{
/// <summary>
/// Occurs when the user clicks on the item.
/// </summary>
event EventHandler<EventArgs> Click;
/// <summary>
/// Gets or sets the text of the item, with mnemonic.
/// </summary>
/// <value>The text.</value>
string Text { get; set; }
/// <summary>
/// Gets or sets the tool tip to show when hovering the mouse over the item.
/// </summary>
/// <value>The tool tip.</value>
string ToolTip { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.ICommandItem"/> is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
bool Enabled { get; set; }
}
/// <summary>
/// Base class for items in a menu
/// </summary>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public abstract class MenuItem : Menu, ICommandItem
{
/// <summary>
/// Gets or sets the order that the menu item should use when inserted into a submenu.
/// </summary>
/// <remarks>
/// The order can be used to sort your menu items when added in a different order.
///
/// This is useful when you have menu items added from different areas of your program.
/// </remarks>
/// <value>The order to use when inserting into the submenu.</value>
public int Order { get; set; }
static readonly object Command_Key = new object();
/// <summary>
/// Gets or sets the command to invoke when the menu item is pressed.
/// </summary>
/// <remarks>
/// This will invoke the specified command when the menu item is pressed.
/// The <see cref="ICommand.CanExecute"/> will also used to set the enabled/disabled state of the menu item.
/// </remarks>
/// <value>The command to invoke.</value>
public ICommand Command
{
get { return Properties.GetCommand(Command_Key); }
set { Properties.SetCommand(Command_Key, value, e => Enabled = e, r => Click += r, r => Click -= r); }
}
new IHandler Handler { get { return (IHandler)base.Handler; } }
/// <summary>
/// Occurs when the user clicks or selects the menu item.
/// </summary>
public event EventHandler<EventArgs> Click;
/// <summary>
/// Raises the <see cref="Click"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="Validate"/> event.
/// </summary>
public const string ValidateEvent = "MenuActionItem.ValidateEvent";
/// <summary>
/// Occurs when the menu item is validated.
/// </summary>
/// <remarks>
/// This is used to allow enabling/disabling items before they are shown to the user.
/// Usually, platforms will call validate on all items each time they are shown in a submenu or context menu.
/// </remarks>
public event EventHandler<EventArgs> Validate
{
add { Properties.AddHandlerEvent(ValidateEvent, value); }
remove { Properties.RemoveEvent(ValidateEvent, value); }
}
/// <summary>
/// Raises the <see cref="Validate"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnValidate(EventArgs e)
{
Properties.TriggerEvent(ValidateEvent, this, e);
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.MenuItem"/> class.
/// </summary>
protected MenuItem()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.MenuItem"/> class with the specified command.
/// </summary>
/// <remarks>
/// This links the menu item with the specified command, and will trigger <see cref="Eto.Forms.Command.Execute"/>
/// when the user clicks the item, and enable/disable the menu item based on <see cref="Eto.Forms.Command.Enabled"/>.
///
/// This is not a weak link, so you should not re-use the Command instance for other menu items if you are disposing
/// this menu item.
/// </remarks>
/// <param name="command">Command to initialize the menu item with.</param>
protected MenuItem(Command command)
{
ID = command.ID;
Text = command.MenuText;
ToolTip = command.ToolTip;
Shortcut = command.Shortcut;
Validate += (sender, e) => Enabled = command.Enabled;
Command = command;
}
static MenuItem()
{
EventLookup.Register<MenuItem>(c => c.OnValidate(null), MenuItem.ValidateEvent);
}
/// <summary>
/// Gets or sets the text of the menu item, with mnemonics identified with &.
/// </summary>
/// <value>The text with mnemonic of the menu item.</value>
public string Text
{
get { return Handler.Text; }
set { Handler.Text = value; }
}
/// <summary>
/// Gets or sets a user-defined tag for the menu item.
/// </summary>
/// <value>The user-defined tag.</value>
public object Tag { get; set; }
/// <summary>
/// Gets or sets the tool tip of the item.
/// </summary>
/// <value>The tool tip.</value>
public string ToolTip
{
get { return Handler.ToolTip; }
set { Handler.ToolTip = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.MenuItem"/> is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
public bool Enabled
{
get { return Handler.Enabled; }
set { Handler.Enabled = value; }
}
/// <summary>
/// Gets or sets the shortcut key the user can press to activate the menu item.
/// </summary>
/// <value>The shortcut key.</value>
public Keys Shortcut
{
get { return Handler.Shortcut; }
set { Handler.Shortcut = value; }
}
/// <summary>
/// Callback interface for the <see cref="MenuItem"/>
/// </summary>
public new interface ICallback : Menu.ICallback
{
/// <summary>
/// Raises the click event.
/// </summary>
void OnClick(MenuItem widget, EventArgs e);
/// <summary>
/// Raises the validate event.
/// </summary>
void OnValidate(MenuItem widget, EventArgs e);
}
/// <summary>
/// Callback implementation for the <see cref="MenuItem"/>
/// </summary>
protected class Callback : ICallback
{
/// <summary>
/// Raises the click event.
/// </summary>
public void OnClick(MenuItem widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnClick(e));
}
/// <summary>
/// Raises the validate event.
/// </summary>
public void OnValidate(MenuItem widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnValidate(e));
}
}
static readonly object callback = new Callback();
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <returns>The callback.</returns>
protected override object GetCallback()
{
return callback;
}
/// <summary>
/// Handler interface for the <see cref="MenuItem"/>
/// </summary>
public new interface IHandler : Menu.IHandler
{
/// <summary>
/// Gets or sets the shortcut key the user can press to activate the menu item.
/// </summary>
/// <value>The shortcut key.</value>
Keys Shortcut { get; set; }
/// <summary>
/// Called when creating the menu item from a command.
/// </summary>
/// <remarks>
/// This is used primarily when creating menu items for system commands that the platform returns
/// via <see cref="MenuBar.SystemCommands"/>.
/// </remarks>
/// <param name="command">Command the menu item is created with.</param>
void CreateFromCommand(Command command);
/// <summary>
/// Gets or sets the text of the menu item, with mnemonics identified with &.
/// </summary>
/// <value>The text with mnemonic of the menu item.</value>
string Text { get; set; }
/// <summary>
/// Gets or sets the tool tip of the item.
/// </summary>
/// <value>The tool tip.</value>
string ToolTip { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.MenuItem"/> is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
bool Enabled { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using LibGit2Sharp.Core;
using Xunit;
namespace LibGit2Sharp.Tests.TestHelpers
{
public class BaseFixture : IPostTestDirectoryRemover, IDisposable
{
private readonly List<string> directories = new List<string>();
#if LEAKS_IDENTIFYING
public BaseFixture()
{
LeaksContainer.Clear();
}
#endif
static BaseFixture()
{
// Do the set up in the static ctor so it only happens once
SetUpTestEnvironment();
}
public static string BareTestRepoPath { get; private set; }
public static string StandardTestRepoWorkingDirPath { get; private set; }
public static string StandardTestRepoPath { get; private set; }
public static string ShallowTestRepoPath { get; private set; }
public static string MergedTestRepoWorkingDirPath { get; private set; }
public static string MergeTestRepoWorkingDirPath { get; private set; }
public static string MergeRenamesTestRepoWorkingDirPath { get; private set; }
public static string RevertTestRepoWorkingDirPath { get; private set; }
public static string SubmoduleTestRepoWorkingDirPath { get; private set; }
private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; }
private static string AssumeUnchangedRepoWorkingDirPath { get; set; }
public static string SubmoduleSmallTestRepoWorkingDirPath { get; set; }
public static DirectoryInfo ResourcesDirectory { get; private set; }
public static bool IsFileSystemCaseSensitive { get; private set; }
protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto)
{
int seconds = dto.ToSecondsSinceEpoch();
return Epoch.ToDateTimeOffset(seconds, (int) dto.Offset.TotalMinutes);
}
private static void SetUpTestEnvironment()
{
IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal();
const string sourceRelativePath = @"../../Resources";
ResourcesDirectory = new DirectoryInfo(sourceRelativePath);
// Setup standard paths to our test repositories
BareTestRepoPath = Path.Combine(sourceRelativePath, "testrepo.git");
StandardTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "testrepo_wd");
StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git");
ShallowTestRepoPath = Path.Combine(sourceRelativePath, "shallow.git");
MergedTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergedrepo_wd");
MergeRenamesTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergerenames_wd");
MergeTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "merge_testrepo_wd");
RevertTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "revert_testrepo_wd");
SubmoduleTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_wd");
SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_target_wd");
AssumeUnchangedRepoWorkingDirPath = Path.Combine(sourceRelativePath, "assume_unchanged_wd");
SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_small_wd");
CleanupTestReposOlderThan(TimeSpan.FromMinutes(15));
}
private static void CleanupTestReposOlderThan(TimeSpan olderThan)
{
var oldTestRepos = new DirectoryInfo(Constants.TemporaryReposPath)
.EnumerateDirectories()
.Where(di => di.CreationTimeUtc < DateTimeOffset.Now.Subtract(olderThan))
.Select(di => di.FullName);
foreach (var dir in oldTestRepos)
{
DirectoryHelper.DeleteDirectory(dir);
}
}
private static bool IsFileSystemCaseSensitiveInternal()
{
var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName());
if (Directory.Exists(mixedPath))
{
Directory.Delete(mixedPath);
}
Directory.CreateDirectory(mixedPath);
bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant());
Directory.Delete(mixedPath);
return !isInsensitive;
}
protected void CreateCorruptedDeadBeefHead(string repoPath)
{
const string deadbeef = "deadbeef";
string headPath = string.Format("refs/heads/{0}", deadbeef);
Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef));
}
protected SelfCleaningDirectory BuildSelfCleaningDirectory()
{
return new SelfCleaningDirectory(this);
}
protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path)
{
return new SelfCleaningDirectory(this, path);
}
protected string SandboxBareTestRepo()
{
return Sandbox(BareTestRepoPath);
}
protected string SandboxStandardTestRepo()
{
return Sandbox(StandardTestRepoWorkingDirPath);
}
protected string SandboxMergedTestRepo()
{
return Sandbox(MergedTestRepoWorkingDirPath);
}
protected string SandboxStandardTestRepoGitDir()
{
return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath));
}
protected string SandboxMergeTestRepo()
{
return Sandbox(MergeTestRepoWorkingDirPath);
}
protected string SandboxRevertTestRepo()
{
return Sandbox(RevertTestRepoWorkingDirPath);
}
public string SandboxSubmoduleTestRepo()
{
return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath);
}
public string SandboxAssumeUnchangedTestRepo()
{
return Sandbox(AssumeUnchangedRepoWorkingDirPath);
}
public string SandboxSubmoduleSmallTestRepo()
{
var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath);
Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd"));
return path;
}
protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths)
{
var scd = BuildSelfCleaningDirectory();
var source = new DirectoryInfo(sourceDirectoryPath);
var clonePath = Path.Combine(scd.DirectoryPath, source.Name);
DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath));
foreach (var additionalPath in additionalSourcePaths)
{
var additional = new DirectoryInfo(additionalPath);
var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name);
DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional));
}
return clonePath;
}
protected string InitNewRepository(bool isBare = false)
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
return Repository.Init(scd.DirectoryPath, isBare);
}
protected Repository InitIsolatedRepository(string path = null, bool isBare = false, RepositoryOptions options = null)
{
path = path ?? InitNewRepository(isBare);
options = BuildFakeConfigs(BuildSelfCleaningDirectory(), options);
return new Repository(path, options);
}
public void Register(string directoryPath)
{
directories.Add(directoryPath);
}
public virtual void Dispose()
{
foreach (string directory in directories)
{
DirectoryHelper.DeleteDirectory(directory);
}
#if LEAKS_IDENTIFYING
GC.Collect();
GC.WaitForPendingFinalizers();
if (LeaksContainer.TypeNames.Any())
{
Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}"
+ "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in SafeHandleBase.cs{1}"
+ "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine));
}
#endif
}
protected static void InconclusiveIf(Func<bool> predicate, string message)
{
if (!predicate())
{
return;
}
throw new SkipException(message);
}
protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion)
{
Type type = Type.GetType("Mono.Runtime");
if (type == null)
{
// We're running on top of .Net
return;
}
MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
if (displayName == null)
{
throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method.");
}
var version = (string) displayName.Invoke(null, null);
System.Version current;
try
{
current = new System.Version(version.Split(' ')[0]);
}
catch (Exception e)
{
throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e);
}
InconclusiveIf(() => current < minimumVersion,
string.Format(
"Current Mono version is {0}. Minimum required version to run this test is {1}.",
current, minimumVersion));
}
protected static void AssertValueInConfigFile(string configFilePath, string regex)
{
var text = File.ReadAllText(configFilePath);
var r = new Regex(regex, RegexOptions.Multiline).Match(text);
Assert.True(r.Success, text);
}
public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null)
{
options = BuildFakeRepositoryOptions(scd, options);
StringBuilder sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = global{0}", Environment.NewLine)
.AppendFormat("[Wow]{0}", Environment.NewLine)
.AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine);
File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString());
sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = system{0}", Environment.NewLine);
File.WriteAllText(options.SystemConfigurationLocation, sb.ToString());
sb = new StringBuilder()
.AppendFormat("[Woot]{0}", Environment.NewLine)
.AppendFormat("this-rocks = xdg{0}", Environment.NewLine);
File.WriteAllText(options.XdgConfigurationLocation, sb.ToString());
return options;
}
private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirectory scd, RepositoryOptions options = null)
{
options = options ?? new RepositoryOptions();
string confs = Path.Combine(scd.DirectoryPath, "confs");
Directory.CreateDirectory(confs);
options.GlobalConfigurationLocation = Path.Combine(confs, "my-global-config");
options.XdgConfigurationLocation = Path.Combine(confs, "my-xdg-config");
options.SystemConfigurationLocation = Path.Combine(confs, "my-system-config");
return options;
}
/// <summary>
/// Creates a configuration file with user.name and user.email set to signature
/// </summary>
/// <remarks>The configuration file will be removed automatically when the tests are finished</remarks>
/// <param name="signature">The signature to use for user.name and user.email</param>
/// <returns>The path to the configuration file</returns>
protected string CreateConfigurationWithDummyUser(Signature signature)
{
return CreateConfigurationWithDummyUser(signature.Name, signature.Email);
}
protected string CreateConfigurationWithDummyUser(string name, string email)
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
string configFilePath = Touch(scd.DirectoryPath, "fake-config");
using (Configuration config = Configuration.BuildFrom(configFilePath))
{
if (name != null)
{
config.Set("user.name", name);
}
if (email != null)
{
config.Set("user.email", email);
}
}
return configFilePath;
}
/// <summary>
/// Asserts that the commit has been authored and committed by the specified signature
/// </summary>
/// <param name="commit">The commit</param>
/// <param name="signature">The signature to compare author and commiter to</param>
protected void AssertCommitSignaturesAre(Commit commit, Signature signature)
{
Assert.Equal(signature.Name, commit.Author.Name);
Assert.Equal(signature.Email, commit.Author.Email);
Assert.Equal(signature.Name, commit.Committer.Name);
Assert.Equal(signature.Email, commit.Committer.Email);
}
protected static string Touch(string parent, string file, string content = null, Encoding encoding = null)
{
string filePath = Path.Combine(parent, file);
string dir = Path.GetDirectoryName(filePath);
Debug.Assert(dir != null);
Directory.CreateDirectory(dir);
File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII);
return filePath;
}
protected static string Touch(string parent, string file, Stream stream)
{
Debug.Assert(stream != null);
string filePath = Path.Combine(parent, file);
string dir = Path.GetDirectoryName(filePath);
Debug.Assert(dir != null);
Directory.CreateDirectory(dir);
using (var fs = File.Open(filePath, FileMode.Create))
{
CopyStream(stream, fs);
fs.Flush();
}
return filePath;
}
protected string Expected(string filename)
{
return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename));
}
protected string Expected(string filenameFormat, params object[] args)
{
return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args));
}
protected static void AssertRefLogEntry(IRepository repo, string canonicalName,
string message, ObjectId @from, ObjectId to,
Identity committer, DateTimeOffset before)
{
var reflogEntry = repo.Refs.Log(canonicalName).First();
Assert.Equal(to, reflogEntry.To);
Assert.Equal(message, reflogEntry.Message);
Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From);
Assert.Equal(committer.Email, reflogEntry.Committer.Email);
Assert.InRange(reflogEntry.Committer.When, before, DateTimeOffset.Now);
}
protected static void EnableRefLog(IRepository repository, bool enable = true)
{
repository.Config.Set("core.logAllRefUpdates", enable);
}
public static void CopyStream(Stream input, Stream output)
{
// Reused from the following Stack Overflow post with permission
// of Jon Skeet (obtained on 25 Feb 2013)
// http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
public static bool StreamEquals(Stream one, Stream two)
{
int onebyte, twobyte;
while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0)
{
if (onebyte != twobyte)
return false;
}
return true;
}
public void AssertBelongsToARepository<T>(IRepository repo, T instance)
where T : IBelongToARepository
{
Assert.Same(repo, ((IBelongToARepository)instance).Repository);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Orleans.Metadata;
using Orleans.Runtime;
using Orleans.Utilities;
namespace Orleans
{
/// <summary>
/// Associates <see cref="GrainInterfaceType"/>s with a compatible <see cref="GrainType"/>.
/// </summary>
/// <remarks>
/// This is primarily intended for end-users calling <see cref="IGrainFactory"/> methods without needing to be overly explicit.
/// </remarks>
public class GrainInterfaceTypeToGrainTypeResolver
{
private readonly object _lockObj = new object();
private readonly ConcurrentDictionary<GrainInterfaceType, GrainType> _genericMapping = new ConcurrentDictionary<GrainInterfaceType, GrainType>();
private readonly IClusterManifestProvider _clusterManifestProvider;
private Cache _cache;
/// <summary>
/// Creates a new instance of the <see cref="GrainInterfaceTypeToGrainTypeResolver"/> class.
/// </summary>
/// <param name="clusterManifestProvider">The cluster manifest provider.</param>
public GrainInterfaceTypeToGrainTypeResolver(IClusterManifestProvider clusterManifestProvider)
{
_clusterManifestProvider = clusterManifestProvider;
}
/// <summary>
/// Returns the <see cref="GrainType"/> which supports the provided <see cref="GrainInterfaceType"/> and which has an implementing type name beginning with the provided prefix string.
/// </summary>
public GrainType GetGrainType(GrainInterfaceType interfaceType, string prefix)
{
if (string.IsNullOrWhiteSpace(prefix))
{
return GetGrainType(interfaceType);
}
GrainType result = default;
GrainInterfaceType lookupType;
if (GenericGrainInterfaceType.TryParse(interfaceType, out var genericInterface))
{
lookupType = genericInterface.GetGenericGrainType().Value;
}
else
{
lookupType = interfaceType;
}
var cache = GetCache();
if (cache.Map.TryGetValue(lookupType, out var entry))
{
var hasCandidate = false;
foreach (var impl in entry.Implementations)
{
if (impl.Prefix.StartsWith(prefix, StringComparison.Ordinal))
{
if (impl.Prefix.Length == prefix.Length)
{
// Exact matches take precedence
result = impl.GrainType;
break;
}
if (hasCandidate)
{
var candidates = string.Join(", ", entry.Implementations.Select(i => $"{i.GrainType} ({i.Prefix})"));
throw new ArgumentException($"Unable to identify a single appropriate grain type for interface {interfaceType} with implementation prefix \"{prefix}\". Candidates: {candidates}");
}
result = impl.GrainType;
hasCandidate = true;
}
}
}
if (result.IsDefault)
{
throw new ArgumentException($"Could not find an implementation matching prefix \"{prefix}\" for interface {interfaceType}");
}
if (GenericGrainType.TryParse(result, out var genericGrainType) && !genericGrainType.IsConstructed)
{
result = genericGrainType.GrainType.GetConstructed(genericInterface.Value);
}
return result;
}
/// <summary>
/// Returns a <see cref="GrainType"/> which implements the provided <see cref="GrainInterfaceType"/>.
/// </summary>
public GrainType GetGrainType(GrainInterfaceType interfaceType)
{
GrainType result = default;
var cache = GetCache();
if (cache.Map.TryGetValue(interfaceType, out var entry))
{
if (!entry.PrimaryImplementation.IsDefault)
{
result = entry.PrimaryImplementation;
}
else if (entry.Implementations.Count == 1)
{
result = entry.Implementations[0].GrainType;
}
else if (entry.Implementations.Count > 1)
{
var candidates = string.Join(", ", entry.Implementations.Select(i => $"{i.GrainType} ({i.Prefix})"));
throw new ArgumentException($"Unable to identify a single appropriate grain type for interface {interfaceType}. Candidates: {candidates}");
}
else
{
// No implementations
}
}
else if (_genericMapping.TryGetValue(interfaceType, out result))
{
}
else if (GenericGrainInterfaceType.TryParse(interfaceType, out var genericInterface))
{
var unconstructedInterface = genericInterface.GetGenericGrainType();
var unconstructed = GetGrainType(unconstructedInterface.Value);
if (GenericGrainType.TryParse(unconstructed, out var genericGrainType))
{
if (genericGrainType.IsConstructed)
{
result = genericGrainType.GrainType;
}
else
{
result = genericGrainType.GrainType.GetConstructed(genericInterface.Value);
}
}
else
{
result = unconstructed;
}
_genericMapping[interfaceType] = result;
}
if (result.IsDefault)
{
throw new ArgumentException($"Could not find an implementation for interface {interfaceType}");
}
return result;
}
/// <summary>
/// Returns the cache, rebuilding it if it is out of date.
/// </summary>
/// <returns>The cache.</returns>
private Cache GetCache()
{
if (_cache is Cache cache && cache.Version == _clusterManifestProvider.Current.Version)
{
return cache;
}
lock (_lockObj)
{
var manifest = _clusterManifestProvider.Current;
cache = _cache;
if (cache is object && cache.Version == manifest.Version)
{
return cache;
}
return _cache = BuildCache(manifest);
}
}
/// <summary>
/// Builds a cached resolution mapping.
/// </summary>
/// <param name="clusterManifest">The current cluster manifest.</param>
/// <returns>The cache.</returns>
private static Cache BuildCache(ClusterManifest clusterManifest)
{
var result = new Dictionary<GrainInterfaceType, CacheEntry>();
foreach (var manifest in clusterManifest.AllGrainManifests)
{
GrainType knownPrimary = default;
foreach (var grainInterface in manifest.Interfaces)
{
var id = grainInterface.Key;
if (grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.DefaultGrainType, out var defaultTypeString))
{
knownPrimary = GrainType.Create(defaultTypeString);
continue;
}
}
foreach (var grainType in manifest.Grains)
{
var id = grainType.Key;
grainType.Value.Properties.TryGetValue(WellKnownGrainTypeProperties.TypeName, out var typeName);
grainType.Value.Properties.TryGetValue(WellKnownGrainTypeProperties.FullTypeName, out var fullTypeName);
foreach (var property in grainType.Value.Properties)
{
if (!property.Key.StartsWith(WellKnownGrainTypeProperties.ImplementedInterfacePrefix, StringComparison.Ordinal)) continue;
var implemented = GrainInterfaceType.Create(property.Value);
string interfaceTypeName;
if (manifest.Interfaces.TryGetValue(implemented, out var interfaceProperties))
{
interfaceProperties.Properties.TryGetValue(WellKnownGrainInterfaceProperties.TypeName, out interfaceTypeName);
}
else
{
interfaceTypeName = null;
}
// Try to work out the best primary implementation
result.TryGetValue(implemented, out var entry);
GrainType primaryImplementation;
if (!knownPrimary.IsDefault)
{
primaryImplementation = knownPrimary;
}
else if (!entry.PrimaryImplementation.IsDefault)
{
primaryImplementation = entry.PrimaryImplementation;
}
else if (string.Equals(interfaceTypeName?.Substring(1), typeName, StringComparison.Ordinal))
{
primaryImplementation = id;
}
else
{
primaryImplementation = default;
}
var implementations = entry.Implementations ?? new List<(string Prefix, GrainType GrainType)>();
if (!implementations.Contains((fullTypeName, id))) implementations.Add((fullTypeName, id));
result[implemented] = new CacheEntry(primaryImplementation, implementations);
}
}
}
return new Cache(clusterManifest.Version, result);
}
/// <summary>
/// Contains a mapping from grain interface type to the implementations of that interface.
/// </summary>
private class Cache
{
/// <summary>
/// Initializes a new instance of the <see cref="Cache"/> class.
/// </summary>
/// <param name="version">The cluster manifest version which this instance corresponds to.</param>
/// <param name="map">The interface map.</param>
public Cache(MajorMinorVersion version, Dictionary<GrainInterfaceType, CacheEntry> map)
{
this.Version = version;
this.Map = map;
}
/// <summary>
/// Gets the cluster manifest version which this cache corresponds to.
/// </summary>
public MajorMinorVersion Version { get; }
/// <summary>
/// Gets the mapping from grain interface type to implementations.
/// </summary>
public Dictionary<GrainInterfaceType, CacheEntry> Map { get; }
}
/// <summary>
/// Represents the implementation <see cref="GrainType"/> values for a grain interface type.
/// </summary>
private readonly struct CacheEntry
{
/// <summary>
/// Initializes a new instance of the <see cref="CacheEntry"/> struct.
/// </summary>
/// <param name="primaryImplementation">The primary implementation type.</param>
/// <param name="implementations">The set of other implementations along with their grain type prefixes.</param>
public CacheEntry(GrainType primaryImplementation, List<(string Prefix, GrainType GrainType)> implementations)
{
this.PrimaryImplementation = primaryImplementation;
this.Implementations = implementations;
}
/// <summary>
/// Gets the primary implementation type.
/// </summary>
public GrainType PrimaryImplementation { get; }
/// <summary>
/// Gets the collection of implementation types with their class name prefixes.
/// </summary>
public List<(string Prefix, GrainType GrainType)> Implementations { get; }
}
}
}
| |
// GtkSharp.Generation.OpaqueGen.cs - The Opaque Generatable.
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2003 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 GtkSharp.Generation {
using System;
using System.Collections;
using System.IO;
using System.Xml;
public class OpaqueGen : HandleBase {
public OpaqueGen (XmlElement ns, XmlElement elem) : base (ns, elem) {}
public override string FromNative(string var, bool owned)
{
return var + " == IntPtr.Zero ? null : (" + QualifiedName + ") GLib.Opaque.GetOpaque (" + var + ", typeof (" + QualifiedName + "), " + (owned ? "true" : "false") + ")";
}
private bool DisableRawCtor {
get {
return Elem.HasAttribute ("disable_raw_ctor");
}
}
public override void Generate (GenerationInfo gen_info)
{
gen_info.CurrentType = Name;
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name);
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ("\tusing System.Collections;");
sw.WriteLine ("\tusing System.Runtime.InteropServices;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
SymbolTable table = SymbolTable.Table;
Method ref_, unref, dispose;
GetSpecialMethods (out ref_, out unref, out dispose);
if (IsDeprecated)
sw.WriteLine ("\t[Obsolete]");
sw.Write ("\t{0} class " + Name, IsInternal ? "internal" : "public");
string cs_parent = table.GetCSType(Elem.GetAttribute("parent"));
if (cs_parent != "")
sw.Write (" : " + cs_parent);
else
sw.Write (" : GLib.Opaque");
foreach (string iface in managed_interfaces) {
if (Parent != null && Parent.Implements (iface))
continue;
sw.Write (", " + iface);
}
sw.WriteLine (" {");
sw.WriteLine ();
GenFields (gen_info);
GenMethods (gen_info, null, null);
GenCtors (gen_info);
if (ref_ != null) {
ref_.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Ref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned) {");
sw.WriteLine ("\t\t\t\t" + ref_.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = true;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (ref_.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
if (ref_.ReturnType == "void")
sw.WriteLine ("\t\tpublic void Ref () {}");
else
sw.WriteLine ("\t\tpublic " + Name + " Ref () { return this; }");
sw.WriteLine ();
}
}
bool finalizer_needed = false;
if (unref != null) {
unref.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Unref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (Owned) {");
sw.WriteLine ("\t\t\t\t" + unref.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (unref.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
sw.WriteLine ("\t\tpublic void Unref () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (dispose != null) {
dispose.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Free (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\t" + dispose.CName + " (raw);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (dispose.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now freed automatically\")]");
sw.WriteLine ("\t\tpublic void " + dispose.Name + " () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (finalizer_needed) {
sw.WriteLine ("\t\tclass FinalizerInfo {");
sw.WriteLine ("\t\t\tIntPtr handle;");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic FinalizerInfo (IntPtr handle)");
sw.WriteLine ("\t\t\t{");
sw.WriteLine ("\t\t\t\tthis.handle = handle;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic bool Handler ()");
sw.WriteLine ("\t\t\t{");
if (dispose != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", dispose.CName);
else if (unref != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", unref.CName);
sw.WriteLine ("\t\t\t\treturn false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t~{0} ()", Name);
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned)");
sw.WriteLine ("\t\t\t\treturn;");
sw.WriteLine ("\t\t\tFinalizerInfo info = new FinalizerInfo (Handle);");
sw.WriteLine ("\t\t\tGLib.Timeout.Add (50, new GLib.TimeoutHandler (info.Handler));");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#if false
Method copy = Methods ["Copy"] as Method;
if (copy != null && copy.Parameters.Count == 0) {
sw.WriteLine ("\t\tprotected override GLib.Opaque Copy (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tGLib.Opaque result = new " + QualifiedName + " (" + copy.CName + " (raw));");
sw.WriteLine ("\t\t\tresult.Owned = true;");
sw.WriteLine ("\t\t\treturn result;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#endif
sw.WriteLine ("#endregion");
AppendCustom(sw, gen_info.CustomDir);
sw.WriteLine ("\t}");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = null;
Statistics.OpaqueCount++;
}
void GetSpecialMethods (out Method ref_, out Method unref, out Method dispose)
{
ref_ = CheckSpecialMethod (GetMethod ("Ref"));
unref = CheckSpecialMethod (GetMethod ("Unref"));
dispose = GetMethod ("Free");
if (dispose == null) {
dispose = GetMethod ("Destroy");
if (dispose == null)
dispose = GetMethod ("Dispose");
}
dispose = CheckSpecialMethod (dispose);
}
Method CheckSpecialMethod (Method method)
{
if (method == null)
return null;
if (method.ReturnType != "void" &&
method.ReturnType != QualifiedName)
return null;
if (method.Signature.ToString () != "")
return null;
methods.Remove (method.Name);
return method;
}
protected override void GenCtors (GenerationInfo gen_info)
{
if (!DisableRawCtor) {
gen_info.Writer.WriteLine("\t\tpublic " + Name + "(IntPtr raw) : base(raw) {}");
gen_info.Writer.WriteLine();
}
base.GenCtors (gen_info);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Avalonia.Data;
using Avalonia.Diagnostics;
using Avalonia.Logging;
using Avalonia.PropertyStore;
using Avalonia.Threading;
namespace Avalonia
{
/// <summary>
/// An object with <see cref="AvaloniaProperty"/> support.
/// </summary>
/// <remarks>
/// This class is analogous to DependencyObject in WPF.
/// </remarks>
public class AvaloniaObject : IAvaloniaObject, IAvaloniaObjectDebug, INotifyPropertyChanged, IValueSink
{
private IAvaloniaObject _inheritanceParent;
private List<IDisposable> _directBindings;
private PropertyChangedEventHandler _inpcChanged;
private EventHandler<AvaloniaPropertyChangedEventArgs> _propertyChanged;
private List<IAvaloniaObject> _inheritanceChildren;
private ValueStore _values;
private ValueStore Values => _values ?? (_values = new ValueStore(this));
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaObject"/> class.
/// </summary>
public AvaloniaObject()
{
VerifyAccess();
}
/// <summary>
/// Raised when a <see cref="AvaloniaProperty"/> value changes on this object.
/// </summary>
public event EventHandler<AvaloniaPropertyChangedEventArgs> PropertyChanged
{
add { _propertyChanged += value; }
remove { _propertyChanged -= value; }
}
/// <summary>
/// Raised when a <see cref="AvaloniaProperty"/> value changes on this object.
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add { _inpcChanged += value; }
remove { _inpcChanged -= value; }
}
/// <summary>
/// Gets or sets the parent object that inherited <see cref="AvaloniaProperty"/> values
/// are inherited from.
/// </summary>
/// <value>
/// The inheritance parent.
/// </value>
protected IAvaloniaObject InheritanceParent
{
get
{
return _inheritanceParent;
}
set
{
VerifyAccess();
if (_inheritanceParent != value)
{
var oldParent = _inheritanceParent;
var valuestore = _values;
_inheritanceParent?.RemoveInheritanceChild(this);
_inheritanceParent = value;
var properties = AvaloniaPropertyRegistry.Instance.GetRegisteredInherited(GetType());
var propertiesCount = properties.Count;
for (var i = 0; i < propertiesCount; i++)
{
var property = properties[i];
if (valuestore?.IsSet(property) == true)
{
// If local value set there can be no change.
continue;
}
property.RouteInheritanceParentChanged(this, oldParent);
}
_inheritanceParent?.AddInheritanceChild(this);
}
}
}
/// <summary>
/// Gets or sets the value of a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="property">The property.</param>
public object this[AvaloniaProperty property]
{
get { return GetValue(property); }
set { SetValue(property, value); }
}
/// <summary>
/// Gets or sets a binding for a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <param name="binding">The binding information.</param>
public IBinding this[IndexerDescriptor binding]
{
get { return new IndexerBinding(this, binding.Property, binding.Mode); }
set { this.Bind(binding.Property, value); }
}
public bool CheckAccess() => Dispatcher.UIThread.CheckAccess();
public void VerifyAccess() => Dispatcher.UIThread.VerifyAccess();
/// <summary>
/// Clears a <see cref="AvaloniaProperty"/>'s local value.
/// </summary>
/// <param name="property">The property.</param>
public void ClearValue(AvaloniaProperty property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
property.RouteClearValue(this);
}
/// <summary>
/// Clears a <see cref="AvaloniaProperty"/>'s local value.
/// </summary>
/// <param name="property">The property.</param>
public void ClearValue<T>(AvaloniaProperty<T> property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
switch (property)
{
case StyledPropertyBase<T> styled:
ClearValue(styled);
break;
case DirectPropertyBase<T> direct:
ClearValue(direct);
break;
default:
throw new NotSupportedException("Unsupported AvaloniaProperty type.");
}
}
/// <summary>
/// Clears a <see cref="AvaloniaProperty"/>'s local value.
/// </summary>
/// <param name="property">The property.</param>
public void ClearValue<T>(StyledPropertyBase<T> property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
_values?.ClearLocalValue(property);
}
/// <summary>
/// Clears a <see cref="AvaloniaProperty"/>'s local value.
/// </summary>
/// <param name="property">The property.</param>
public void ClearValue<T>(DirectPropertyBase<T> property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
var p = AvaloniaPropertyRegistry.Instance.GetRegisteredDirect(this, property);
p.InvokeSetter(this, p.GetUnsetValue(GetType()));
}
/// <summary>
/// Compares two objects using reference equality.
/// </summary>
/// <param name="obj">The object to compare.</param>
/// <remarks>
/// Overriding Equals and GetHashCode on an AvaloniaObject is disallowed for two reasons:
///
/// - AvaloniaObjects are by their nature mutable
/// - The presence of attached properties means that the semantics of equality are
/// difficult to define
///
/// See https://github.com/AvaloniaUI/Avalonia/pull/2747 for the discussion that prompted
/// this.
/// </remarks>
public sealed override bool Equals(object obj) => base.Equals(obj);
/// <summary>
/// Gets the hash code for the object.
/// </summary>
/// <remarks>
/// Overriding Equals and GetHashCode on an AvaloniaObject is disallowed for two reasons:
///
/// - AvaloniaObjects are by their nature mutable
/// - The presence of attached properties means that the semantics of equality are
/// difficult to define
///
/// See https://github.com/AvaloniaUI/Avalonia/pull/2747 for the discussion that prompted
/// this.
/// </remarks>
public sealed override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Gets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>The value.</returns>
public object GetValue(AvaloniaProperty property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
return property.RouteGetValue(this);
}
/// <summary>
/// Gets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <returns>The value.</returns>
public T GetValue<T>(StyledPropertyBase<T> property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
return GetValueOrInheritedOrDefault(property);
}
/// <summary>
/// Gets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <returns>The value.</returns>
public T GetValue<T>(DirectPropertyBase<T> property)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
var registered = AvaloniaPropertyRegistry.Instance.GetRegisteredDirect(this, property);
return registered.InvokeGetter(this);
}
/// <inheritdoc/>
public Optional<T> GetBaseValue<T>(StyledPropertyBase<T> property, BindingPriority maxPriority)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
if (_values is object &&
_values.TryGetValue(property, maxPriority, out var value))
{
return value;
}
return default;
}
/// <summary>
/// Checks whether a <see cref="AvaloniaProperty"/> is animating.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>True if the property is animating, otherwise false.</returns>
public bool IsAnimating(AvaloniaProperty property)
{
Contract.Requires<ArgumentNullException>(property != null);
VerifyAccess();
return _values?.IsAnimating(property) ?? false;
}
/// <summary>
/// Checks whether a <see cref="AvaloniaProperty"/> is set on this object.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>True if the property is set, otherwise false.</returns>
/// <remarks>
/// Checks whether a value is assigned to the property, or that there is a binding to the
/// property that is producing a value other than <see cref="AvaloniaProperty.UnsetValue"/>.
/// </remarks>
public bool IsSet(AvaloniaProperty property)
{
Contract.Requires<ArgumentNullException>(property != null);
VerifyAccess();
return _values?.IsSet(property) ?? false;
}
/// <summary>
/// Sets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
/// <param name="priority">The priority of the value.</param>
public void SetValue(
AvaloniaProperty property,
object value,
BindingPriority priority = BindingPriority.LocalValue)
{
property = property ?? throw new ArgumentNullException(nameof(property));
property.RouteSetValue(this, value, priority);
}
/// <summary>
/// Sets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
/// <param name="priority">The priority of the value.</param>
/// <returns>
/// An <see cref="IDisposable"/> if setting the property can be undone, otherwise null.
/// </returns>
public IDisposable SetValue<T>(
StyledPropertyBase<T> property,
T value,
BindingPriority priority = BindingPriority.LocalValue)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
LogPropertySet(property, value, priority);
if (value is UnsetValueType)
{
if (priority == BindingPriority.LocalValue)
{
Values.ClearLocalValue(property);
}
else
{
throw new NotSupportedException(
"Cannot set property to Unset at non-local value priority.");
}
}
else if (!(value is DoNothingType))
{
return Values.SetValue(property, value, priority);
}
return null;
}
/// <summary>
/// Sets a <see cref="AvaloniaProperty"/> value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
public void SetValue<T>(DirectPropertyBase<T> property, T value)
{
property = property ?? throw new ArgumentNullException(nameof(property));
VerifyAccess();
LogPropertySet(property, value, BindingPriority.LocalValue);
SetDirectValueUnchecked(property, value);
}
/// <summary>
/// Binds a <see cref="AvaloniaProperty"/> to an observable.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="source">The observable.</param>
/// <param name="priority">The priority of the binding.</param>
/// <returns>
/// A disposable which can be used to terminate the binding.
/// </returns>
public IDisposable Bind<T>(
StyledPropertyBase<T> property,
IObservable<BindingValue<T>> source,
BindingPriority priority = BindingPriority.LocalValue)
{
property = property ?? throw new ArgumentNullException(nameof(property));
source = source ?? throw new ArgumentNullException(nameof(source));
VerifyAccess();
return Values.AddBinding(property, source, priority);
}
/// <summary>
/// Binds a <see cref="AvaloniaProperty"/> to an observable.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="source">The observable.</param>
/// <returns>
/// A disposable which can be used to terminate the binding.
/// </returns>
public IDisposable Bind<T>(
DirectPropertyBase<T> property,
IObservable<BindingValue<T>> source)
{
property = property ?? throw new ArgumentNullException(nameof(property));
source = source ?? throw new ArgumentNullException(nameof(source));
VerifyAccess();
property = AvaloniaPropertyRegistry.Instance.GetRegisteredDirect(this, property);
if (property.IsReadOnly)
{
throw new ArgumentException($"The property {property.Name} is readonly.");
}
Logger.TryGet(LogEventLevel.Verbose, LogArea.Property)?.Log(
this,
"Bound {Property} to {Binding} with priority LocalValue",
property,
GetDescription(source));
_directBindings ??= new List<IDisposable>();
return new DirectBindingSubscription<T>(this, property, source);
}
/// <summary>
/// Coerces the specified <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
public void CoerceValue<T>(StyledPropertyBase<T> property)
{
_values?.CoerceValue(property);
}
/// <inheritdoc/>
void IAvaloniaObject.AddInheritanceChild(IAvaloniaObject child)
{
_inheritanceChildren ??= new List<IAvaloniaObject>();
_inheritanceChildren.Add(child);
}
/// <inheritdoc/>
void IAvaloniaObject.RemoveInheritanceChild(IAvaloniaObject child)
{
_inheritanceChildren?.Remove(child);
}
void IAvaloniaObject.InheritedPropertyChanged<T>(
AvaloniaProperty<T> property,
Optional<T> oldValue,
Optional<T> newValue)
{
if (property.Inherits && (_values == null || !_values.IsSet(property)))
{
RaisePropertyChanged(property, oldValue, newValue, BindingPriority.LocalValue);
}
}
/// <inheritdoc/>
Delegate[] IAvaloniaObjectDebug.GetPropertyChangedSubscribers()
{
return _propertyChanged?.GetInvocationList();
}
void IValueSink.ValueChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
var property = (StyledPropertyBase<T>)change.Property;
LogIfError(property, change.NewValue);
// If the change is to the effective value of the property and no old/new value is set
// then fill in the old/new value from property inheritance/default value. We don't do
// this for non-effective value changes because these are only needed for property
// transitions, where knowing e.g. that an inherited value is active at an arbitrary
// priority isn't of any use and would introduce overhead.
if (change.IsEffectiveValueChange && !change.OldValue.HasValue)
{
change.SetOldValue(GetInheritedOrDefault<T>(property));
}
if (change.IsEffectiveValueChange && !change.NewValue.HasValue)
{
change.SetNewValue(GetInheritedOrDefault(property));
}
if (!change.IsEffectiveValueChange ||
!EqualityComparer<T>.Default.Equals(change.OldValue.Value, change.NewValue.Value))
{
RaisePropertyChanged(change);
if (change.IsEffectiveValueChange)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Property)?.Log(
this,
"{Property} changed from {$Old} to {$Value} with priority {Priority}",
property,
change.OldValue,
change.NewValue,
change.Priority);
}
}
}
void IValueSink.Completed<T>(
StyledPropertyBase<T> property,
IPriorityValueEntry entry,
Optional<T> oldValue)
{
var change = new AvaloniaPropertyChangedEventArgs<T>(
this,
property,
oldValue,
default,
BindingPriority.Unset);
((IValueSink)this).ValueChanged(change);
}
/// <summary>
/// Called for each inherited property when the <see cref="InheritanceParent"/> changes.
/// </summary>
/// <typeparam name="T">The type of the property value.</typeparam>
/// <param name="property">The property.</param>
/// <param name="oldParent">The old inheritance parent.</param>
internal void InheritanceParentChanged<T>(
StyledPropertyBase<T> property,
IAvaloniaObject oldParent)
{
var oldValue = oldParent switch
{
AvaloniaObject o => o.GetValueOrInheritedOrDefault(property),
null => property.GetDefaultValue(GetType()),
_ => oldParent.GetValue(property)
};
var newValue = GetInheritedOrDefault(property);
if (!EqualityComparer<T>.Default.Equals(oldValue, newValue))
{
RaisePropertyChanged(property, oldValue, newValue);
}
}
internal AvaloniaPropertyValue GetDiagnosticInternal(AvaloniaProperty property)
{
if (property.IsDirect)
{
return new AvaloniaPropertyValue(
property,
GetValue(property),
BindingPriority.Unset,
"Local Value");
}
else if (_values != null)
{
var result = _values.GetDiagnostic(property);
if (result != null)
{
return result;
}
}
return new AvaloniaPropertyValue(
property,
GetValue(property),
BindingPriority.Unset,
"Unset");
}
/// <summary>
/// Logs a binding error for a property.
/// </summary>
/// <param name="property">The property that the error occurred on.</param>
/// <param name="e">The binding error.</param>
protected internal virtual void LogBindingError(AvaloniaProperty property, Exception e)
{
Logger.TryGet(LogEventLevel.Warning, LogArea.Binding)?.Log(
this,
"Error in binding to {Target}.{Property}: {Message}",
this,
property,
e.Message);
}
/// <summary>
/// Called to update the validation state for properties for which data validation is
/// enabled.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="value">The new binding value for the property.</param>
protected virtual void UpdateDataValidation<T>(
AvaloniaProperty<T> property,
BindingValue<T> value)
{
}
/// <summary>
/// Called when a avalonia property changes on the object.
/// </summary>
/// <param name="change">The property change details.</param>
protected virtual void OnPropertyChangedCore<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
if (change.IsEffectiveValueChange)
{
OnPropertyChanged(change);
}
}
/// <summary>
/// Called when a avalonia property changes on the object.
/// </summary>
/// <param name="change">The property change details.</param>
protected virtual void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
}
/// <summary>
/// Raises the <see cref="PropertyChanged"/> event.
/// </summary>
/// <param name="property">The property that has changed.</param>
/// <param name="oldValue">The old property value.</param>
/// <param name="newValue">The new property value.</param>
/// <param name="priority">The priority of the binding that produced the value.</param>
protected internal void RaisePropertyChanged<T>(
AvaloniaProperty<T> property,
Optional<T> oldValue,
BindingValue<T> newValue,
BindingPriority priority = BindingPriority.LocalValue)
{
RaisePropertyChanged(new AvaloniaPropertyChangedEventArgs<T>(
this,
property,
oldValue,
newValue,
priority));
}
/// <summary>
/// Sets the backing field for a direct avalonia property, raising the
/// <see cref="PropertyChanged"/> event if the value has changed.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="field">The backing field.</param>
/// <param name="value">The value.</param>
/// <returns>
/// True if the value changed, otherwise false.
/// </returns>
protected bool SetAndRaise<T>(AvaloniaProperty<T> property, ref T field, T value)
{
VerifyAccess();
if (EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
var old = field;
field = value;
RaisePropertyChanged(property, old, value);
return true;
}
private T GetInheritedOrDefault<T>(StyledPropertyBase<T> property)
{
if (property.Inherits && InheritanceParent is AvaloniaObject o)
{
return o.GetValueOrInheritedOrDefault(property);
}
return property.GetDefaultValue(GetType());
}
private T GetValueOrInheritedOrDefault<T>(
StyledPropertyBase<T> property,
BindingPriority maxPriority = BindingPriority.Animation)
{
var o = this;
var inherits = property.Inherits;
var value = default(T);
while (o != null)
{
var values = o._values;
if (values?.TryGetValue(property, maxPriority, out value) == true)
{
return value;
}
if (!inherits)
{
break;
}
o = o.InheritanceParent as AvaloniaObject;
}
return property.GetDefaultValue(GetType());
}
protected internal void RaisePropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
VerifyAccess();
if (change.IsEffectiveValueChange)
{
change.Property.Notifying?.Invoke(this, true);
}
try
{
OnPropertyChangedCore(change);
if (change.IsEffectiveValueChange)
{
change.Property.NotifyChanged(change);
_propertyChanged?.Invoke(this, change);
if (_inpcChanged != null)
{
var inpce = new PropertyChangedEventArgs(change.Property.Name);
_inpcChanged(this, inpce);
}
if (change.Property.Inherits && _inheritanceChildren != null)
{
foreach (var child in _inheritanceChildren)
{
child.InheritedPropertyChanged(
change.Property,
change.OldValue,
change.NewValue.ToOptional());
}
}
}
}
finally
{
if (change.IsEffectiveValueChange)
{
change.Property.Notifying?.Invoke(this, false);
}
}
}
/// <summary>
/// Sets the value of a direct property.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
private void SetDirectValueUnchecked<T>(DirectPropertyBase<T> property, T value)
{
var p = AvaloniaPropertyRegistry.Instance.GetRegisteredDirect(this, property);
if (value is UnsetValueType)
{
p.InvokeSetter(this, p.GetUnsetValue(GetType()));
}
else if (!(value is DoNothingType))
{
p.InvokeSetter(this, value);
}
}
/// <summary>
/// Sets the value of a direct property.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="value">The value.</param>
private void SetDirectValueUnchecked<T>(DirectPropertyBase<T> property, BindingValue<T> value)
{
var p = AvaloniaPropertyRegistry.Instance.FindRegisteredDirect(this, property);
if (p == null)
{
throw new ArgumentException($"Property '{property.Name} not registered on '{this.GetType()}");
}
LogIfError(property, value);
switch (value.Type)
{
case BindingValueType.UnsetValue:
case BindingValueType.BindingError:
var fallback = value.HasValue ? value : value.WithValue(property.GetUnsetValue(GetType()));
property.InvokeSetter(this, fallback);
break;
case BindingValueType.DataValidationError:
property.InvokeSetter(this, value);
break;
case BindingValueType.Value:
case BindingValueType.BindingErrorWithFallback:
case BindingValueType.DataValidationErrorWithFallback:
property.InvokeSetter(this, value);
break;
}
var metadata = p.GetMetadata(GetType());
if (metadata.EnableDataValidation == true)
{
UpdateDataValidation(property, value);
}
}
/// <summary>
/// Gets a description of an observable that van be used in logs.
/// </summary>
/// <param name="o">The observable.</param>
/// <returns>The description.</returns>
private string GetDescription(object o)
{
var description = o as IDescription;
return description?.Description ?? o.ToString();
}
/// <summary>
/// Logs a mesage if the notification represents a binding error.
/// </summary>
/// <param name="property">The property being bound.</param>
/// <param name="value">The binding notification.</param>
private void LogIfError<T>(AvaloniaProperty property, BindingValue<T> value)
{
if (value.HasError)
{
if (value.Error is AggregateException aggregate)
{
foreach (var inner in aggregate.InnerExceptions)
{
LogBindingError(property, inner);
}
}
else
{
LogBindingError(property, value.Error);
}
}
}
/// <summary>
/// Logs a property set message.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="value">The new value.</param>
/// <param name="priority">The priority.</param>
private void LogPropertySet<T>(AvaloniaProperty<T> property, T value, BindingPriority priority)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Property)?.Log(
this,
"Set {Property} to {$Value} with priority {Priority}",
property,
value,
priority);
}
private class DirectBindingSubscription<T> : IObserver<BindingValue<T>>, IDisposable
{
private readonly AvaloniaObject _owner;
private readonly DirectPropertyBase<T> _property;
private readonly IDisposable _subscription;
public DirectBindingSubscription(
AvaloniaObject owner,
DirectPropertyBase<T> property,
IObservable<BindingValue<T>> source)
{
_owner = owner;
_property = property;
_owner._directBindings.Add(this);
_subscription = source.Subscribe(this);
}
public void Dispose()
{
_subscription.Dispose();
_owner._directBindings.Remove(this);
}
public void OnCompleted() => Dispose();
public void OnError(Exception error) => Dispose();
public void OnNext(BindingValue<T> value)
{
if (Dispatcher.UIThread.CheckAccess())
{
_owner.SetDirectValueUnchecked(_property, value);
}
else
{
// To avoid allocating closure in the outer scope we need to capture variables
// locally. This allows us to skip most of the allocations when on UI thread.
var instance = _owner;
var property = _property;
var newValue = value;
Dispatcher.UIThread.Post(() => instance.SetDirectValueUnchecked(property, newValue));
}
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Text;
using System.Security;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
#if CORECLR
// Use stubs for SerializableAttribute, SecurityPermissionAttribute, ReliabilityContractAttribute and ISerializable related types.
using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Runtime.ConstrainedExecution;
#endif
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
/// 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();
#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">innter 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);
}
#if !CORECLR
/// <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");
}
#endif
#endregion Constructors
#region ISerializable Overrides
#if !CORECLR
/// <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);
}
#endif
#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 sessin 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>
/// Dipose resources
/// </summary>
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
//[SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
protected void Dispose(bool disposing)
{
if (disposing)
{
if (null != _hSessionKey)
{
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 (null == s_hStaticRSAKey)
{
if (null != _hRSAKey)
{
if (!_hRSAKey.IsInvalid)
{
_hRSAKey.Dispose();
}
_hRSAKey = null;
}
}
if (null == s_hStaticProv)
{
if (null != _hProv)
{
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 = ClrFacade.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;
}
}
} // if (ptr ...
} // if (rsa != null...
else
{
Dbg.Assert(false, "Session key not availble to encrypt secure string");
}
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()
{
_rsaCryptoProvider = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForServer();
}
#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 sessoin 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
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace oAuthX.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) 2013-2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using Gwen;
using Gwen.Control;
using SharpNav;
using SharpNav.Geometry;
//Doesn't compile if in an unsupported configuration
#if STANDALONE || OPENTK
namespace SharpNav.Examples
{
public partial class ExampleWindow
{
private NavMeshGenerationSettings settings;
private AreaIdGenerationSettings areaSettings;
private StatusBar statusBar;
private void InitializeUI()
{
settings = NavMeshGenerationSettings.Default;
areaSettings = new AreaIdGenerationSettings();
DockBase dock = new DockBase(gwenCanvas);
dock.Dock = Pos.Fill;
dock.SetSize(Width, Height);
dock.RightDock.Width = 280;
dock.BottomDock.Height = 150;
statusBar = new StatusBar(gwenCanvas);
Label genTime = new Label(statusBar);
genTime.Name = "GenTime";
genTime.Text = "Generation Time: 0ms";
genTime.Dock = Pos.Left;
LabeledCheckBox catchCheckBox = new LabeledCheckBox(statusBar);
catchCheckBox.Text = "Intercept and log exceptions";
catchCheckBox.Dock = Pos.Right;
catchCheckBox.CheckChanged += (s, e) => interceptExceptions = catchCheckBox.IsChecked;
catchCheckBox.IsChecked = true;
Base genBase = new Base(dock);
dock.RightDock.TabControl.AddPage("NavMesh Generation", genBase);
Button generateButton = new Button(genBase);
generateButton.Text = "Generate!";
generateButton.Height = 30;
generateButton.Dock = Pos.Top;
generateButton.Released += (s, e) => GenerateNavMesh();
GroupBox displaySettings = new GroupBox(genBase);
displaySettings.Text = "Display";
displaySettings.Dock = Pos.Top;
displaySettings.Height = 60;
Base levelCheckBase = new Base(displaySettings);
levelCheckBase.Dock = Pos.Top;
Label levelCheckLabel = new Label(levelCheckBase);
levelCheckLabel.Text = "Level";
levelCheckLabel.Dock = Pos.Left;
CheckBox levelCheckBox = new CheckBox(levelCheckBase);
levelCheckBox.Dock = Pos.Right;
levelCheckBox.Checked += (s, e) => displayLevel = true;
levelCheckBox.UnChecked += (s, e) => displayLevel = false;
levelCheckBox.IsChecked = true;
levelCheckBase.SizeToChildren();
Base displayModeBase = new Base(displaySettings);
displayModeBase.Dock = Pos.Top;
displayModeBase.Padding = new Padding(0, 4, 0, 0);
Label displayModeLabel = new Label(displayModeBase);
displayModeLabel.Text = "Generation Step";
displayModeLabel.Dock = Pos.Left;
displayModeLabel.Padding = new Padding(0, 0, 4, 0);
ComboBox displayModes = new ComboBox(displayModeBase);
displayModes.Dock = Pos.Top;
displayModes.AddItem("None", "", DisplayMode.None);
displayModes.AddItem("Heightfield", "", DisplayMode.Heightfield);
displayModes.AddItem("Compact Heightfield", "", DisplayMode.CompactHeightfield);
displayModes.AddItem("Distance Field", "", DisplayMode.DistanceField);
displayModes.AddItem("Regions", "", DisplayMode.Regions);
displayModes.AddItem("Contours", "", DisplayMode.Contours);
displayModes.AddItem("Polygon Mesh", "", DisplayMode.PolyMesh);
displayModes.AddItem("Polygon Mesh Detail", "", DisplayMode.PolyMeshDetail);
displayModes.AddItem("NavMesh", "", DisplayMode.NavMesh);
displayModes.AddItem("Pathfinding", "", DisplayMode.Pathfinding);
displayModes.ItemSelected += (s, e) => displayMode = (DisplayMode)e.SelectedItem.UserData;
displayModes.SelectByUserData(DisplayMode.PolyMeshDetail);
displayModeBase.SizeToChildren();
displayModeBase.Height += 4; //accounts for the padding, GWEN.NET should do this
const int leftMax = 125;
const int rightMax = 20;
GroupBox areaSetting = new GroupBox(genBase);
areaSetting.Text = "Area";
areaSetting.Dock = Pos.Top;
areaSetting.Height = 90;
var levelTris = level.GetTriangles();
BBox3 bounds = TriangleEnumerable.FromTriangle(levelTris, 0, levelTris.Length).GetBoundingBox();
Base maxTriSlope = CreateSliderOption(areaSetting, "Max Tri Slope:", 0.0001f, 3.14f, 3.14f, "N2", leftMax, rightMax, v => areaSettings.MaxTriSlope = v);
Base minLevelHeight = CreateSliderOption(areaSetting, "Min Height:", bounds.Min.Y, bounds.Max.Y, bounds.Min.Y, "N0", leftMax, rightMax, v => areaSettings.MinLevelHeight = v);
Base maxLevelHeight = CreateSliderOption(areaSetting, "Max Height:", bounds.Min.Y, bounds.Max.Y, bounds.Max.Y, "N0", leftMax, rightMax, v => areaSettings.MaxLevelHeight = v);
GroupBox rsSettings = new GroupBox(genBase);
rsSettings.Text = "Rasterization";
rsSettings.Dock = Pos.Top;
rsSettings.Height = 90;
Base cellSizeSetting = CreateSliderOption(rsSettings, "Cell Size:", 0.1f, 2.0f, 0.3f, "N2", leftMax, rightMax, v => settings.CellSize = v);
Base cellHeightSetting = CreateSliderOption(rsSettings, "Cell Height:", 0.1f, 2f, 0.2f, "N2", leftMax, rightMax, v => settings.CellHeight = v);
GroupBox agentSettings = new GroupBox(genBase);
agentSettings.Text = "Agent";
agentSettings.Dock = Pos.Top;
agentSettings.Height = 115;
Base maxSlopeSetting = CreateSliderOption(agentSettings, "Max Climb:", 0.1f, 5.0f, 0.9f, "N0", leftMax, rightMax, v => settings.MaxClimb = v);
Base maxHeightSetting = CreateSliderOption(agentSettings, "Height:", 0.1f, 5.0f, 2.0f, "N0", leftMax, rightMax, v => settings.AgentHeight = v);
Base erodeRadius = CreateSliderOption(agentSettings, "Radius:", 0.0f, 5.0f, 0.6f, "N1", leftMax, rightMax, v => { settings.AgentRadius = v; agentCylinder.Radius = v; });
Base addRemoveAgent = CreateAddRemoveButton(agentSettings, "Count", leftMax, rightMax, 0, MAX_AGENTS, () => { numActiveAgents++; GenerateCrowd(); }, () => { numActiveAgents--; GenerateCrowd(); });
GroupBox regionSettings = new GroupBox(genBase);
regionSettings.Text = "Region";
regionSettings.Dock = Pos.Top;
regionSettings.Height = 65;
Base minRegionSize = CreateSliderOption(regionSettings, "Min Region Size:", 0f, 150f, 8f, "N0", leftMax, rightMax, v => settings.MinRegionSize = (int)Math.Round(v));
Base mrgRegionSize = CreateSliderOption(regionSettings, "Merged Region Size:", 0f, 150f, 20f, "N0", leftMax, rightMax, v => settings.MergedRegionSize = (int)Math.Round(v));
GroupBox navMeshSettings = new GroupBox(genBase);
navMeshSettings.Text = "NavMesh";
navMeshSettings.Dock = Pos.Top;
navMeshSettings.Height = 90;
Base maxEdgeLength = CreateSliderOption(navMeshSettings, "Max Edge Length:", 0f, 50f, 12f, "N0", leftMax, rightMax, v => settings.MaxEdgeLength = (int)Math.Round(v));
Base maxEdgeErr = CreateSliderOption(navMeshSettings, "Max Edge Error:", 0f, 3f, 1.8f, "N1", leftMax, rightMax, v => settings.MaxEdgeError = v);
Base vertsPerPoly = CreateSliderOption(navMeshSettings, "Verts Per Poly:", 3f, 12f, 6f, "N0", leftMax, rightMax, v => settings.VertsPerPoly = (int)Math.Round(v));
GroupBox navMeshDetailSettings = new GroupBox(genBase);
navMeshDetailSettings.Text = "NavMeshDetail";
navMeshDetailSettings.Dock = Pos.Top;
navMeshDetailSettings.Height = 65;
Base sampleDistance = CreateSliderOption(navMeshDetailSettings, "Sample Distance:", 0f, 16f, 6f, "N0", leftMax, rightMax, v => settings.SampleDistance = (int)Math.Round(v));
Base maxSampleError = CreateSliderOption(navMeshDetailSettings, "Max Sample Error:", 0f, 16f, 1f, "N0", leftMax, rightMax, v => settings.MaxSampleError = (int)Math.Round(v));
Base logBase = new Base(dock);
dock.BottomDock.TabControl.AddPage("Log", logBase);
ListBox logBox = new ListBox(logBase);
logBox.Dock = Pos.Fill;
logBox.AllowMultiSelect = false;
logBox.EnableScroll(true, true);
Console.SetOut(new GwenTextWriter(logBox));
}
private Base CreateAddRemoveButton(Base parent, string labelText, int labelMaxWidth, int valueLabelMaxWidth, int minValue, int maxValue, Action onAdd, Action onRemove)
{
Base b = new Base(parent);
b.Dock = Pos.Top;
b.Padding = new Padding(0, 0, 0, 4);
//Base r = new Base(b);
//r.Dock = Pos.Right;
//r.Padding = new Padding(0, 0, 0, 0);
//Base l = new Base(b);
//l.Dock = Pos.Left;
//l.Padding = new Padding(0, 0, 0, 0);
Label label = new Label(b);
label.Text = labelText;
label.Dock = Pos.Left;
label.Padding = new Padding(0, 0, Math.Max(0, labelMaxWidth - label.Width), 0);
Label valueLabel = new Label(b);
valueLabel.Dock = Pos.Left;
valueLabel.Text = "0";
valueLabel.Padding = new Padding(Math.Max(0, valueLabelMaxWidth - valueLabel.Width), 0, 0, 0);
Button addButton = new Button(b);
addButton.Text = "+";
addButton.Height = 20;
addButton.Width = 20;
addButton.Dock = Pos.Right;
addButton.Released += (s, e) => onAdd();
addButton.Released += (s, e) => valueLabel.Text = Math.Min(maxValue, int.Parse(valueLabel.Text) + 1).ToString();
Button removeButton = new Button(b);
removeButton.Text = "-";
removeButton.Height = 20;
removeButton.Width = 20;
removeButton.Dock = Pos.Right;
removeButton.Released += (s, e) => onRemove();
removeButton.Released += (s, e) => valueLabel.Text = Math.Max(minValue, int.Parse(valueLabel.Text) - 1).ToString();
b.SizeToChildren();
return b;
}
private Base CreateSliderOption(Base parent, string labelText, float min, float max, float value, string valueStringFormat, int labelMaxWidth, int valueLabelMaxWidth, Action<float> onChange)
{
Base b = new Base(parent);
b.Dock = Pos.Top;
b.Padding = new Padding(0, 0, 0, 4);
Label label = new Label(b);
label.Text = labelText;
label.Dock = Pos.Left;
label.Padding = new Padding(0, 0, Math.Max(0, labelMaxWidth - label.Width), 0);
Label valueLabel = new Label(b);
valueLabel.Dock = Pos.Right;
HorizontalSlider slider = new HorizontalSlider(b);
slider.Dock = Pos.Fill;
slider.Height = 20;
slider.Min = min;
slider.Max = max;
slider.Value = value;
slider.ValueChanged += (s, e) =>
{
int prevWidth = valueLabel.Width;
valueLabel.Text = slider.Value.ToString(valueStringFormat);
valueLabel.Padding = new Padding(valueLabel.Padding.Left - (valueLabel.Width - prevWidth), 0, 0, 0);
};
slider.ValueChanged += (s, e) => onChange(slider.Value);
valueLabel.Text = value.ToString(valueStringFormat);
valueLabel.Padding = new Padding(Math.Max(0, valueLabelMaxWidth - valueLabel.Width), 0, 0, 0);
onChange(value);
b.SizeToChildren();
return b;
}
private class AreaIdGenerationSettings
{
public float MaxTriSlope { get; set; }
public float MinLevelHeight { get; set; }
public float MaxLevelHeight { get; set; }
}
}
}
#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.
namespace System.Xml.Schema
{
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Runtime.Versioning;
#pragma warning disable 618
internal sealed class XsdValidator : BaseValidator
{
private int _startIDConstraint = -1;
private const int STACK_INCREMENT = 10;
private HWStack _validationStack; // validaton contexts
private Hashtable _attPresence;
private XmlNamespaceManager _nsManager;
private bool _bManageNamespaces = false;
private Hashtable _IDs;
private IdRefNode _idRefListHead;
private Parser _inlineSchemaParser = null;
private XmlSchemaContentProcessing _processContents;
private static readonly XmlSchemaDatatype s_dtCDATA = XmlSchemaDatatype.FromXmlTokenizedType(XmlTokenizedType.CDATA);
private static readonly XmlSchemaDatatype s_dtQName = XmlSchemaDatatype.FromXmlTokenizedTypeXsd(XmlTokenizedType.QName);
private static readonly XmlSchemaDatatype s_dtStringArray = s_dtCDATA.DeriveByList(null);
//To avoid SchemaNames creation
private string _nsXmlNs;
private string _nsXs;
private string _nsXsi;
private string _xsiType;
private string _xsiNil;
private string _xsiSchemaLocation;
private string _xsiNoNamespaceSchemaLocation;
private string _xsdSchema;
internal XsdValidator(BaseValidator validator) : base(validator)
{
Init();
}
internal XsdValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling) : base(reader, schemaCollection, eventHandling)
{
Init();
}
private void Init()
{
_nsManager = reader.NamespaceManager;
if (_nsManager == null)
{
_nsManager = new XmlNamespaceManager(NameTable);
_bManageNamespaces = true;
}
_validationStack = new HWStack(STACK_INCREMENT);
textValue = new StringBuilder();
_attPresence = new Hashtable();
schemaInfo = new SchemaInfo();
checkDatatype = false;
_processContents = XmlSchemaContentProcessing.Strict;
Push(XmlQualifiedName.Empty);
//Add common strings to be compared to NameTable
_nsXmlNs = NameTable.Add(XmlReservedNs.NsXmlNs);
_nsXs = NameTable.Add(XmlReservedNs.NsXs);
_nsXsi = NameTable.Add(XmlReservedNs.NsXsi);
_xsiType = NameTable.Add("type");
_xsiNil = NameTable.Add("nil");
_xsiSchemaLocation = NameTable.Add("schemaLocation");
_xsiNoNamespaceSchemaLocation = NameTable.Add("noNamespaceSchemaLocation");
_xsdSchema = NameTable.Add("schema");
}
public override void Validate()
{
if (IsInlineSchemaStarted)
{
ProcessInlineSchema();
}
else
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
ValidateElement();
if (reader.IsEmptyElement)
{
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.Whitespace:
ValidateWhitespace();
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
case XmlNodeType.SignificantWhitespace:
ValidateText();
break;
case XmlNodeType.EndElement:
ValidateEndElement();
break;
}
}
}
public override void CompleteValidation()
{
CheckForwardRefs();
}
private bool IsInlineSchemaStarted
{
get { return _inlineSchemaParser != null; }
}
private void ProcessInlineSchema()
{
if (!_inlineSchemaParser.ParseReaderNode())
{ // Done
_inlineSchemaParser.FinishParsing();
XmlSchema schema = _inlineSchemaParser.XmlSchema;
string inlineNS = null;
if (schema != null && schema.ErrorCount == 0)
{
try
{
SchemaInfo inlineSchemaInfo = new SchemaInfo();
inlineSchemaInfo.SchemaType = SchemaType.XSD;
inlineNS = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
if (!SchemaInfo.TargetNamespaces.ContainsKey(inlineNS))
{
if (SchemaCollection.Add(inlineNS, inlineSchemaInfo, schema, true) != null)
{ //If no errors on compile
//Add to validator's SchemaInfo
SchemaInfo.Add(inlineSchemaInfo, EventHandler);
}
}
}
catch (XmlSchemaException e)
{
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { BaseUri.AbsoluteUri, e.Message }, XmlSeverityType.Error);
}
}
_inlineSchemaParser = null;
}
}
private void ValidateElement()
{
elementName.Init(reader.LocalName, reader.NamespaceURI);
object particle = ValidateChildElement();
if (IsXSDRoot(elementName.Name, elementName.Namespace) && reader.Depth > 0)
{
_inlineSchemaParser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
_inlineSchemaParser.StartParsing(reader, null);
ProcessInlineSchema();
}
else
{
ProcessElement(particle);
}
}
private object ValidateChildElement()
{
object particle = null;
int errorCode = 0;
if (context.NeedValidateChildren)
{
if (context.IsNill)
{
SendValidationEvent(SR.Sch_ContentInNill, elementName.ToString());
return null;
}
particle = context.ElementDecl.ContentValidator.ValidateElement(elementName, context, out errorCode);
if (particle == null)
{
_processContents = context.ProcessContents = XmlSchemaContentProcessing.Skip;
if (errorCode == -2)
{ //ContentModel all group error
SendValidationEvent(SR.Sch_AllElement, elementName.ToString());
}
XmlSchemaValidator.ElementValidationError(elementName, context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
return particle;
}
private void ProcessElement(object particle)
{
XmlQualifiedName xsiType;
string xsiNil;
SchemaElementDecl elementDecl = FastGetElementDecl(particle);
Push(elementName);
if (_bManageNamespaces)
{
_nsManager.PushScope();
}
ProcessXsiAttributes(out xsiType, out xsiNil);
if (_processContents != XmlSchemaContentProcessing.Skip)
{
if (elementDecl == null || !xsiType.IsEmpty || xsiNil != null)
{
elementDecl = ThoroughGetElementDecl(elementDecl, xsiType, xsiNil);
}
if (elementDecl == null)
{
if (HasSchema && _processContents == XmlSchemaContentProcessing.Strict)
{
SendValidationEvent(SR.Sch_UndeclaredElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
else
{
SendValidationEvent(SR.Sch_NoElementSchemaFound, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace), XmlSeverityType.Warning);
}
}
}
context.ElementDecl = elementDecl;
ValidateStartElementIdentityConstraints();
ValidateStartElement();
if (context.ElementDecl != null)
{
ValidateEndStartElement();
context.NeedValidateChildren = _processContents != XmlSchemaContentProcessing.Skip;
context.ElementDecl.ContentValidator.InitValidation(context);
}
}
// SxS: This method processes attributes read from source document and does not expose any resources.
// It's OK to suppress the SxS warning.
private void ProcessXsiAttributes(out XmlQualifiedName xsiType, out string xsiNil)
{
string[] xsiSchemaLocation = null;
string xsiNoNamespaceSchemaLocation = null;
xsiType = XmlQualifiedName.Empty;
xsiNil = null;
if (reader.Depth == 0)
{
//Load schema for empty namespace
LoadSchema(string.Empty, null);
//Should load schemas for namespaces already added to nsManager
foreach (string ns in _nsManager.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml).Values)
{
LoadSchema(ns, null);
}
}
if (reader.MoveToFirstAttribute())
{
do
{
string objectNs = reader.NamespaceURI;
string objectName = reader.LocalName;
if (Ref.Equal(objectNs, _nsXmlNs))
{
LoadSchema(reader.Value, null);
if (_bManageNamespaces)
{
_nsManager.AddNamespace(reader.Prefix.Length == 0 ? string.Empty : reader.LocalName, reader.Value);
}
}
else if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiSchemaLocation))
{
xsiSchemaLocation = (string[])s_dtStringArray.ParseValue(reader.Value, NameTable, _nsManager);
}
else if (Ref.Equal(objectName, _xsiNoNamespaceSchemaLocation))
{
xsiNoNamespaceSchemaLocation = reader.Value;
}
else if (Ref.Equal(objectName, _xsiType))
{
xsiType = (XmlQualifiedName)s_dtQName.ParseValue(reader.Value, NameTable, _nsManager);
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = reader.Value;
}
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
if (xsiNoNamespaceSchemaLocation != null)
{
LoadSchema(string.Empty, xsiNoNamespaceSchemaLocation);
}
if (xsiSchemaLocation != null)
{
for (int i = 0; i < xsiSchemaLocation.Length - 1; i += 2)
{
LoadSchema((string)xsiSchemaLocation[i], (string)xsiSchemaLocation[i + 1]);
}
}
}
private void ValidateEndElement()
{
if (_bManageNamespaces)
{
_nsManager.PopScope();
}
if (context.ElementDecl != null)
{
if (!context.IsNill)
{
if (context.NeedValidateChildren)
{
if (!context.ElementDecl.ContentValidator.CompleteValidation(context))
{
XmlSchemaValidator.CompleteValidationError(context, EventHandler, reader, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition, null);
}
}
if (checkDatatype && !context.IsNill)
{
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
if (!(stringValue.Length == 0 && context.ElementDecl.DefaultValueTyped != null))
{
CheckValue(stringValue, null);
checkDatatype = false;
}
}
}
// for each level in the stack, endchildren and fill value from element
if (HasIdentityConstraints)
{
EndElementIdentityConstraints();
}
}
Pop();
}
private SchemaElementDecl FastGetElementDecl(object particle)
{
SchemaElementDecl elementDecl = null;
if (particle != null)
{
XmlSchemaElement element = particle as XmlSchemaElement;
if (element != null)
{
elementDecl = element.ElementDecl;
}
else
{
XmlSchemaAny any = (XmlSchemaAny)particle;
_processContents = any.ProcessContentsCorrect;
}
}
return elementDecl;
}
private SchemaElementDecl ThoroughGetElementDecl(SchemaElementDecl elementDecl, XmlQualifiedName xsiType, string xsiNil)
{
if (elementDecl == null)
{
elementDecl = schemaInfo.GetElementDecl(elementName);
}
if (elementDecl != null)
{
if (xsiType.IsEmpty)
{
if (elementDecl.IsAbstract)
{
SendValidationEvent(SR.Sch_AbstractElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
elementDecl = null;
}
}
else if (xsiNil != null && xsiNil.Equals("true"))
{
SendValidationEvent(SR.Sch_XsiNilAndType);
}
else
{
SchemaElementDecl elementDeclXsi;
if (!schemaInfo.ElementDeclsByType.TryGetValue(xsiType, out elementDeclXsi) && xsiType.Namespace == _nsXs)
{
XmlSchemaSimpleType simpleType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName(xsiType.Name, _nsXs));
if (simpleType != null)
{
elementDeclXsi = simpleType.ElementDecl;
}
}
if (elementDeclXsi == null)
{
SendValidationEvent(SR.Sch_XsiTypeNotFound, xsiType.ToString());
elementDecl = null;
}
else if (!XmlSchemaType.IsDerivedFrom(elementDeclXsi.SchemaType, elementDecl.SchemaType, elementDecl.Block))
{
SendValidationEvent(SR.Sch_XsiTypeBlockedEx, new string[] { xsiType.ToString(), XmlSchemaValidator.QNameString(context.LocalName, context.Namespace) });
elementDecl = null;
}
else
{
elementDecl = elementDeclXsi;
}
}
if (elementDecl != null && elementDecl.IsNillable)
{
if (xsiNil != null)
{
context.IsNill = XmlConvert.ToBoolean(xsiNil);
if (context.IsNill && elementDecl.DefaultValueTyped != null)
{
SendValidationEvent(SR.Sch_XsiNilAndFixed);
}
}
}
else if (xsiNil != null)
{
SendValidationEvent(SR.Sch_InvalidXsiNill);
}
}
return elementDecl;
}
private void ValidateStartElement()
{
if (context.ElementDecl != null)
{
if (context.ElementDecl.IsAbstract)
{
SendValidationEvent(SR.Sch_AbstractElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
reader.SchemaTypeObject = context.ElementDecl.SchemaType;
if (reader.IsEmptyElement && !context.IsNill && context.ElementDecl.DefaultValueTyped != null)
{
reader.TypedValueObject = UnWrapUnion(context.ElementDecl.DefaultValueTyped);
context.IsNill = true; // reusing IsNill
}
else
{
reader.TypedValueObject = null; //Typed value cleanup
}
if (this.context.ElementDecl.HasRequiredAttribute || HasIdentityConstraints)
{
_attPresence.Clear();
}
}
if (reader.MoveToFirstAttribute())
{
do
{
if ((object)reader.NamespaceURI == (object)_nsXmlNs)
{
continue;
}
if ((object)reader.NamespaceURI == (object)_nsXsi)
{
continue;
}
try
{
reader.SchemaTypeObject = null;
XmlQualifiedName attQName = new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
bool skipContents = (_processContents == XmlSchemaContentProcessing.Skip);
SchemaAttDef attnDef = schemaInfo.GetAttributeXsd(context.ElementDecl, attQName, ref skipContents);
if (attnDef != null)
{
if (context.ElementDecl != null && (context.ElementDecl.HasRequiredAttribute || _startIDConstraint != -1))
{
_attPresence.Add(attnDef.Name, attnDef);
}
Debug.Assert(attnDef.SchemaType != null);
reader.SchemaTypeObject = attnDef.SchemaType;
if (attnDef.Datatype != null)
{
// need to check the contents of this attribute to make sure
// it is valid according to the specified attribute type.
CheckValue(reader.Value, attnDef);
}
if (HasIdentityConstraints)
{
AttributeIdentityConstraints(reader.LocalName, reader.NamespaceURI, reader.TypedValueObject, reader.Value, attnDef);
}
}
else if (!skipContents)
{
if (context.ElementDecl == null
&& _processContents == XmlSchemaContentProcessing.Strict
&& attQName.Namespace.Length != 0
&& schemaInfo.Contains(attQName.Namespace)
)
{
SendValidationEvent(SR.Sch_UndeclaredAttribute, attQName.ToString());
}
else
{
SendValidationEvent(SR.Sch_NoAttributeSchemaFound, attQName.ToString(), XmlSeverityType.Warning);
}
}
}
catch (XmlSchemaException e)
{
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
private void ValidateEndStartElement()
{
if (context.ElementDecl.HasDefaultAttribute)
{
for (int i = 0; i < context.ElementDecl.DefaultAttDefs.Count; ++i)
{
SchemaAttDef attdef = (SchemaAttDef)context.ElementDecl.DefaultAttDefs[i];
reader.AddDefaultAttribute(attdef);
// even default attribute i have to move to... but can't exist
if (HasIdentityConstraints && !_attPresence.Contains(attdef.Name))
{
AttributeIdentityConstraints(attdef.Name.Name, attdef.Name.Namespace, UnWrapUnion(attdef.DefaultValueTyped), attdef.DefaultValueRaw, attdef);
}
}
}
if (context.ElementDecl.HasRequiredAttribute)
{
try
{
context.ElementDecl.CheckAttributes(_attPresence, reader.StandAlone);
}
catch (XmlSchemaException e)
{
e.SetSource(reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
SendValidationEvent(e);
}
}
if (context.ElementDecl.Datatype != null)
{
checkDatatype = true;
hasSibling = false;
textString = string.Empty;
textValue.Length = 0;
}
}
private void LoadSchemaFromLocation(string uri, string url)
{
XmlReader reader = null;
SchemaInfo schemaInfo = null;
try
{
Uri ruri = this.XmlResolver.ResolveUri(BaseUri, url);
Stream stm = (Stream)this.XmlResolver.GetEntity(ruri, null, null);
reader = new XmlTextReader(ruri.ToString(), stm, NameTable);
//XmlSchema schema = SchemaCollection.Add(uri, reader, this.XmlResolver);
Parser parser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
parser.XmlResolver = this.XmlResolver;
SchemaType schemaType = parser.Parse(reader, uri);
schemaInfo = new SchemaInfo();
schemaInfo.SchemaType = schemaType;
if (schemaType == SchemaType.XSD)
{
if (SchemaCollection.EventHandler == null)
{
SchemaCollection.EventHandler = this.EventHandler;
}
SchemaCollection.Add(uri, schemaInfo, parser.XmlSchema, true);
}
//Add to validator's SchemaInfo
SchemaInfo.Add(schemaInfo, EventHandler);
while (reader.Read()) ; // wellformness check
}
catch (XmlSchemaException e)
{
schemaInfo = null;
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Error);
}
catch (Exception e)
{
schemaInfo = null;
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Warning);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
private void LoadSchema(string uri, string url)
{
if (this.XmlResolver == null)
{
return;
}
if (SchemaInfo.TargetNamespaces.ContainsKey(uri) && _nsManager.LookupPrefix(uri) != null)
{
return;
}
SchemaInfo schemaInfo = null;
if (SchemaCollection != null)
schemaInfo = SchemaCollection.GetSchemaInfo(uri);
if (schemaInfo != null)
{
if (schemaInfo.SchemaType != SchemaType.XSD)
{
throw new XmlException(SR.Xml_MultipleValidaitonTypes, string.Empty, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
SchemaInfo.Add(schemaInfo, EventHandler);
return;
}
if (url != null)
{
LoadSchemaFromLocation(uri, url);
}
}
private bool HasSchema { get { return schemaInfo.SchemaType != SchemaType.None; } }
public override bool PreserveWhitespace
{
get { return context.ElementDecl != null ? context.ElementDecl.ContentValidator.PreserveWhitespace : false; }
}
private void ProcessTokenizedType(
XmlTokenizedType ttype,
string name
)
{
switch (ttype)
{
case XmlTokenizedType.ID:
if (FindId(name) != null)
{
SendValidationEvent(SR.Sch_DupId, name);
}
else
{
AddID(name, context.LocalName);
}
break;
case XmlTokenizedType.IDREF:
object p = FindId(name);
if (p == null)
{ // add it to linked list to check it later
_idRefListHead = new IdRefNode(_idRefListHead, name, this.PositionInfo.LineNumber, this.PositionInfo.LinePosition);
}
break;
case XmlTokenizedType.ENTITY:
ProcessEntity(schemaInfo, name, this, EventHandler, reader.BaseURI, PositionInfo.LineNumber, PositionInfo.LinePosition);
break;
default:
break;
}
}
private void CheckValue(
string value,
SchemaAttDef attdef
)
{
try
{
reader.TypedValueObject = null;
bool isAttn = attdef != null;
XmlSchemaDatatype dtype = isAttn ? attdef.Datatype : context.ElementDecl.Datatype;
if (dtype == null)
{
return; // no reason to check
}
object typedValue = dtype.ParseValue(value, NameTable, _nsManager, true);
// Check special types
XmlTokenizedType ttype = dtype.TokenizedType;
if (ttype == XmlTokenizedType.ENTITY || ttype == XmlTokenizedType.ID || ttype == XmlTokenizedType.IDREF)
{
if (dtype.Variety == XmlSchemaDatatypeVariety.List)
{
string[] ss = (string[])typedValue;
for (int i = 0; i < ss.Length; ++i)
{
ProcessTokenizedType(dtype.TokenizedType, ss[i]);
}
}
else
{
ProcessTokenizedType(dtype.TokenizedType, (string)typedValue);
}
}
SchemaDeclBase decl = isAttn ? (SchemaDeclBase)attdef : (SchemaDeclBase)context.ElementDecl;
if (!decl.CheckValue(typedValue))
{
if (isAttn)
{
SendValidationEvent(SR.Sch_FixedAttributeValue, attdef.Name.ToString());
}
else
{
SendValidationEvent(SR.Sch_FixedElementValue, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
if (dtype.Variety == XmlSchemaDatatypeVariety.Union)
{
typedValue = UnWrapUnion(typedValue);
}
reader.TypedValueObject = typedValue;
}
catch (XmlSchemaException)
{
if (attdef != null)
{
SendValidationEvent(SR.Sch_AttributeValueDataType, attdef.Name.ToString());
}
else
{
SendValidationEvent(SR.Sch_ElementValueDataType, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
}
}
internal void AddID(string name, object node)
{
// Note: It used to be true that we only called this if _fValidate was true,
// but due to the fact that you can now dynamically type somethign as an ID
// that is no longer true.
if (_IDs == null)
{
_IDs = new Hashtable();
}
_IDs.Add(name, node);
}
public override object FindId(string name)
{
return _IDs == null ? null : _IDs[name];
}
public bool IsXSDRoot(string localName, string ns)
{
return Ref.Equal(ns, _nsXs) && Ref.Equal(localName, _xsdSchema);
}
private void Push(XmlQualifiedName elementName)
{
context = (ValidationState)_validationStack.Push();
if (context == null)
{
context = new ValidationState();
_validationStack.AddToTop(context);
}
context.LocalName = elementName.Name;
context.Namespace = elementName.Namespace;
context.HasMatched = false;
context.IsNill = false;
context.ProcessContents = _processContents;
context.NeedValidateChildren = false;
context.Constr = null; //resetting the constraints to be null incase context != null
// when pushing onto stack;
}
private void Pop()
{
if (_validationStack.Length > 1)
{
_validationStack.Pop();
if (_startIDConstraint == _validationStack.Length)
{
_startIDConstraint = -1;
}
context = (ValidationState)_validationStack.Peek();
_processContents = context.ProcessContents;
}
}
private void CheckForwardRefs()
{
IdRefNode next = _idRefListHead;
while (next != null)
{
if (FindId(next.Id) == null)
{
SendValidationEvent(new XmlSchemaException(SR.Sch_UndeclaredId, next.Id, reader.BaseURI, next.LineNo, next.LinePos));
}
IdRefNode ptr = next.Next;
next.Next = null; // unhook each object so it is cleaned up by Garbage Collector
next = ptr;
}
// not needed any more.
_idRefListHead = null;
}
private void ValidateStartElementIdentityConstraints()
{
// added on June 15, set the context here, so the stack can have them
if (context.ElementDecl != null)
{
if (context.ElementDecl.Constraints != null)
{
AddIdentityConstraints();
}
//foreach constraint in stack (including the current one)
if (HasIdentityConstraints)
{
ElementIdentityConstraints();
}
}
}
private bool HasIdentityConstraints
{
get { return _startIDConstraint != -1; }
}
private void AddIdentityConstraints()
{
context.Constr = new ConstraintStruct[context.ElementDecl.Constraints.Length];
int id = 0;
for (int i = 0; i < context.ElementDecl.Constraints.Length; ++i)
{
context.Constr[id++] = new ConstraintStruct(context.ElementDecl.Constraints[i]);
} // foreach constraint /constraintstruct
// added on June 19, make connections between new keyref tables with key/unique tables in stack
// i can't put it in the above loop, coz there will be key on the same level
for (int i = 0; i < context.Constr.Length; ++i)
{
if (context.Constr[i].constraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref)
{
bool find = false;
// go upwards checking or only in this level
for (int level = _validationStack.Length - 1; level >= ((_startIDConstraint >= 0) ? _startIDConstraint : _validationStack.Length - 1); level--)
{
// no constraint for this level
if (((ValidationState)(_validationStack[level])).Constr == null)
{
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)_validationStack[level]).Constr;
for (int j = 0; j < constraints.Length; ++j)
{
if (constraints[j].constraint.name == context.Constr[i].constraint.refer)
{
find = true;
if (constraints[j].keyrefTable == null)
{
constraints[j].keyrefTable = new Hashtable();
}
context.Constr[i].qualifiedTable = constraints[j].keyrefTable;
break;
}
}
if (find)
{
break;
}
}
if (!find)
{
// didn't find connections, throw exceptions
SendValidationEvent(SR.Sch_RefNotInScope, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
}
} // finished dealing with keyref
} // end foreach
// initial set
if (_startIDConstraint == -1)
{
_startIDConstraint = _validationStack.Length - 1;
}
}
private void ElementIdentityConstraints()
{
for (int i = _startIDConstraint; i < _validationStack.Length; i++)
{
// no constraint for this level
if (((ValidationState)(_validationStack[i])).Constr == null)
{
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)_validationStack[i]).Constr;
for (int j = 0; j < constraints.Length; ++j)
{
// check selector from here
if (constraints[j].axisSelector.MoveToStartElement(reader.LocalName, reader.NamespaceURI))
{
// selector selects new node, activate a new set of fields
Debug.WriteLine("Selector Match!");
Debug.WriteLine("Name: " + reader.LocalName + "\t|\tURI: " + reader.NamespaceURI + "\n");
// in which axisFields got updated
constraints[j].axisSelector.PushKS(PositionInfo.LineNumber, PositionInfo.LinePosition);
}
// axisFields is not null, but may be empty
for (int k = 0; k < constraints[j].axisFields.Count; ++k)
{
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[j].axisFields[k];
// check field from here
if (laxis.MoveToStartElement(reader.LocalName, reader.NamespaceURI))
{
Debug.WriteLine("Element Field Match!");
// checking simpleType / simpleContent
if (context.ElementDecl != null)
{ // nextElement can be null when xml/xsd are not valid
if (context.ElementDecl.Datatype == null)
{
SendValidationEvent(SR.Sch_FieldSimpleTypeExpected, reader.LocalName);
}
else
{
// can't fill value here, wait till later....
// fill type : xsdType
laxis.isMatched = true;
// since it's simpletyped element, the endchildren will come consequently... don't worry
}
}
}
}
}
}
}
// facilitate modifying
private void AttributeIdentityConstraints(string name, string ns, object obj, string sobj, SchemaAttDef attdef)
{
for (int ci = _startIDConstraint; ci < _validationStack.Length; ci++)
{
// no constraint for this level
if (((ValidationState)(_validationStack[ci])).Constr == null)
{
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)_validationStack[ci]).Constr;
for (int i = 0; i < constraints.Length; ++i)
{
// axisFields is not null, but may be empty
for (int j = 0; j < constraints[i].axisFields.Count; ++j)
{
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[i].axisFields[j];
// check field from here
if (laxis.MoveToAttribute(name, ns))
{
Debug.WriteLine("Attribute Field Match!");
//attribute is only simpletype, so needn't checking...
// can fill value here, yeah!!
Debug.WriteLine("Attribute Field Filling Value!");
Debug.WriteLine("Name: " + name + "\t|\tURI: " + ns + "\t|\tValue: " + obj + "\n");
if (laxis.Ks[laxis.Column] != null)
{
// should be evaluated to either an empty node-set or a node-set with exactly one member
// two matches...
SendValidationEvent(SR.Sch_FieldSingleValueExpected, name);
}
else if ((attdef != null) && (attdef.Datatype != null))
{
laxis.Ks[laxis.Column] = new TypedObject(obj, sobj, attdef.Datatype);
}
}
}
}
}
}
private object UnWrapUnion(object typedValue)
{
XsdSimpleValue simpleValue = typedValue as XsdSimpleValue;
if (simpleValue != null)
{
typedValue = simpleValue.TypedValue;
}
return typedValue;
}
private void EndElementIdentityConstraints()
{
for (int ci = _validationStack.Length - 1; ci >= _startIDConstraint; ci--)
{
// no constraint for this level
if (((ValidationState)(_validationStack[ci])).Constr == null)
{
continue;
}
// else
ConstraintStruct[] constraints = ((ValidationState)_validationStack[ci]).Constr;
for (int i = 0; i < constraints.Length; ++i)
{
// EndChildren
// axisFields is not null, but may be empty
for (int j = 0; j < constraints[i].axisFields.Count; ++j)
{
LocatedActiveAxis laxis = (LocatedActiveAxis)constraints[i].axisFields[j];
// check field from here
// isMatched is false when nextElement is null. so needn't change this part.
if (laxis.isMatched)
{
Debug.WriteLine("Element Field Filling Value!");
Debug.WriteLine("Name: " + reader.LocalName + "\t|\tURI: " + reader.NamespaceURI + "\t|\tValue: " + reader.TypedValueObject + "\n");
// fill value
laxis.isMatched = false;
if (laxis.Ks[laxis.Column] != null)
{
// [field...] should be evaluated to either an empty node-set or a node-set with exactly one member
// two matches... already existing field value in the table.
SendValidationEvent(SR.Sch_FieldSingleValueExpected, reader.LocalName);
}
else
{
// for element, reader.Value = "";
string stringValue = !hasSibling ? textString : textValue.ToString(); // only for identity-constraint exception reporting
if (reader.TypedValueObject != null && stringValue.Length != 0)
{
laxis.Ks[laxis.Column] = new TypedObject(reader.TypedValueObject, stringValue, context.ElementDecl.Datatype);
}
}
}
// EndChildren
laxis.EndElement(reader.LocalName, reader.NamespaceURI);
}
if (constraints[i].axisSelector.EndElement(reader.LocalName, reader.NamespaceURI))
{
// insert key sequence into hash (+ located active axis tuple leave for later)
KeySequence ks = constraints[i].axisSelector.PopKS();
// unqualified keysequence are not allowed
switch (constraints[i].constraint.Role)
{
case CompiledIdentityConstraint.ConstraintRole.Key:
if (!ks.IsQualified())
{
//Key's fields can't be null... if we can return context node's line info maybe it will be better
//only keymissing & keyduplicate reporting cases are necessary to be dealt with... 3 places...
SendValidationEvent(new XmlSchemaException(SR.Sch_MissingKey, constraints[i].constraint.name.ToString(), reader.BaseURI, ks.PosLine, ks.PosCol));
}
else if (constraints[i].qualifiedTable.Contains(ks))
{
// unique or key checking value confliction
// for redundant key, reporting both occurings
// doesn't work... how can i retrieve value out??
SendValidationEvent(new XmlSchemaException(SR.Sch_DuplicateKey,
new string[2] { ks.ToString(), constraints[i].constraint.name.ToString() },
reader.BaseURI, ks.PosLine, ks.PosCol));
}
else
{
constraints[i].qualifiedTable.Add(ks, ks);
}
break;
case CompiledIdentityConstraint.ConstraintRole.Unique:
if (!ks.IsQualified())
{
continue;
}
if (constraints[i].qualifiedTable.Contains(ks))
{
// unique or key checking confliction
SendValidationEvent(new XmlSchemaException(SR.Sch_DuplicateKey,
new string[2] { ks.ToString(), constraints[i].constraint.name.ToString() },
reader.BaseURI, ks.PosLine, ks.PosCol));
}
else
{
constraints[i].qualifiedTable.Add(ks, ks);
}
break;
case CompiledIdentityConstraint.ConstraintRole.Keyref:
// is there any possibility:
// 2 keyrefs: value is equal, type is not
// both put in the hashtable, 1 reference, 1 not
if (constraints[i].qualifiedTable != null)
{ //Will be null in cases when the keyref is outside the scope of the key, that is not allowed by our impl
if (!ks.IsQualified() || constraints[i].qualifiedTable.Contains(ks))
{
continue;
}
constraints[i].qualifiedTable.Add(ks, ks);
}
break;
}
}
}
}
// current level's constraint struct
ConstraintStruct[] vcs = ((ValidationState)(_validationStack[_validationStack.Length - 1])).Constr;
if (vcs != null)
{
// validating all referencing tables...
for (int i = 0; i < vcs.Length; ++i)
{
if ((vcs[i].constraint.Role == CompiledIdentityConstraint.ConstraintRole.Keyref)
|| (vcs[i].keyrefTable == null))
{
continue;
}
foreach (KeySequence ks in vcs[i].keyrefTable.Keys)
{
if (!vcs[i].qualifiedTable.Contains(ks))
{
SendValidationEvent(new XmlSchemaException(SR.Sch_UnresolvedKeyref, new string[2] { ks.ToString(), vcs[i].constraint.name.ToString() },
reader.BaseURI, ks.PosLine, ks.PosCol));
}
}
}
}
}
}
#pragma warning restore 618
}
| |
// <copyright file="SelectElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.UI
{
/// <summary>
/// Provides a convenience method for manipulating selections of options in an HTML select element.
/// </summary>
public class SelectElement : IWrapsElement
{
private readonly IWebElement element;
/// <summary>
/// Initializes a new instance of the <see cref="SelectElement"/> class.
/// </summary>
/// <param name="element">The element to be wrapped</param>
/// <exception cref="ArgumentNullException">Thrown when the <see cref="IWebElement"/> object is <see langword="null"/></exception>
/// <exception cref="UnexpectedTagNameException">Thrown when the element wrapped is not a <select> element.</exception>
public SelectElement(IWebElement element)
{
if (element == null)
{
throw new ArgumentNullException("element", "element cannot be null");
}
string tagName = element.TagName;
if (string.IsNullOrEmpty(tagName) || string.Compare(tagName, "select", StringComparison.OrdinalIgnoreCase) != 0)
{
throw new UnexpectedTagNameException("select", tagName);
}
this.element = element;
// let check if it's a multiple
string attribute = element.GetAttribute("multiple");
this.IsMultiple = attribute != null && attribute.ToLowerInvariant() != "false";
}
/// <summary>
/// Gets the <see cref="IWebElement"/> wrapped by this object.
/// </summary>
public IWebElement WrappedElement
{
get { return this.element; }
}
/// <summary>
/// Gets a value indicating whether the parent element supports multiple selections.
/// </summary>
public bool IsMultiple { get; private set; }
/// <summary>
/// Gets the list of options for the select element.
/// </summary>
public IList<IWebElement> Options
{
get
{
return this.element.FindElements(By.TagName("option"));
}
}
/// <summary>
/// Gets the selected item within the select element.
/// </summary>
/// <remarks>If more than one item is selected this will return the first item.</remarks>
/// <exception cref="NoSuchElementException">Thrown if no option is selected.</exception>
public IWebElement SelectedOption
{
get
{
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
return option;
}
}
throw new NoSuchElementException("No option is selected");
}
}
/// <summary>
/// Gets all of the selected options within the select element.
/// </summary>
public IList<IWebElement> AllSelectedOptions
{
get
{
List<IWebElement> returnValue = new List<IWebElement>();
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
returnValue.Add(option);
}
}
return returnValue;
}
}
/// <summary>
/// Select all options by the text displayed.
/// </summary>
/// <param name="text">The text of the option to be selected.</param>
/// <param name="partialMatch">Default value is false. If true a partial match on the Options list will be performed, otherwise exact match.</param>
/// <remarks>When given "Bar" this method would select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown if there is no element with the given text present.</exception>
public void SelectByText(string text, bool partialMatch = false)
{
if (text == null)
{
throw new ArgumentNullException("text", "text must not be null");
}
bool matched = false;
IList<IWebElement> options;
if (!partialMatch)
{
// try to find the option via XPATH ...
options = this.element.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"));
}
else
{
options = this.element.FindElements(By.XPath(".//option[contains(normalize-space(.), " + EscapeQuotes(text) + ")]"));
}
foreach (IWebElement option in options)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (options.Count == 0 && text.Contains(" "))
{
string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
IList<IWebElement> candidates;
if (string.IsNullOrEmpty(substringWithoutSpace))
{
// hmm, text is either empty or contains only spaces - get all options ...
candidates = this.element.FindElements(By.TagName("option"));
}
else
{
// get candidates via XPATH ...
candidates = this.element.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"));
}
foreach (IWebElement option in candidates)
{
if (text == option.Text)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
}
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate element with text: " + text);
}
}
/// <summary>
/// Select an option by the value.
/// </summary>
/// <param name="value">The value of the option to be selected.</param>
/// <remarks>When given "foo" this method will select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown when no element with the specified value is found.</exception>
public void SelectByValue(string value)
{
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
bool matched = false;
foreach (IWebElement option in options)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with value: " + value);
}
}
/// <summary>
/// Select the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <param name="index">The value of the index attribute of the option to be selected.</param>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified index attribute.</exception>
public void SelectByIndex(int index)
{
string match = index.ToString(CultureInfo.InvariantCulture);
foreach (IWebElement option in this.Options)
{
if (option.GetAttribute("index") == match)
{
SetSelected(option, true);
return;
}
}
throw new NoSuchElementException("Cannot locate option with index: " + index);
}
/// <summary>
/// Clear all selected entries. This is only valid when the SELECT supports multiple selections.
/// </summary>
/// <exception cref="WebDriverException">Thrown when attempting to deselect all options from a SELECT
/// that does not support multiple selections.</exception>
public void DeselectAll()
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect all options if multi-select is supported");
}
foreach (IWebElement option in this.Options)
{
SetSelected(option, false);
}
}
/// <summary>
/// Deselect the option by the text displayed.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified test attribute.</exception>
/// <param name="text">The text of the option to be deselected.</param>
/// <remarks>When given "Bar" this method would deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByText(string text)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
bool matched = false;
StringBuilder builder = new StringBuilder(".//option[normalize-space(.) = ");
builder.Append(EscapeQuotes(text));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
SetSelected(option, false);
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with text: " + text);
}
}
/// <summary>
/// Deselect the option having value matching the specified text.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified value attribute.</exception>
/// <param name="value">The value of the option to deselect.</param>
/// <remarks>When given "foo" this method will deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByValue(string value)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
bool matched = false;
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
SetSelected(option, false);
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with value: " + value);
}
}
/// <summary>
/// Deselect the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified index attribute.</exception>
/// <param name="index">The value of the index attribute of the option to deselect.</param>
public void DeselectByIndex(int index)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
string match = index.ToString(CultureInfo.InvariantCulture);
foreach (IWebElement option in this.Options)
{
if (match == option.GetAttribute("index"))
{
SetSelected(option, false);
return;
}
}
throw new NoSuchElementException("Cannot locate option with index: " + index);
}
private static string EscapeQuotes(string toEscape)
{
// Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1 && toEscape.IndexOf("'", StringComparison.OrdinalIgnoreCase) > -1)
{
bool quoteIsLast = false;
if (toEscape.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase) == toEscape.Length - 1)
{
quoteIsLast = true;
}
List<string> substrings = new List<string>(toEscape.Split('\"'));
if (quoteIsLast && string.IsNullOrEmpty(substrings[substrings.Count - 1]))
{
// If the last character is a quote ('"'), we end up with an empty entry
// at the end of the list, which is unnecessary. We don't want to split
// ignoring *all* empty entries, since that might mask legitimate empty
// strings. Instead, just remove the empty ending entry.
substrings.RemoveAt(substrings.Count - 1);
}
StringBuilder quoted = new StringBuilder("concat(");
for (int i = 0; i < substrings.Count; i++)
{
quoted.Append("\"").Append(substrings[i]).Append("\"");
if (i == substrings.Count - 1)
{
if (quoteIsLast)
{
quoted.Append(", '\"')");
}
else
{
quoted.Append(")");
}
}
else
{
quoted.Append(", '\"', ");
}
}
return quoted.ToString();
}
// Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1)
{
return string.Format(CultureInfo.InvariantCulture, "'{0}'", toEscape);
}
// Otherwise return the quoted string
return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", toEscape);
}
private static string GetLongestSubstringWithoutSpace(string s)
{
string result = string.Empty;
string[] substrings = s.Split(' ');
foreach (string substring in substrings)
{
if (substring.Length > result.Length)
{
result = substring;
}
}
return result;
}
private static void SetSelected(IWebElement option, bool select)
{
bool isSelected = option.Selected;
if ((!isSelected && select) || (isSelected && !select))
{
option.Click();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping
{
private const int IcmpHeaderLengthInBytes = 8;
private const int IpHeaderLengthInBytes = 20;
[ThreadStatic]
private static Random t_idGenerator;
private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
try
{
Task<PingReply> t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ?
SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) :
SendWithPingUtility(address, buffer, timeout, options);
PingReply reply = await t.ConfigureAwait(false);
if (_canceled)
{
throw new OperationCanceledException();
}
return reply;
}
finally
{
Finish();
}
}
private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
EndPoint endPoint = new IPEndPoint(address, 0);
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
// Use a random value as the identifier. This doesn't need to be perfectly random
// or very unpredictable, rather just good enough to avoid unexpected conflicts.
Random rand = t_idGenerator ?? (t_idGenerator = new Random());
ushort identifier = (ushort)rand.Next((int)ushort.MaxValue + 1);
IcmpHeader header = new IcmpHeader()
{
Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
Code = 0,
HeaderChecksum = 0,
Identifier = identifier,
SequenceNumber = 0,
};
byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);
using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
{
socket.ReceiveTimeout = timeout;
socket.SendTimeout = timeout;
// Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.
int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];
long elapsed;
Stopwatch sw = Stopwatch.StartNew();
// Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
// to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
// For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
while ((elapsed = sw.ElapsedMilliseconds) < timeout)
{
Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
new ArraySegment<byte>(receiveBuffer),
SocketFlags.None,
endPoint);
var cts = new CancellationTokenSource();
Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
cts.Cancel();
if (finished != receiveTask)
{
sw.Stop();
return CreateTimedOutPingReply();
}
SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
int bytesReceived = receiveResult.ReceivedBytes;
if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
{
continue; // Not enough bytes to reconstruct IP header + ICMP header.
}
byte type, code;
unsafe
{
fixed (byte* bytesPtr = &receiveBuffer[0])
{
int icmpHeaderOffset = ipHeaderLength;
IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
type = receivedHeader.Type;
code = receivedHeader.Code;
if (identifier != receivedHeader.Identifier
|| type == (byte)IcmpV4MessageType.EchoRequest
|| type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
{
continue;
}
}
}
sw.Stop();
long roundTripTime = sw.ElapsedMilliseconds;
int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
// We want to return a buffer with the actual data we sent out, not including the header data.
byte[] dataBuffer = new byte[bytesReceived - dataOffset];
Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);
IPStatus status = isIpv4
? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
: IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);
return new PingReply(address, options, status, roundTripTime, dataBuffer);
}
// We have exceeded our timeout duration, and no reply has been received.
sw.Stop();
return CreateTimedOutPingReply();
}
}
private async Task<PingReply> SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath;
if (pingExecutable == null)
{
throw new PlatformNotSupportedException(SR.net_ping_utility_not_found);
}
string processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4);
ProcessStartInfo psi = new ProcessStartInfo(pingExecutable, processArgs);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
Process p = new Process() { StartInfo = psi };
var processCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
p.EnableRaisingEvents = true;
p.Exited += (s, e) => processCompletion.SetResult(true);
p.Start();
var cts = new CancellationTokenSource();
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false);
if (finished == timeoutTask && !p.HasExited)
{
// Try to kill the ping process if it didn't return. If it is already in the process of exiting, a Win32Exception will be thrown.
try
{
p.Kill();
}
catch (Win32Exception) { }
return CreateTimedOutPingReply();
}
else
{
cts.Cancel();
if (p.ExitCode == 1 || p.ExitCode == 2)
{
// Throw timeout for known failure return codes from ping functions.
return CreateTimedOutPingReply();
}
try
{
string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false);
long rtt = UnixCommandLinePing.ParseRoundTripTime(output);
return new PingReply(
address,
null, // Ping utility cannot accommodate these, return null to indicate they were ignored.
IPStatus.Success,
rtt,
Array.Empty<byte>()); // Ping utility doesn't deliver this info.
}
catch (Exception)
{
// If the standard output cannot be successfully parsed, throw a generic PingException.
throw new PingException(SR.net_ping);
}
}
}
private PingReply CreateTimedOutPingReply()
{
// Documentation indicates that you should only pay attention to the IPStatus value when
// its value is not "Success", but the rest of these values match that of the Windows implementation.
return new PingReply(new IPAddress(0), null, IPStatus.TimedOut, 0, Array.Empty<byte>());
}
#if DEBUG
static Ping()
{
Debug.Assert(Marshal.SizeOf<IcmpHeader>() == 8, "The size of an ICMP Header must be 8 bytes.");
}
#endif
// Must be 8 bytes total.
[StructLayout(LayoutKind.Sequential)]
internal struct IcmpHeader
{
public byte Type;
public byte Code;
public ushort HeaderChecksum;
public ushort Identifier;
public ushort SequenceNumber;
}
private static unsafe byte[] CreateSendMessageBuffer(IcmpHeader header, byte[] payload)
{
int headerSize = sizeof(IcmpHeader);
byte[] result = new byte[headerSize + payload.Length];
Marshal.Copy(new IntPtr(&header), result, 0, headerSize);
payload.CopyTo(result, headerSize);
ushort checksum = ComputeBufferChecksum(result);
// Jam the checksum into the buffer.
result[2] = (byte)(checksum >> 8);
result[3] = (byte)(checksum & (0xFF));
return result;
}
private static ushort ComputeBufferChecksum(byte[] buffer)
{
// This is using the "deferred carries" approach outlined in RFC 1071.
uint sum = 0;
for (int i = 0; i < buffer.Length; i += 2)
{
// Combine each pair of bytes into a 16-bit number and add it to the sum
ushort element0 = (ushort)((buffer[i] << 8) & 0xFF00);
ushort element1 = (i + 1 < buffer.Length)
? (ushort)(buffer[i + 1] & 0x00FF)
: (ushort)0; // If there's an odd number of bytes, pad by one octet of zeros.
ushort combined = (ushort)(element0 | element1);
sum += (uint)combined;
}
// Add back the "carry bits" which have risen to the upper 16 bits of the sum.
while ((sum >> 16) != 0)
{
var partialSum = sum & 0xFFFF;
var carries = sum >> 16;
sum = partialSum + carries;
}
return unchecked((ushort)~sum);
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using ParquetSharp.Column;
using ParquetSharp.Column.Statistics;
using ParquetSharp.External;
using ParquetSharp.Filter;
using ParquetSharp.Filter2.Predicate;
using ParquetSharp.Hadoop;
using ParquetSharp.Hadoop.Metadata;
using ParquetSharp.IO;
using ParquetSharp.Schema;
using Xunit;
using static ParquetSharp.Column.Encoding;
using static ParquetSharp.Filter2.Predicate.Operators;
namespace ParquetHadoopTests.Hadoop
{
public class TestInputFormat
{
List<BlockMetaData> blocks;
BlockLocation[] hdfsBlocks;
FileStatus fileStatus;
MessageType schema;
FileMetaData fileMetaData;
/*
The test File contains 2-3 hdfs blocks based on the setting of each test, when hdfsBlock size is set to 50: [0-49][50-99]
each row group is of size 10, so the rowGroups layout on hdfs is like:
xxxxx xxxxx
each x is a row group, each groups of x's is a hdfsBlock
*/
// @Before
public void setUp()
{
blocks = new List<BlockMetaData>();
for (int i = 0; i < 10; i++)
{
blocks.add(newBlock(i * 10, 10));
}
schema = MessageTypeParser.parseMessageType("message doc { required binary foo; }");
fileMetaData = new FileMetaData(schema, new Dictionary<string, string>(), "parquet-mr");
}
[Fact]
public void testThrowExceptionWhenMaxSplitSizeIsSmallerThanMinSplitSize()
{
try
{
generateSplitByMinMaxSize(50, 49);
Assert.True(false, "should throw exception when max split size is smaller than the min split size");
}
catch (ParquetDecodingException e)
{
Assert.Equal("maxSplitSize and minSplitSize should be positive and max should be greater or equal to the minSplitSize: maxSplitSize = 49; minSplitSize is 50"
, e.Message);
}
}
[Fact]
public void testThrowExceptionWhenMaxSplitSizeIsNegative()
{
try
{
generateSplitByMinMaxSize(-100, -50);
Assert.True(false, "should throw exception when max split size is negative");
}
catch (ParquetDecodingException e)
{
Assert.Equal("maxSplitSize and minSplitSize should be positive and max should be greater or equal to the minSplitSize: maxSplitSize = -50; minSplitSize is -100"
, e.Message);
}
}
[Fact]
public void testGetFilter()
{
IntColumn intColumn = intColumn("foo");
FilterPredicate p = or(eq(intColumn, 7), eq(intColumn, 12));
Configuration conf = new Configuration();
ParquetInputFormat.setFilterPredicate(conf, p);
Filter read = ParquetInputFormat.getFilter(conf);
Assert.True(read is FilterPredicateCompat);
Assert.Equal(p, ((FilterPredicateCompat)read).getFilterPredicate());
conf = new Configuration();
ParquetInputFormat.setFilterPredicate(conf, not(p));
read = ParquetInputFormat.getFilter(conf);
Assert.True(read is FilterPredicateCompat);
Assert.Equal(and(notEq(intColumn, 7), notEq(intColumn, 12)), ((FilterPredicateCompat)read).getFilterPredicate());
Assert.Equal(FilterCompat.NOOP, ParquetInputFormat.getFilter(new Configuration()));
}
/*
aaaaa bbbbb
*/
[Fact]
public void testGenerateSplitsAlignedWithHDFSBlock()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(50, 50);
shouldSplitBlockSizeBe(splits, 5, 5);
shouldSplitLocationBe(splits, 0, 1);
shouldSplitLengthBe(splits, 50, 50);
splits = generateSplitByMinMaxSize(0, Long.MAX_VALUE);
shouldSplitBlockSizeBe(splits, 5, 5);
shouldSplitLocationBe(splits, 0, 1);
shouldSplitLengthBe(splits, 50, 50);
}
[Fact]
public void testRowGroupNotAlignToHDFSBlock()
{
//Test HDFS blocks size(51) is not multiple of row group size(10)
withHDFSBlockSize(51, 51);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(50, 50);
shouldSplitBlockSizeBe(splits, 5, 5);
shouldSplitLocationBe(splits, 0, 0);//for the second split, the first byte will still be in the first hdfs block, therefore the locations are both 0
shouldSplitLengthBe(splits, 50, 50);
//Test a rowgroup is greater than the hdfsBlock boundary
withHDFSBlockSize(49, 49);
splits = generateSplitByMinMaxSize(50, 50);
shouldSplitBlockSizeBe(splits, 5, 5);
shouldSplitLocationBe(splits, 0, 1);
shouldSplitLengthBe(splits, 50, 50);
/*
aaaa bbbbb c
for the 5th row group, the midpoint is 45, but the end of first hdfsBlock is 44, therefore a new split(b) will be created
for 9th group, the mid point is 85, the end of second block is 88, so it's considered mainly in the 2nd hdfs block, and therefore inserted as
a row group of split b
*/
withHDFSBlockSize(44, 44, 44);
splits = generateSplitByMinMaxSize(40, 50);
shouldSplitBlockSizeBe(splits, 4, 5, 1);
shouldSplitLocationBe(splits, 0, 0, 2);
shouldSplitLengthBe(splits, 40, 50, 10);
}
/*
when min size is 55, max size is 56, the first split will be generated with 6 row groups(size of 10 each), which satisfies split.size>min.size, but not split.size<max.size
aaaaa abbbb
*/
[Fact]
public void testGenerateSplitsNotAlignedWithHDFSBlock()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(55, 56);
shouldSplitBlockSizeBe(splits, 6, 4);
shouldSplitLocationBe(splits, 0, 1);
shouldSplitLengthBe(splits, 60, 40);
withHDFSBlockSize(51, 51);
splits = generateSplitByMinMaxSize(55, 56);
shouldSplitBlockSizeBe(splits, 6, 4);
shouldSplitLocationBe(splits, 0, 1);//since a whole row group of split a is added to the second hdfs block, so the location of split b is still 1
shouldSplitLengthBe(splits, 60, 40);
withHDFSBlockSize(49, 49, 49);
splits = generateSplitByMinMaxSize(55, 56);
shouldSplitBlockSizeBe(splits, 6, 4);
shouldSplitLocationBe(splits, 0, 1);
shouldSplitLengthBe(splits, 60, 40);
}
/*
when the max size is set to be 30, first split will be of size 30,
and when creating second split, it will try to align it to second hdfsBlock, and therefore generates a split of size 20
aaabb cccdd
*/
[Fact]
public void testGenerateSplitsSmallerThanMaxSizeAndAlignToHDFS()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(18, 30);
shouldSplitBlockSizeBe(splits, 3, 2, 3, 2);
shouldSplitLocationBe(splits, 0, 0, 1, 1);
shouldSplitLengthBe(splits, 30, 20, 30, 20);
/*
aaabb cccdd
*/
withHDFSBlockSize(51, 51);
splits = generateSplitByMinMaxSize(18, 30);
shouldSplitBlockSizeBe(splits, 3, 2, 3, 2);
shouldSplitLocationBe(splits, 0, 0, 0, 1);//the first byte of split c is in the first hdfs block
shouldSplitLengthBe(splits, 30, 20, 30, 20);
/*
aaabb cccdd
*/
withHDFSBlockSize(49, 49, 49);
splits = generateSplitByMinMaxSize(18, 30);
shouldSplitBlockSizeBe(splits, 3, 2, 3, 2);
shouldSplitLocationBe(splits, 0, 0, 1, 1);
shouldSplitLengthBe(splits, 30, 20, 30, 20);
}
/*
when the min size is set to be 25, so the second split can not be aligned with the boundary of hdfs block, there for split of size 30 will be created as the 3rd split.
aaabb bcccd
*/
[Fact]
public void testGenerateSplitsCrossHDFSBlockBoundaryToSatisfyMinSize()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(25, 30);
shouldSplitBlockSizeBe(splits, 3, 3, 3, 1);
shouldSplitLocationBe(splits, 0, 0, 1, 1);
shouldSplitLengthBe(splits, 30, 30, 30, 10);
}
/*
when rowGroups size is 10, but min split size is 10, max split size is 18, it will create splits of size 20 and of size 10 and align with hdfsBlocks
aabbc ddeef
*/
[Fact]
public void testMultipleRowGroupsInABlockToAlignHDFSBlock()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByMinMaxSize(10, 18);
shouldSplitBlockSizeBe(splits, 2, 2, 1, 2, 2, 1);
shouldSplitLocationBe(splits, 0, 0, 0, 1, 1, 1);
shouldSplitLengthBe(splits, 20, 20, 10, 20, 20, 10);
/*
aabbc ddeef
notice the first byte of split d is in the first hdfs block:
when adding the 6th row group, although the first byte of it is in the first hdfs block
, but the mid point of the row group is in the second hdfs block, there for a new split(d) is created including that row group
*/
withHDFSBlockSize(51, 51);
splits = generateSplitByMinMaxSize(10, 18);
shouldSplitBlockSizeBe(splits, 2, 2, 1, 2, 2, 1);
shouldSplitLocationBe(splits, 0, 0, 0, 0, 1, 1);// location of split d should be 0, since the first byte is in the first hdfs block
shouldSplitLengthBe(splits, 20, 20, 10, 20, 20, 10);
/*
aabbc ddeef
same as the case where block sizes are 50 50
*/
withHDFSBlockSize(49, 49);
splits = generateSplitByMinMaxSize(10, 18);
shouldSplitBlockSizeBe(splits, 2, 2, 1, 2, 2, 1);
shouldSplitLocationBe(splits, 0, 0, 0, 1, 1, 1);
shouldSplitLengthBe(splits, 20, 20, 10, 20, 20, 10);
}
public sealed class DummyUnboundRecordFilter : UnboundRecordFilter
{
public RecordFilter bind(IEnumerable<ColumnReader> readers)
{
return null;
}
}
[Fact]
public void testOnlyOneKindOfFilterSupported()
{
IntColumn foo = intColumn("foo");
FilterPredicate p = or(eq(foo, 10), eq(foo, 11));
Job job = new Job();
Configuration conf = job.getConfiguration();
ParquetInputFormat.setUnboundRecordFilter(job, typeof(DummyUnboundRecordFilter));
try
{
ParquetInputFormat.setFilterPredicate(conf, p);
Assert.True(false, "this should throw");
}
catch (ArgumentException e)
{
Assert.Equal("You cannot provide a FilterPredicate after providing an UnboundRecordFilter", e.Message);
}
job = new Job();
conf = job.getConfiguration();
ParquetInputFormat.setFilterPredicate(conf, p);
try
{
ParquetInputFormat.setUnboundRecordFilter(job, typeof(DummyUnboundRecordFilter));
Assert.True(false, "this should throw");
}
catch (ArgumentException e)
{
Assert.Equal("You cannot provide an UnboundRecordFilter after providing a FilterPredicate", e.Message);
}
}
public static BlockMetaData makeBlockFromStats(IntStatistics stats, long valueCount)
{
BlockMetaData blockMetaData = new BlockMetaData();
ColumnChunkMetaData column = ColumnChunkMetaData.get(ColumnPath.get("foo"),
PrimitiveTypeName.INT32,
CompressionCodecName.GZIP,
new HashSet<Encoding>(Arrays.asList(Encoding.PLAIN)),
stats,
100l, 100l, valueCount, 100l, 100l);
blockMetaData.addColumn(column);
blockMetaData.setTotalByteSize(200l);
blockMetaData.setRowCount(valueCount);
return blockMetaData;
}
[Fact]
public void testFooterCacheValueIsCurrent()
{
File tempFile = getTempFile();
FileSystem fs = FileSystem.getLocal(new Configuration());
ParquetInputFormat.FootersCacheValue cacheValue = getDummyCacheValue(tempFile, fs);
Assert.True(tempFile.setLastModified(tempFile.lastModified() + 5000));
Assert.False(cacheValue.isCurrent(new ParquetInputFormat.FileStatusWrapper(fs.getFileStatus(new Path(tempFile.getAbsolutePath())))));
}
[Fact]
public void testFooterCacheValueIsNewer()
{
File tempFile = getTempFile();
FileSystem fs = FileSystem.getLocal(new Configuration());
ParquetInputFormat.FootersCacheValue cacheValue = getDummyCacheValue(tempFile, fs);
Assert.True(cacheValue.isNewerThan(null));
Assert.False(cacheValue.isNewerThan(cacheValue));
Assert.True(tempFile.setLastModified(tempFile.lastModified() + 5000));
ParquetInputFormat.FootersCacheValue newerCacheValue = getDummyCacheValue(tempFile, fs);
Assert.True(newerCacheValue.isNewerThan(cacheValue));
Assert.False(cacheValue.isNewerThan(newerCacheValue));
}
[Fact]
public void testDeprecatedConstructorOfParquetInputSplit()
{
withHDFSBlockSize(50, 50);
List<ParquetInputSplit> splits = generateSplitByDeprecatedConstructor(50, 50);
shouldSplitBlockSizeBe(splits, 5, 5);
shouldOneSplitRowGroupOffsetBe(splits.get(0), 0, 10, 20, 30, 40);
shouldOneSplitRowGroupOffsetBe(splits.get(1), 50, 60, 70, 80, 90);
shouldSplitLengthBe(splits, 50, 50);
shouldSplitStartBe(splits, 0, 50);
}
[Fact]
public void testGetFootersReturnsInPredictableOrder()
{
File tempDir = Files.createTempDir();
tempDir.deleteOnExit();
int numFiles = 10; // create a nontrivial number of files so that it actually tests getFooters() returns files in the correct order
string url = "";
for (int i = 0; i < numFiles; i++)
{
File file = new File(tempDir, string.format("part-%05d.parquet", i));
createParquetFile(file);
if (i > 0)
{
url += ",";
}
url += "file:" + file.getAbsolutePath();
}
Job job = new Job();
FileInputFormat.setInputPaths(job, url);
List<Footer> footers = new ParquetInputFormat<Object>().getFooters(job);
for (int i = 0; i < numFiles; i++)
{
Footer footer = footers.get(i);
File file = new File(tempDir, string.format("part-%05d.parquet", i));
Assert.Equal("file:" + file.getAbsolutePath(), footer.getFile().ToString());
}
}
private void createParquetFile(File file)
{
Path path = new Path(file.toURI());
Configuration configuration = new Configuration();
MessageType schema = MessageTypeParser.parseMessageType("message m { required group a {required binary b;}}");
string[] columnPath = { "a", "b" };
ColumnDescriptor c1 = schema.getColumnDescription(columnPath);
byte[] bytes1 = { 0, 1, 2, 3 };
byte[] bytes2 = { 2, 3, 4, 5 };
CompressionCodecName codec = CompressionCodecName.UNCOMPRESSED;
BinaryStatistics stats = new BinaryStatistics();
ParquetFileWriter w = new ParquetFileWriter(configuration, schema, path);
w.start();
w.startBlock(3);
w.startColumn(c1, 5, codec);
w.writeDataPage(2, 4, BytesInput.from(bytes1), stats, BIT_PACKED, BIT_PACKED, PLAIN);
w.writeDataPage(3, 4, BytesInput.from(bytes1), stats, BIT_PACKED, BIT_PACKED, PLAIN);
w.endColumn();
w.endBlock();
w.startBlock(4);
w.startColumn(c1, 7, codec);
w.writeDataPage(7, 4, BytesInput.from(bytes2), stats, BIT_PACKED, BIT_PACKED, PLAIN);
w.endColumn();
w.endBlock();
w.end(new Dictionary<string, string>());
}
private File getTempFile()
{
File tempFile = File.createTempFile("footer_", ".txt");
tempFile.deleteOnExit();
return tempFile;
}
private ParquetInputFormat.FootersCacheValue getDummyCacheValue(File file, FileSystem fs)
{
Path path = new Path(file.getPath());
FileStatus status = fs.getFileStatus(path);
ParquetInputFormat.FileStatusWrapper statusWrapper = new ParquetInputFormat.FileStatusWrapper(status);
ParquetMetadata mockMetadata = mock(typeof(ParquetMetadata));
ParquetInputFormat.FootersCacheValue cacheValue =
new ParquetInputFormat.FootersCacheValue(statusWrapper, new Footer(path, mockMetadata));
Assert.True(cacheValue.isCurrent(statusWrapper));
return cacheValue;
}
private static readonly Dictionary<string, string> extramd;
static TestInputFormat()
{
Dictionary<string, string> md = new Dictionary<string, string>();
md.put("specific", "foo");
extramd = unmodifiableMap(md);
}
private List<ParquetInputSplit> generateSplitByMinMaxSize(long min, long max)
{
return ClientSideMetadataSplitStrategy.generateSplits(
blocks, hdfsBlocks,
fileStatus,
schema.ToString(),
extramd,
min, max);
}
private List<ParquetInputSplit> generateSplitByDeprecatedConstructor(long min, long max)
{
List<ParquetInputSplit> splits = new List<ParquetInputSplit>();
List<ClientSideMetadataSplitStrategy.SplitInfo> splitInfos = ClientSideMetadataSplitStrategy
.generateSplitInfo(blocks, hdfsBlocks, min, max);
for (ClientSideMetadataSplitStrategy.SplitInfo splitInfo : splitInfos)
{
BlockMetaData lastRowGroup = splitInfo.getRowGroups().get(splitInfo.getRowGroupCount() - 1);
long end = lastRowGroup.getStartingPos() + lastRowGroup.getTotalByteSize();
ParquetInputSplit split = new ParquetInputSplit(fileStatus.getPath(),
splitInfo.hdfsBlock.getOffset(), end, splitInfo.hdfsBlock.getHosts(),
splitInfo.rowGroups, schema.ToString(), null, null, extramd);
splits.add(split);
}
return splits;
}
private void shouldSplitStartBe(List<ParquetInputSplit> splits, params long[] offsets)
{
Assert.Equal(message(splits), offsets.Length, splits.Count);
for (int i = 0; i < offsets.Length; i++)
{
Assert.Equal(message(splits) + i, offsets[i], splits.get(i).getStart());
}
}
private void shouldSplitBlockSizeBe(List<ParquetInputSplit> splits, params int[] sizes)
{
Assert.Equal(message(splits), sizes.Length, splits.Count);
for (int i = 0; i < sizes.Length; i++)
{
Assert.Equal(message(splits) + i, sizes[i], splits.get(i).getRowGroupOffsets().Length);
}
}
private void shouldSplitLocationBe(List<ParquetInputSplit> splits, params int[] locations)
{
Assert.Equal(message(splits), locations.Length, splits.Count);
for (int i = 0; i < locations.Length; i++)
{
int loc = locations[i];
ParquetInputSplit split = splits.get(i);
Assert.Equal(message(splits) + i, "[foo" + loc + ".datanode, bar" + loc + ".datanode]", Arrays.ToString(split.getLocations()));
}
}
private void shouldOneSplitRowGroupOffsetBe(ParquetInputSplit split, params int[] rowGroupOffsets)
{
Assert.Equal(split.ToString(), rowGroupOffsets.Length, split.getRowGroupOffsets().Length);
for (int i = 0; i < rowGroupOffsets.Length; i++)
{
Assert.Equal(split.ToString(), rowGroupOffsets[i], split.getRowGroupOffsets()[i]);
}
}
private string message(List<ParquetInputSplit> splits)
{
return string.valueOf(splits) + " " + Arrays.ToString(hdfsBlocks) + "\n";
}
private void shouldSplitLengthBe(List<ParquetInputSplit> splits, params int[] lengths)
{
Assert.Equal(message(splits), lengths.Length, splits.Count);
for (int i = 0; i < lengths.Length; i++)
{
Assert.Equal(message(splits) + i, lengths[i], splits.get(i).getLength());
}
}
private void withHDFSBlockSize(params long[] blockSizes)
{
hdfsBlocks = new BlockLocation[blockSizes.Length];
long offset = 0;
for (int i = 0; i < blockSizes.Length; i++)
{
long blockSize = blockSizes[i];
hdfsBlocks[i] = new BlockLocation(new string[0], new string[] { "foo" + i + ".datanode", "bar" + i + ".datanode" }, offset, blockSize);
offset += blockSize;
}
fileStatus = new FileStatus(offset, false, 2, 50, 0, new Path("hdfs://foo.namenode:1234/bar"));
}
private BlockMetaData newBlock(long start, long compressedBlockSize)
{
BlockMetaData blockMetaData = new BlockMetaData();
long uncompressedSize = compressedBlockSize * 2;//assuming the compression ratio is 2
ColumnChunkMetaData column = ColumnChunkMetaData.get(ColumnPath.get("foo"),
PrimitiveTypeName.BINARY,
CompressionCodecName.GZIP,
new HashSet<Encoding>(Arrays.asList(Encoding.PLAIN)),
new BinaryStatistics(),
start, 0l, 0l, compressedBlockSize, uncompressedSize);
blockMetaData.addColumn(column);
blockMetaData.setTotalByteSize(uncompressedSize);
return blockMetaData;
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
* Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
*
* http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
*
* EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
* cipher to encrypt and authenticate data. It's on-line (the length of a
* message isn't needed to begin processing it), has good performances, it's
* simple and provably secure (provided the underlying block cipher is secure).
*
* Of course, this implementations is NOT thread-safe.
*/
public class EaxBlockCipher
: IAeadBlockCipher
{
private enum Tag : byte { N, H, C };
private SicBlockCipher cipher;
private bool forEncryption;
private int blockSize;
private IMac mac;
private byte[] nonceMac;
private byte[] associatedTextMac;
private byte[] macBlock;
private int macSize;
private byte[] bufBlock;
private int bufOff;
private bool cipherInitialized;
private byte[] initialAssociatedText;
/**
* Constructor that accepts an instance of a block cipher engine.
*
* @param cipher the engine to use
*/
public EaxBlockCipher(
IBlockCipher cipher)
{
blockSize = cipher.GetBlockSize();
mac = new CMac(cipher);
macBlock = new byte[blockSize];
associatedTextMac = new byte[mac.GetMacSize()];
nonceMac = new byte[mac.GetMacSize()];
this.cipher = new SicBlockCipher(cipher);
}
public virtual string AlgorithmName
{
get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; }
}
public virtual IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
public virtual int GetBlockSize()
{
return cipher.GetBlockSize();
}
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
byte[] nonce;
ICipherParameters keyParam;
if (parameters is AeadParameters)
{
AeadParameters param = (AeadParameters) parameters;
nonce = param.GetNonce();
initialAssociatedText = param.GetAssociatedText();
macSize = param.MacSize / 8;
keyParam = param.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV) parameters;
nonce = param.GetIV();
initialAssociatedText = null;
macSize = mac.GetMacSize() / 2;
keyParam = param.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to EAX");
}
bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];
byte[] tag = new byte[blockSize];
// Key reuse implemented in CBC mode of underlying CMac
mac.Init(keyParam);
tag[blockSize - 1] = (byte)Tag.N;
mac.BlockUpdate(tag, 0, blockSize);
mac.BlockUpdate(nonce, 0, nonce.Length);
mac.DoFinal(nonceMac, 0);
// Same BlockCipher underlies this and the mac, so reuse last key on cipher
cipher.Init(true, new ParametersWithIV(null, nonceMac));
Reset();
}
private void InitCipher()
{
if (cipherInitialized)
{
return;
}
cipherInitialized = true;
mac.DoFinal(associatedTextMac, 0);
byte[] tag = new byte[blockSize];
tag[blockSize - 1] = (byte)Tag.C;
mac.BlockUpdate(tag, 0, blockSize);
}
private void CalculateMac()
{
byte[] outC = new byte[blockSize];
mac.DoFinal(outC, 0);
for (int i = 0; i < macBlock.Length; i++)
{
macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
}
}
public virtual void Reset()
{
Reset(true);
}
private void Reset(
bool clearMac)
{
cipher.Reset(); // TODO Redundant since the mac will reset it?
mac.Reset();
bufOff = 0;
Array.Clear(bufBlock, 0, bufBlock.Length);
if (clearMac)
{
Array.Clear(macBlock, 0, macBlock.Length);
}
byte[] tag = new byte[blockSize];
tag[blockSize - 1] = (byte)Tag.H;
mac.BlockUpdate(tag, 0, blockSize);
cipherInitialized = false;
if (initialAssociatedText != null)
{
ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
}
}
public virtual void ProcessAadByte(byte input)
{
if (cipherInitialized)
{
throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
}
mac.Update(input);
}
public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
{
if (cipherInitialized)
{
throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
}
mac.BlockUpdate(inBytes, inOff, len);
}
public virtual int ProcessByte(
byte input,
byte[] outBytes,
int outOff)
{
InitCipher();
return Process(input, outBytes, outOff);
}
public virtual int ProcessBytes(
byte[] inBytes,
int inOff,
int len,
byte[] outBytes,
int outOff)
{
InitCipher();
int resultLen = 0;
for (int i = 0; i != len; i++)
{
resultLen += Process(inBytes[inOff + i], outBytes, outOff + resultLen);
}
return resultLen;
}
public virtual int DoFinal(
byte[] outBytes,
int outOff)
{
InitCipher();
int extra = bufOff;
byte[] tmp = new byte[bufBlock.Length];
bufOff = 0;
if (forEncryption)
{
Check.OutputLength(outBytes, outOff, extra + macSize, "Output buffer too short");
cipher.ProcessBlock(bufBlock, 0, tmp, 0);
Array.Copy(tmp, 0, outBytes, outOff, extra);
mac.BlockUpdate(tmp, 0, extra);
CalculateMac();
Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);
Reset(false);
return extra + macSize;
}
else
{
if (extra < macSize)
throw new InvalidCipherTextException("data too short");
Check.OutputLength(outBytes, outOff, extra - macSize, "Output buffer too short");
if (extra > macSize)
{
mac.BlockUpdate(bufBlock, 0, extra - macSize);
cipher.ProcessBlock(bufBlock, 0, tmp, 0);
Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
}
CalculateMac();
if (!VerifyMac(bufBlock, extra - macSize))
throw new InvalidCipherTextException("mac check in EAX failed");
Reset(false);
return extra - macSize;
}
}
public virtual byte[] GetMac()
{
byte[] mac = new byte[macSize];
Array.Copy(macBlock, 0, mac, 0, macSize);
return mac;
}
public virtual int GetUpdateOutputSize(
int len)
{
int totalData = len + bufOff;
if (!forEncryption)
{
if (totalData < macSize)
{
return 0;
}
totalData -= macSize;
}
return totalData - totalData % blockSize;
}
public virtual int GetOutputSize(
int len)
{
int totalData = len + bufOff;
if (forEncryption)
{
return totalData + macSize;
}
return totalData < macSize ? 0 : totalData - macSize;
}
private int Process(
byte b,
byte[] outBytes,
int outOff)
{
bufBlock[bufOff++] = b;
if (bufOff == bufBlock.Length)
{
Check.OutputLength(outBytes, outOff, blockSize, "Output buffer is too short");
// TODO Could move the ProcessByte(s) calls to here
// InitCipher();
int size;
if (forEncryption)
{
size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
mac.BlockUpdate(outBytes, outOff, blockSize);
}
else
{
mac.BlockUpdate(bufBlock, 0, blockSize);
size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
}
bufOff = 0;
if (!forEncryption)
{
Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
bufOff = macSize;
}
return size;
}
return 0;
}
private bool VerifyMac(byte[] mac, int off)
{
int nonEqual = 0;
for (int i = 0; i < macSize; i++)
{
nonEqual |= (macBlock[i] ^ mac[off + i]);
}
return nonEqual == 0;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible;
using Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding
{
public static class PathfindingHelpers
{
public static bool TryEndNode(ref PathfindingNode endNode, PathfindingArgs pathfindingArgs)
{
if (!Traversable(pathfindingArgs.CollisionMask, pathfindingArgs.Access, endNode))
{
if (pathfindingArgs.Proximity > 0.0f)
{
foreach (var node in BFSPathfinder.GetNodesInRange(pathfindingArgs, false))
{
endNode = node;
return true;
}
}
return false;
}
return true;
}
public static bool DirectionTraversable(int collisionMask, ICollection<string> access, PathfindingNode currentNode, Direction direction)
{
// If it's a diagonal we need to check NSEW to see if we can get to it and stop corner cutting, NE needs N and E etc.
// Given there's different collision layers stored for each node in the graph it's probably not worth it to cache this
// Also this will help with corner-cutting
PathfindingNode northNeighbor = null;
PathfindingNode southNeighbor = null;
PathfindingNode eastNeighbor = null;
PathfindingNode westNeighbor = null;
foreach (var neighbor in currentNode.GetNeighbors())
{
if (neighbor.TileRef.X == currentNode.TileRef.X &&
neighbor.TileRef.Y == currentNode.TileRef.Y + 1)
{
northNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X + 1 &&
neighbor.TileRef.Y == currentNode.TileRef.Y)
{
eastNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X &&
neighbor.TileRef.Y == currentNode.TileRef.Y - 1)
{
southNeighbor = neighbor;
continue;
}
if (neighbor.TileRef.X == currentNode.TileRef.X - 1 &&
neighbor.TileRef.Y == currentNode.TileRef.Y)
{
westNeighbor = neighbor;
continue;
}
}
switch (direction)
{
case Direction.NorthEast:
if (northNeighbor == null || eastNeighbor == null) return false;
if (!Traversable(collisionMask, access, northNeighbor) ||
!Traversable(collisionMask, access, eastNeighbor))
{
return false;
}
break;
case Direction.NorthWest:
if (northNeighbor == null || westNeighbor == null) return false;
if (!Traversable(collisionMask, access, northNeighbor) ||
!Traversable(collisionMask, access, westNeighbor))
{
return false;
}
break;
case Direction.SouthWest:
if (southNeighbor == null || westNeighbor == null) return false;
if (!Traversable(collisionMask, access, southNeighbor) ||
!Traversable(collisionMask, access, westNeighbor))
{
return false;
}
break;
case Direction.SouthEast:
if (southNeighbor == null || eastNeighbor == null) return false;
if (!Traversable(collisionMask, access, southNeighbor) ||
!Traversable(collisionMask, access, eastNeighbor))
{
return false;
}
break;
}
return true;
}
public static bool Traversable(int collisionMask, ICollection<string> access, PathfindingNode node)
{
if ((collisionMask & node.BlockedCollisionMask) != 0)
{
return false;
}
foreach (var reader in node.AccessReaders)
{
if (!reader.IsAllowed(access))
{
return false;
}
}
return true;
}
public static Queue<TileRef> ReconstructPath(Dictionary<PathfindingNode, PathfindingNode> cameFrom, PathfindingNode current)
{
var running = new Stack<TileRef>();
running.Push(current.TileRef);
while (cameFrom.ContainsKey(current))
{
var previousCurrent = current;
current = cameFrom[current];
cameFrom.Remove(previousCurrent);
running.Push(current.TileRef);
}
var result = new Queue<TileRef>(running);
return result;
}
/// <summary>
/// This will reconstruct the path and fill in the tile holes as well
/// </summary>
/// <param name="cameFrom"></param>
/// <param name="current"></param>
/// <returns></returns>
public static Queue<TileRef> ReconstructJumpPath(Dictionary<PathfindingNode, PathfindingNode> cameFrom, PathfindingNode current)
{
var running = new Stack<TileRef>();
running.Push(current.TileRef);
while (cameFrom.ContainsKey(current))
{
var previousCurrent = current;
current = cameFrom[current];
var intermediate = previousCurrent;
cameFrom.Remove(previousCurrent);
var pathfindingSystem = IoCManager.Resolve<IEntitySystemManager>().GetEntitySystem<PathfindingSystem>();
var mapManager = IoCManager.Resolve<IMapManager>();
var grid = mapManager.GetGrid(current.TileRef.GridIndex);
// Get all the intermediate nodes
while (true)
{
var xOffset = 0;
var yOffset = 0;
if (intermediate.TileRef.X < current.TileRef.X)
{
xOffset += 1;
}
else if (intermediate.TileRef.X > current.TileRef.X)
{
xOffset -= 1;
}
else
{
xOffset = 0;
}
if (intermediate.TileRef.Y < current.TileRef.Y)
{
yOffset += 1;
}
else if (intermediate.TileRef.Y > current.TileRef.Y)
{
yOffset -= 1;
}
else
{
yOffset = 0;
}
intermediate = pathfindingSystem.GetNode(grid.GetTileRef(
new Vector2i(intermediate.TileRef.X + xOffset, intermediate.TileRef.Y + yOffset)));
if (intermediate.TileRef != current.TileRef)
{
// Hacky corner cut fix
running.Push(intermediate.TileRef);
continue;
}
break;
}
running.Push(current.TileRef);
}
var result = new Queue<TileRef>(running);
return result;
}
public static float OctileDistance(int dstX, int dstY)
{
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float OctileDistance(PathfindingNode endNode, PathfindingNode currentNode)
{
// "Fast Euclidean" / octile.
// This implementation is written down in a few sources; it just saves doing sqrt.
int dstX = Math.Abs(currentNode.TileRef.X - endNode.TileRef.X);
int dstY = Math.Abs(currentNode.TileRef.Y - endNode.TileRef.Y);
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float OctileDistance(TileRef endTile, TileRef startTile)
{
// "Fast Euclidean" / octile.
// This implementation is written down in a few sources; it just saves doing sqrt.
int dstX = Math.Abs(startTile.X - endTile.X);
int dstY = Math.Abs(startTile.Y - endTile.Y);
if (dstX > dstY)
{
return 1.4f * dstY + (dstX - dstY);
}
return 1.4f * dstX + (dstY - dstX);
}
public static float ManhattanDistance(PathfindingNode endNode, PathfindingNode currentNode)
{
return Math.Abs(currentNode.TileRef.X - endNode.TileRef.X) + Math.Abs(currentNode.TileRef.Y - endNode.TileRef.Y);
}
public static float? GetTileCost(PathfindingArgs pathfindingArgs, PathfindingNode start, PathfindingNode end)
{
if (!pathfindingArgs.NoClip && !Traversable(pathfindingArgs.CollisionMask, pathfindingArgs.Access, end))
{
return null;
}
if (!pathfindingArgs.AllowSpace && end.TileRef.Tile.IsEmpty)
{
return null;
}
var cost = 1.0f;
switch (pathfindingArgs.AllowDiagonals)
{
case true:
cost *= OctileDistance(end, start);
break;
// Manhattan distance
case false:
cost *= ManhattanDistance(end, start);
break;
}
return cost;
}
public static Direction RelativeDirection(PathfindingChunk endChunk, PathfindingChunk startChunk)
{
var xDiff = (endChunk.Indices.X - startChunk.Indices.X) / PathfindingChunk.ChunkSize;
var yDiff = (endChunk.Indices.Y - startChunk.Indices.Y) / PathfindingChunk.ChunkSize;
return RelativeDirection(xDiff, yDiff);
}
public static Direction RelativeDirection(PathfindingNode endNode, PathfindingNode startNode)
{
var xDiff = endNode.TileRef.X - startNode.TileRef.X;
var yDiff = endNode.TileRef.Y - startNode.TileRef.Y;
return RelativeDirection(xDiff, yDiff);
}
public static Direction RelativeDirection(int x, int y)
{
switch (x)
{
case -1:
switch (y)
{
case -1:
return Direction.SouthWest;
case 0:
return Direction.West;
case 1:
return Direction.NorthWest;
default:
throw new InvalidOperationException();
}
case 0:
switch (y)
{
case -1:
return Direction.South;
case 0:
throw new InvalidOperationException();
case 1:
return Direction.North;
default:
throw new InvalidOperationException();
}
case 1:
switch (y)
{
case -1:
return Direction.SouthEast;
case 0:
return Direction.East;
case 1:
return Direction.NorthEast;
default:
throw new InvalidOperationException();
}
default:
throw new InvalidOperationException();
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
#endregion
using System;
using System.Runtime.InteropServices;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
public class TimespecTest
{
[Test]
public void Now_IsInUtc()
{
Assert.AreEqual(DateTimeKind.Utc, Timespec.Now.ToDateTime().Kind);
}
[Test]
public void Now_AgreesWithUtcNow()
{
var timespec = Timespec.Now;
var utcNow = DateTime.UtcNow;
TimeSpan difference = utcNow - timespec.ToDateTime();
// This test is inherently a race - but the two timestamps
// should really be way less that a minute apart.
Assert.IsTrue(difference.TotalSeconds < 60);
}
[Test]
public void InfFuture()
{
var timespec = Timespec.InfFuture;
}
[Test]
public void InfPast()
{
var timespec = Timespec.InfPast;
}
[Test]
public void TimespecSizeIsNativeSize()
{
Assert.AreEqual(Timespec.NativeSize, Marshal.SizeOf(typeof(Timespec)));
}
[Test]
public void ToDateTime()
{
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
new Timespec(IntPtr.Zero, 0).ToDateTime());
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 10, DateTimeKind.Utc).AddTicks(50),
new Timespec(new IntPtr(10), 5000).ToDateTime());
Assert.AreEqual(new DateTime(2015, 7, 21, 4, 21, 48, DateTimeKind.Utc),
new Timespec(new IntPtr(1437452508), 0).ToDateTime());
// before epoch
Assert.AreEqual(new DateTime(1969, 12, 31, 23, 59, 55, DateTimeKind.Utc).AddTicks(10),
new Timespec(new IntPtr(-5), 1000).ToDateTime());
// infinity
Assert.AreEqual(DateTime.MaxValue, Timespec.InfFuture.ToDateTime());
Assert.AreEqual(DateTime.MinValue, Timespec.InfPast.ToDateTime());
// nanos are rounded to ticks are rounded up
Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(1),
new Timespec(IntPtr.Zero, 99).ToDateTime());
// Illegal inputs
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), -2).ToDateTime());
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), 1000 * 1000 * 1000).ToDateTime());
Assert.Throws(typeof(InvalidOperationException),
() => new Timespec(new IntPtr(0), 0, GPRClockType.Monotonic).ToDateTime());
}
[Test]
public void ToDateTime_ReturnsUtc()
{
Assert.AreEqual(DateTimeKind.Utc, new Timespec(new IntPtr(1437452508), 0).ToDateTime().Kind);
Assert.AreNotEqual(DateTimeKind.Unspecified, new Timespec(new IntPtr(1437452508), 0).ToDateTime().Kind);
}
[Test]
public void ToDateTime_Overflow()
{
// we can only get overflow in ticks arithmetic on 64-bit
if (IntPtr.Size == 8)
{
var timespec = new Timespec(new IntPtr(long.MaxValue - 100), 0);
Assert.AreNotEqual(Timespec.InfFuture, timespec);
Assert.AreEqual(DateTime.MaxValue, timespec.ToDateTime());
Assert.AreEqual(DateTime.MinValue, new Timespec(new IntPtr(long.MinValue + 100), 0).ToDateTime());
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test.");
}
}
[Test]
public void ToDateTime_OutOfDateTimeRange()
{
// we can only get out of range on 64-bit, on 32 bit the max
// timestamp is ~ Jan 19 2038, which is far within range of DateTime
// same case for min value.
if (IntPtr.Size == 8)
{
// DateTime range goes up to year 9999, 20000 years from now should
// be out of range.
long seconds = 20000L * 365L * 24L * 3600L;
var timespec = new Timespec(new IntPtr(seconds), 0);
Assert.AreNotEqual(Timespec.InfFuture, timespec);
Assert.AreEqual(DateTime.MaxValue, timespec.ToDateTime());
Assert.AreEqual(DateTime.MinValue, new Timespec(new IntPtr(-seconds), 0).ToDateTime());
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test");
}
}
[Test]
public void FromDateTime()
{
Assert.AreEqual(new Timespec(IntPtr.Zero, 0),
Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(new Timespec(new IntPtr(10), 5000),
Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 10, DateTimeKind.Utc).AddTicks(50)));
Assert.AreEqual(new Timespec(new IntPtr(1437452508), 0),
Timespec.FromDateTime(new DateTime(2015, 7, 21, 4, 21, 48, DateTimeKind.Utc)));
// before epoch
Assert.AreEqual(new Timespec(new IntPtr(-5), 1000),
Timespec.FromDateTime(new DateTime(1969, 12, 31, 23, 59, 55, DateTimeKind.Utc).AddTicks(10)));
// infinity
Assert.AreEqual(Timespec.InfFuture, Timespec.FromDateTime(DateTime.MaxValue));
Assert.AreEqual(Timespec.InfPast, Timespec.FromDateTime(DateTime.MinValue));
// illegal inputs
Assert.Throws(typeof(ArgumentException),
() => Timespec.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified)));
}
[Test]
public void FromDateTime_OutOfTimespecRange()
{
// we can only get overflow in Timespec on 32-bit
if (IntPtr.Size == 4)
{
Assert.AreEqual(Timespec.InfFuture, Timespec.FromDateTime(new DateTime(2040, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(Timespec.InfPast, Timespec.FromDateTime(new DateTime(1800, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
}
else
{
Console.WriteLine("Test cannot be run on this platform, skipping the test.");
}
}
// Test attribute commented out to prevent running as part of the default test suite.
// [Test]
// [Category("Performance")]
public void NowBenchmark()
{
// approx Timespec.Now latency <33ns
BenchmarkUtil.RunBenchmark(10000000, 1000000000, () => { var now = Timespec.Now; });
}
// Test attribute commented out to prevent running as part of the default test suite.
// [Test]
// [Category("Performance")]
public void PreciseNowBenchmark()
{
// approx Timespec.PreciseNow latency <18ns (when compiled with GRPC_TIMERS_RDTSC)
BenchmarkUtil.RunBenchmark(10000000, 1000000000, () => { var now = Timespec.PreciseNow; });
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Pool-wide patches
/// First published in XenServer 4.1.
/// </summary>
public partial class Pool_patch : XenObject<Pool_patch>
{
public Pool_patch()
{
}
public Pool_patch(string uuid,
string name_label,
string name_description,
string version,
long size,
bool pool_applied,
List<XenRef<Host_patch>> host_patches,
List<after_apply_guidance> after_apply_guidance,
XenRef<Pool_update> pool_update,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.size = size;
this.pool_applied = pool_applied;
this.host_patches = host_patches;
this.after_apply_guidance = after_apply_guidance;
this.pool_update = pool_update;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Pool_patch from a Proxy_Pool_patch.
/// </summary>
/// <param name="proxy"></param>
public Pool_patch(Proxy_Pool_patch proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Pool_patch update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
size = update.size;
pool_applied = update.pool_applied;
host_patches = update.host_patches;
after_apply_guidance = update.after_apply_guidance;
pool_update = update.pool_update;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Pool_patch proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
version = proxy.version == null ? null : (string)proxy.version;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
pool_applied = (bool)proxy.pool_applied;
host_patches = proxy.host_patches == null ? null : XenRef<Host_patch>.Create(proxy.host_patches);
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<after_apply_guidance>(proxy.after_apply_guidance);
pool_update = proxy.pool_update == null ? null : XenRef<Pool_update>.Create(proxy.pool_update);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Pool_patch ToProxy()
{
Proxy_Pool_patch result_ = new Proxy_Pool_patch();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.version = (version != null) ? version : "";
result_.size = size.ToString();
result_.pool_applied = pool_applied;
result_.host_patches = (host_patches != null) ? Helper.RefListToStringArray(host_patches) : new string[] {};
result_.after_apply_guidance = (after_apply_guidance != null) ? Helper.ObjectListToStringArray(after_apply_guidance) : new string[] {};
result_.pool_update = (pool_update != null) ? pool_update : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Pool_patch from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Pool_patch(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
version = Marshalling.ParseString(table, "version");
size = Marshalling.ParseLong(table, "size");
pool_applied = Marshalling.ParseBool(table, "pool_applied");
host_patches = Marshalling.ParseSetRef<Host_patch>(table, "host_patches");
after_apply_guidance = Helper.StringArrayToEnumList<after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
pool_update = Marshalling.ParseRef<Pool_update>(table, "pool_update");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Pool_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_applied, other._pool_applied) &&
Helper.AreEqual2(this._host_patches, other._host_patches) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._pool_update, other._pool_update) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Pool_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_patch.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static Pool_patch get_record(Session session, string _pool_patch)
{
return new Pool_patch((Proxy_Pool_patch)session.proxy.pool_patch_get_record(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Get a reference to the pool_patch instance with the specified UUID.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("")]
public static XenRef<Pool_patch> get_by_uuid(Session session, string _uuid)
{
return XenRef<Pool_patch>.Create(session.proxy.pool_patch_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get all the pool_patch instances with the given label.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
[Deprecated("")]
public static List<XenRef<Pool_patch>> get_by_name_label(Session session, string _label)
{
return XenRef<Pool_patch>.Create(session.proxy.pool_patch_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_uuid(Session session, string _pool_patch)
{
return (string)session.proxy.pool_patch_get_uuid(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_label(Session session, string _pool_patch)
{
return (string)session.proxy.pool_patch_get_name_label(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_description(Session session, string _pool_patch)
{
return (string)session.proxy.pool_patch_get_name_description(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Get the version field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_version(Session session, string _pool_patch)
{
return (string)session.proxy.pool_patch_get_version(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Get the size field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static long get_size(Session session, string _pool_patch)
{
return long.Parse((string)session.proxy.pool_patch_get_size(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Get the pool_applied field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static bool get_pool_applied(Session session, string _pool_patch)
{
return (bool)session.proxy.pool_patch_get_pool_applied(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Get the host_patches field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<XenRef<Host_patch>> get_host_patches(Session session, string _pool_patch)
{
return XenRef<Host_patch>.Create(session.proxy.pool_patch_get_host_patches(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<after_apply_guidance> get_after_apply_guidance(Session session, string _pool_patch)
{
return Helper.StringArrayToEnumList<after_apply_guidance>(session.proxy.pool_patch_get_after_apply_guidance(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Get the pool_update field of the given pool_patch.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static XenRef<Pool_update> get_pool_update(Session session, string _pool_patch)
{
return XenRef<Pool_update>.Create(session.proxy.pool_patch_get_pool_update(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_patch)
{
return Maps.convert_from_proxy_string_string(session.proxy.pool_patch_get_other_config(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Set the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_patch, Dictionary<string, string> _other_config)
{
session.proxy.pool_patch_set_other_config(session.uuid, (_pool_patch != null) ? _pool_patch : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_patch, string _key, string _value)
{
session.proxy.pool_patch_add_to_other_config(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_patch, string _key)
{
session.proxy.pool_patch_remove_from_other_config(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("")]
public static string apply(Session session, string _pool_patch, string _host)
{
return (string)session.proxy.pool_patch_apply(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("")]
public static XenRef<Task> async_apply(Session session, string _pool_patch, string _host)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_apply(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse());
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static void pool_apply(Session session, string _pool_patch)
{
session.proxy.pool_patch_pool_apply(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static XenRef<Task> async_pool_apply(Session session, string _pool_patch)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_pool_apply(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("")]
public static string precheck(Session session, string _pool_patch, string _host)
{
return (string)session.proxy.pool_patch_precheck(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse();
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("")]
public static XenRef<Task> async_precheck(Session session, string _pool_patch, string _host)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_precheck(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse());
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static void clean(Session session, string _pool_patch)
{
session.proxy.pool_patch_clean(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static XenRef<Task> async_clean(Session session, string _pool_patch)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_clean(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static void pool_clean(Session session, string _pool_patch)
{
session.proxy.pool_patch_pool_clean(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static XenRef<Task> async_pool_clean(Session session, string _pool_patch)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_pool_clean(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static void destroy(Session session, string _pool_patch)
{
session.proxy.pool_patch_destroy(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("")]
public static XenRef<Task> async_destroy(Session session, string _pool_patch)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_destroy(session.uuid, (_pool_patch != null) ? _pool_patch : "").parse());
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("")]
public static void clean_on_host(Session session, string _pool_patch, string _host)
{
session.proxy.pool_patch_clean_on_host(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse();
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("")]
public static XenRef<Task> async_clean_on_host(Session session, string _pool_patch, string _host)
{
return XenRef<Task>.Create(session.proxy.async_pool_patch_clean_on_host(session.uuid, (_pool_patch != null) ? _pool_patch : "", (_host != null) ? _host : "").parse());
}
/// <summary>
/// Return a list of all the pool_patchs known to the system.
/// First published in XenServer 4.1.
/// Deprecated since .
/// </summary>
/// <param name="session">The session</param>
[Deprecated("")]
public static List<XenRef<Pool_patch>> get_all(Session session)
{
return XenRef<Pool_patch>.Create(session.proxy.pool_patch_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the pool_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_patch>, Pool_patch> get_all_records(Session session)
{
return XenRef<Pool_patch>.Create<Proxy_Pool_patch>(session.proxy.pool_patch_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version;
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// This patch should be applied across the entire pool
/// </summary>
public virtual bool pool_applied
{
get { return _pool_applied; }
set
{
if (!Helper.AreEqual(value, _pool_applied))
{
_pool_applied = value;
Changed = true;
NotifyPropertyChanged("pool_applied");
}
}
}
private bool _pool_applied;
/// <summary>
/// This hosts this patch is applied to.
/// </summary>
public virtual List<XenRef<Host_patch>> host_patches
{
get { return _host_patches; }
set
{
if (!Helper.AreEqual(value, _host_patches))
{
_host_patches = value;
Changed = true;
NotifyPropertyChanged("host_patches");
}
}
}
private List<XenRef<Host_patch>> _host_patches;
/// <summary>
/// What the client should do after this patch has been applied.
/// </summary>
public virtual List<after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
Changed = true;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<after_apply_guidance> _after_apply_guidance;
/// <summary>
/// A reference to the associated pool_update object
/// First published in .
/// </summary>
public virtual XenRef<Pool_update> pool_update
{
get { return _pool_update; }
set
{
if (!Helper.AreEqual(value, _pool_update))
{
_pool_update = value;
Changed = true;
NotifyPropertyChanged("pool_update");
}
}
}
private XenRef<Pool_update> _pool_update;
/// <summary>
/// additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
// 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.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.Collections.Concurrent
{
// Abstract base for a thread-safe dictionary mapping a set of keys (K) to values (V).
//
// To create an actual dictionary, subclass this type and override the protected Factory method
// to instantiate values (V) for the "Add" case.
//
// The key must be of a type that implements IEquatable<K>. The unifier calls IEquality<K>.Equals()
// and Object.GetHashCode() on the keys.
//
// Deadlock risks:
// - Keys may be tested for equality and asked to compute their hashcode while the unifier
// holds its lock. Thus these operations must be written carefully to avoid deadlocks and
// reentrancy in to the table.
//
// - The Factory method will never be called inside the unifier lock. If two threads race to
// enter a value for the same key, the Factory() may get invoked twice for the same key - one
// of them will "win" the race and its result entered into the dictionary - other gets thrown away.
//
// Notes:
// - This class is used to look up types when GetType() or typeof() is invoked.
// That means that this class itself cannot do or call anything that does these
// things.
//
// - For this reason, it chooses not to mimic the official ConcurrentDictionary class
// (I don't even want to risk using delegates.) Even the LowLevel versions of these
// general utility classes may not be low-level enough for this class's purpose.
//
// Thread safety guarantees:
//
// ConcurrentUnifier is fully thread-safe and requires no
// additional locking to be done by callers.
//
// Performance characteristics:
//
// ConcurrentUnifier will not block a reader, even while
// the table is being written. Only one writer is allowed at a time;
// ConcurrentUnifier handles the synchronization that ensures this.
//
// Safety for concurrent readers is ensured as follows:
//
// Each hash bucket is maintained as a stack. Inserts are done under
// a lock; the entry is filled out completely, then "published" by a
// single write to the top of the bucket. This ensures that a reader
// will see a valid snapshot of the bucket, once it has read the head.
//
// On resize, we allocate an entirely new table, rather than resizing
// in place. We fill in the new table completely, under the lock,
// then "publish" it with a single write. Any reader that races with
// this will either see the old table or the new one; each will contain
// the same data.
//
internal abstract class ConcurrentUnifier<K, V>
where K : IEquatable<K>
where V : class
{
protected ConcurrentUnifier()
{
_lock = new Lock();
_container = new Container(this);
}
//
// Retrieve the *unique* value for a given key. If the key was previously not entered into the dictionary,
// this method invokes the overridable Factory() method to create the new value. The Factory() method is
// invoked outside of any locks. If two threads race to enter a value for the same key, the Factory()
// may get invoked twice for the same key - one of them will "win" the race and its result entered into the
// dictionary - other gets thrown away.
//
public V GetOrAdd(K key)
{
Debug.Assert(key != null);
Debug.Assert(!_lock.IsAcquired, "GetOrAdd called while lock already acquired. A possible cause of this is an Equals or GetHashCode method that causes reentrancy in the table.");
int hashCode = key.GetHashCode();
V value;
bool found = _container.TryGetValue(key, hashCode, out value);
#if DEBUG
{
V checkedValue;
bool checkedFound;
// In debug builds, always exercise a locked TryGet (this is a good way to detect deadlock/reentrancy through Equals/GetHashCode()).
using (LockHolder.Hold(_lock))
{
_container.VerifyUnifierConsistency();
int h = key.GetHashCode();
checkedFound = _container.TryGetValue(key, h, out checkedValue);
}
if (found)
{
// State of a key must never go from found to not found, and only one value may exist per key.
Debug.Assert(checkedFound);
if (default(V) == null) // No good way to do the "only one value" check for value types.
Debug.Assert(Object.ReferenceEquals(checkedValue, value));
}
}
#endif //DEBUG
if (found)
return value;
value = this.Factory(key);
using (LockHolder.Hold(_lock))
{
V heyIWasHereFirst;
if (_container.TryGetValue(key, hashCode, out heyIWasHereFirst))
return heyIWasHereFirst;
if (!_container.HasCapacity)
_container.Resize(); // This overwrites the _container field.
_container.Add(key, hashCode, value);
return value;
}
}
protected abstract V Factory(K key);
private volatile Container _container;
private readonly Lock _lock;
private sealed class Container
{
public Container(ConcurrentUnifier<K, V> owner)
{
// Note: This could be done by calling Resize()'s logic but we cannot safely do that as this code path is reached
// during class construction time and Resize() pulls in enough stuff that we get cyclic cctor warnings from the build.
_buckets = new int[_initialCapacity];
for (int i = 0; i < _initialCapacity; i++)
_buckets[i] = -1;
_entries = new Entry[_initialCapacity];
_nextFreeEntry = 0;
_owner = owner;
}
private Container(ConcurrentUnifier<K, V> owner, int[] buckets, Entry[] entries, int nextFreeEntry)
{
_buckets = buckets;
_entries = entries;
_nextFreeEntry = nextFreeEntry;
_owner = owner;
}
public bool TryGetValue(K key, int hashCode, out V value)
{
// Lock acquistion NOT required (but lock inacquisition NOT guaranteed either.)
int bucket = ComputeBucket(hashCode, _buckets.Length);
int i = Volatile.Read(ref _buckets[bucket]);
while (i != -1)
{
if (key.Equals(_entries[i]._key))
{
value = _entries[i]._value;
return true;
}
i = _entries[i]._next;
}
value = default(V);
return false;
}
public void Add(K key, int hashCode, V value)
{
Debug.Assert(_owner._lock.IsAcquired);
int bucket = ComputeBucket(hashCode, _buckets.Length);
int newEntryIdx = _nextFreeEntry;
_entries[newEntryIdx]._key = key;
_entries[newEntryIdx]._value = value;
_entries[newEntryIdx]._hashCode = hashCode;
_entries[newEntryIdx]._next = _buckets[bucket];
_nextFreeEntry++;
// The line that atomically adds the new key/value pair. If the thread is killed before this line executes but after
// we've incremented _nextFreeEntry, this entry is harmlessly leaked until the next resize.
Volatile.Write(ref _buckets[bucket], newEntryIdx);
VerifyUnifierConsistency();
}
public bool HasCapacity
{
get
{
Debug.Assert(_owner._lock.IsAcquired);
return _nextFreeEntry != _entries.Length;
}
}
public void Resize()
{
Debug.Assert(_owner._lock.IsAcquired);
int newSize = HashHelpers.GetPrime(_buckets.Length * 2);
#if DEBUG
newSize = _buckets.Length + 3;
#endif
if (newSize <= _nextFreeEntry)
throw new OutOfMemoryException();
Entry[] newEntries = new Entry[newSize];
int[] newBuckets = new int[newSize];
for (int i = 0; i < newSize; i++)
newBuckets[i] = -1;
// Note that we walk the bucket chains rather than iterating over _entries. This is because we allow for the possibility
// of abandoned entries (with undefined contents) if a thread is killed between allocating an entry and linking it onto the
// bucket chain.
int newNextFreeEntry = 0;
for (int bucket = 0; bucket < _buckets.Length; bucket++)
{
for (int entry = _buckets[bucket]; entry != -1; entry = _entries[entry]._next)
{
newEntries[newNextFreeEntry]._key = _entries[entry]._key;
newEntries[newNextFreeEntry]._value = _entries[entry]._value;
newEntries[newNextFreeEntry]._hashCode = _entries[entry]._hashCode;
int newBucket = ComputeBucket(newEntries[newNextFreeEntry]._hashCode, newSize);
newEntries[newNextFreeEntry]._next = newBuckets[newBucket];
newBuckets[newBucket] = newNextFreeEntry;
newNextFreeEntry++;
}
}
// The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if
// a thread died between the time between we allocated the entry and the time we link it into the bucket stack.
Debug.Assert(newNextFreeEntry <= _nextFreeEntry);
// The line that atomically installs the resize. If this thread is killed before this point,
// the table remains full and the next guy attempting an add will have to redo the resize.
_owner._container = new Container(_owner, newBuckets, newEntries, newNextFreeEntry);
_owner._container.VerifyUnifierConsistency();
}
private static int ComputeBucket(int hashCode, int numBuckets)
{
int bucket = (hashCode & 0x7fffffff) % numBuckets;
return bucket;
}
[Conditional("DEBUG")]
public void VerifyUnifierConsistency()
{
#if DEBUG
// There's a point at which this check becomes gluttonous, even by checked build standards...
if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100)))
return;
Debug.Assert(_owner._lock.IsAcquired);
Debug.Assert(_nextFreeEntry >= 0 && _nextFreeEntry <= _entries.Length);
int numEntriesEncountered = 0;
for (int bucket = 0; bucket < _buckets.Length; bucket++)
{
int walk1 = _buckets[bucket];
int walk2 = _buckets[bucket]; // walk2 advances two elements at a time - if walk1 ever meets walk2, we've detected a cycle.
while (walk1 != -1)
{
numEntriesEncountered++;
Debug.Assert(walk1 >= 0 && walk1 < _nextFreeEntry);
Debug.Assert(walk2 >= -1 && walk2 < _nextFreeEntry);
Debug.Assert(_entries[walk1]._key != null);
int hashCode = _entries[walk1]._key.GetHashCode();
Debug.Assert(hashCode == _entries[walk1]._hashCode);
int storedBucket = ComputeBucket(_entries[walk1]._hashCode, _buckets.Length);
Debug.Assert(storedBucket == bucket);
walk1 = _entries[walk1]._next;
if (walk2 != -1)
walk2 = _entries[walk2]._next;
if (walk2 != -1)
walk2 = _entries[walk2]._next;
if (walk1 == walk2 && walk2 != -1)
Debug.Fail("Bucket " + bucket + " has a cycle in its linked list.");
}
}
// The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if
// a thread died between the time between we allocated the entry and the time we link it into the bucket stack.
Debug.Assert(numEntriesEncountered <= _nextFreeEntry);
#endif //DEBUG
}
private readonly int[] _buckets;
private readonly Entry[] _entries;
private int _nextFreeEntry;
private readonly ConcurrentUnifier<K, V> _owner;
private const int _initialCapacity = 5;
}
private struct Entry
{
public K _key;
public V _value;
public int _hashCode;
public int _next;
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// represents values used in dead reckoning algorithms
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(Vector3Float))]
public partial class DeadReckoningParameter
{
/// <summary>
/// enumeration of what dead reckoning algorighm to use
/// </summary>
private byte _deadReckoningAlgorithm;
/// <summary>
/// other parameters to use in the dead reckoning algorithm
/// </summary>
private byte[] _otherParameters = new byte[15];
/// <summary>
/// Linear acceleration of the entity
/// </summary>
private Vector3Float _entityLinearAcceleration = new Vector3Float();
/// <summary>
/// angular velocity of the entity
/// </summary>
private Vector3Float _entityAngularVelocity = new Vector3Float();
/// <summary>
/// Initializes a new instance of the <see cref="DeadReckoningParameter"/> class.
/// </summary>
public DeadReckoningParameter()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(DeadReckoningParameter left, DeadReckoningParameter right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(DeadReckoningParameter left, DeadReckoningParameter right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._deadReckoningAlgorithm
marshalSize += 15 * 1; // _otherParameters
marshalSize += this._entityLinearAcceleration.GetMarshalledSize(); // this._entityLinearAcceleration
marshalSize += this._entityAngularVelocity.GetMarshalledSize(); // this._entityAngularVelocity
return marshalSize;
}
/// <summary>
/// Gets or sets the enumeration of what dead reckoning algorighm to use
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "deadReckoningAlgorithm")]
public byte DeadReckoningAlgorithm
{
get
{
return this._deadReckoningAlgorithm;
}
set
{
this._deadReckoningAlgorithm = value;
}
}
/// <summary>
/// Gets or sets the other parameters to use in the dead reckoning algorithm
/// </summary>
[XmlArray(ElementName = "otherParameters")]
public byte[] OtherParameters
{
get
{
return this._otherParameters;
}
set
{
this._otherParameters = value;
}
}
/// <summary>
/// Gets or sets the Linear acceleration of the entity
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "entityLinearAcceleration")]
public Vector3Float EntityLinearAcceleration
{
get
{
return this._entityLinearAcceleration;
}
set
{
this._entityLinearAcceleration = value;
}
}
/// <summary>
/// Gets or sets the angular velocity of the entity
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "entityAngularVelocity")]
public Vector3Float EntityAngularVelocity
{
get
{
return this._entityAngularVelocity;
}
set
{
this._entityAngularVelocity = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._deadReckoningAlgorithm);
for (int idx = 0; idx < this._otherParameters.Length; idx++)
{
dos.WriteByte(this._otherParameters[idx]);
}
this._entityLinearAcceleration.Marshal(dos);
this._entityAngularVelocity.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._deadReckoningAlgorithm = dis.ReadUnsignedByte();
for (int idx = 0; idx < this._otherParameters.Length; idx++)
{
this._otherParameters[idx] = dis.ReadByte();
}
this._entityLinearAcceleration.Unmarshal(dis);
this._entityAngularVelocity.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<DeadReckoningParameter>");
try
{
sb.AppendLine("<deadReckoningAlgorithm type=\"byte\">" + this._deadReckoningAlgorithm.ToString(CultureInfo.InvariantCulture) + "</deadReckoningAlgorithm>");
for (int idx = 0; idx < this._otherParameters.Length; idx++)
{
sb.AppendLine("<otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"byte\">" + this._otherParameters[idx] + "</otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("<entityLinearAcceleration>");
this._entityLinearAcceleration.Reflection(sb);
sb.AppendLine("</entityLinearAcceleration>");
sb.AppendLine("<entityAngularVelocity>");
this._entityAngularVelocity.Reflection(sb);
sb.AppendLine("</entityAngularVelocity>");
sb.AppendLine("</DeadReckoningParameter>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as DeadReckoningParameter;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(DeadReckoningParameter obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._deadReckoningAlgorithm != obj._deadReckoningAlgorithm)
{
ivarsEqual = false;
}
if (obj._otherParameters.Length != 15)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < 15; idx++)
{
if (this._otherParameters[idx] != obj._otherParameters[idx])
{
ivarsEqual = false;
}
}
}
if (!this._entityLinearAcceleration.Equals(obj._entityLinearAcceleration))
{
ivarsEqual = false;
}
if (!this._entityAngularVelocity.Equals(obj._entityAngularVelocity))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._deadReckoningAlgorithm.GetHashCode();
for (int idx = 0; idx < 15; idx++)
{
result = GenerateHash(result) ^ this._otherParameters[idx].GetHashCode();
}
result = GenerateHash(result) ^ this._entityLinearAcceleration.GetHashCode();
result = GenerateHash(result) ^ this._entityAngularVelocity.GetHashCode();
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Diagnostics.SymbolStore;
using System.Reflection;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MethodBuilder : MethodInfo, _MethodBuilder
{
#region Private Data Members
// Identity
internal String m_strName; // The name of the method
private MethodToken m_tkMethod; // The token of this method
private ModuleBuilder m_module;
internal TypeBuilder m_containingType;
// IL
private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
internal LocalSymInfo m_localSymInfo; // keep track debugging local information
internal ILGenerator m_ilGenerator; // Null if not used.
private byte[] m_ubBody; // The IL for the method
private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
private bool m_bIsGlobalMethod;
private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not.
// Attributes
private MethodAttributes m_iAttributes;
private CallingConventions m_callingConvention;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
private SignatureHelper m_signature;
internal Type[] m_parameterTypes;
private ParameterBuilder m_retParam;
private Type m_returnType;
private Type[] m_returnTypeRequiredCustomModifiers;
private Type[] m_returnTypeOptionalCustomModifiers;
private Type[][] m_parameterTypeRequiredCustomModifiers;
private Type[][] m_parameterTypeOptionalCustomModifiers;
// Generics
private GenericTypeParameterBuilder[] m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod);
}
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
Init(name, attributes, callingConvention,
returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
mod, type, bIsGlobalMethod);
}
private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
if (name[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
if (mod == null)
throw new ArgumentNullException("mod");
Contract.EndContractBlock();
if (parameterTypes != null)
{
foreach(Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException("parameterTypes");
}
}
m_strName = name;
m_module = mod;
m_containingType = type;
//
//if (returnType == null)
//{
// m_returnType = typeof(void);
//}
//else
{
m_returnType = returnType;
}
if ((attributes & MethodAttributes.Static) == 0)
{
// turn on the has this calling convention
callingConvention = callingConvention | CallingConventions.HasThis;
}
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual"));
}
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
{
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
(MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));
}
}
m_callingConvention = callingConvention;
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length);
}
else
{
m_parameterTypes = null;
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
m_bIsBaked = false;
m_fInitLocals = true;
m_localSymInfo = new LocalSymInfo();
m_ubBody = null;
m_ilGenerator = null;
// Default is managed IL. Manged IL has bit flag 0x0020 set off
m_dwMethodImplFlags = MethodImplAttributes.IL;
}
#endregion
#region Internal Members
internal void CheckContext(params Type[][] typess)
{
m_module.CheckContext(typess);
}
internal void CheckContext(params Type[] types)
{
m_module.CheckContext(types);
}
[System.Security.SecurityCritical] // auto-generated
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
if (il == null)
{
throw new ArgumentNullException("il");
}
Contract.EndContractBlock();
__ExceptionInfo[] excp;
int counter=0;
int[] filterAddrs;
int[] catchAddrs;
int[] catchEndAddrs;
Type[] catchClass;
int[] type;
int numCatch;
int start, end;
ModuleBuilder dynMod = (ModuleBuilder) m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
{
// you don't need to call DefineBody when you get your ILGenerator
// through MethodBuilder::GetILGenerator.
//
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
}
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
}
m_ubBody = il.BakeByteArray();
m_mdMethodFixups = il.GetTokenFixups();
//Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions();
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
m_exceptions = new ExceptionHandler[numExceptions];
for (int i = 0; i < excp.Length; i++)
{
filterAddrs = excp[i].GetFilterAddresses();
catchAddrs = excp[i].GetCatchAddresses();
catchEndAddrs = excp[i].GetCatchEndAddresses();
catchClass = excp[i].GetCatchClass();
numCatch = excp[i].GetNumberOfCatches();
start = excp[i].GetStartAddress();
end = excp[i].GetEndAddress();
type = excp[i].GetExceptionTypes();
for (int j = 0; j < numCatch; j++)
{
int tkExceptionClass = 0;
if (catchClass[j] != null)
{
tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
}
switch (type[j])
{
case __ExceptionInfo.None:
case __ExceptionInfo.Fault:
case __ExceptionInfo.Filter:
m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
case __ExceptionInfo.Finally:
m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
}
}
}
}
m_bIsBaked=true;
if (dynMod.GetSymWriter() != null)
{
// set the debugging information such as scope and line number
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter();
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
// call OpenScope because OpenMethod no longer implicitly creating
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
if (m_symCustomAttrs != null)
{
foreach(SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter().SetSymAttribute(
new SymbolToken (MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
}
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
symWriter.CloseScope(il.ILOffset);
symWriter.CloseMethod();
}
}
// This is only called from TypeBuilder.CreateType after the method has been created
internal void ReleaseBakedStructures()
{
if (!m_bIsBaked)
{
// We don't need to do anything here if we didn't baked the method body
return;
}
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes()
{
if (m_parameterTypes == null)
m_parameterTypes = EmptyArray<Type>.Value;
return m_parameterTypes;
}
internal static Type GetMethodBaseReturnType(MethodBase method)
{
MethodInfo mi = null;
ConstructorInfo ci = null;
if ( (mi = method as MethodInfo) != null )
{
return mi.ReturnType;
}
else if ( (ci = method as ConstructorInfo) != null)
{
return ci.GetReturnType();
}
else
{
Contract.Assert(false, "We should never get here!");
return null;
}
}
internal void SetToken(MethodToken token)
{
m_tkMethod = token;
}
internal byte[] GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
internal int[] GetTokenFixups()
{
return m_mdMethodFixups;
}
[System.Security.SecurityCritical] // auto-generated
internal SignatureHelper GetMethodSignature()
{
if (m_parameterTypes == null)
m_parameterTypes = EmptyArray<Type>.Value;
m_signature = SignatureHelper.GetMethodSigHelper (m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
return m_signature;
}
// Returns a buffer whose initial signatureLength bytes contain encoded local signature.
internal byte[] GetLocalSignature(out int signatureLength)
{
if (m_localSignature != null)
{
signatureLength = m_localSignature.Length;
return m_localSignature;
}
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
{
// If user is using ILGenerator::DeclareLocal, then get local signaturefrom there.
return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
}
}
return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
}
internal int GetMaxStack()
{
if (m_ilGenerator != null)
{
return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
}
else
{
// this is the case when client provide an array of IL byte stream rather than going through ILGenerator.
return m_maxStack;
}
}
internal ExceptionHandler[] GetExceptionHandlers()
{
return m_exceptions;
}
internal int ExceptionHandlerCount
{
get { return m_exceptions != null ? m_exceptions.Length : 0; }
}
internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num=0;
if (excp==null)
{
return 0;
}
for (int i=0; i<excp.Length; i++)
{
num+=excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
{
return (m_containingType != null && m_containingType.IsCreated());
}
internal TypeBuilder GetTypeBuilder()
{
return m_containingType;
}
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
#endregion
#region Object Overrides
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj) {
if (!(obj is MethodBuilder)) {
return false;
}
if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) {
return false;
}
if (m_iAttributes!=(((MethodBuilder)obj).m_iAttributes)) {
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
if (thatSig.Equals(GetMethodSignature())) {
return true;
}
return false;
}
public override int GetHashCode()
{
return this.m_strName.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(1000);
sb.Append("Name: " + m_strName + " " + Environment.NewLine);
sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine);
sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine);
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
return m_strName;
}
}
internal int MetadataTokenInternal
{
get
{
return GetToken().Token;
}
}
public override Module Module
{
get
{
return m_containingType.Module;
}
}
public override Type DeclaringType
{
get
{
if (m_containingType.m_isHiddenGlobalType == true)
return null;
return m_containingType;
}
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get
{
return null;
}
}
public override Type ReflectedType
{
get
{
return DeclaringType;
}
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_dwMethodImplFlags;
}
public override MethodAttributes Attributes
{
get { return m_iAttributes; }
}
public override CallingConventions CallingConvention
{
get {return m_callingConvention;}
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecurityCritical
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecuritySafeCritical
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override bool IsSecurityTransparent
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
#endregion
#region MethodInfo Overrides
public override MethodInfo GetBaseDefinition()
{
return this;
}
public override Type ReturnType
{
get
{
return m_returnType;
}
}
[Pure]
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.GetParameters();
}
public override ParameterInfo ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.ReturnParameter;
}
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region Generic Members
public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } }
public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } }
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod { get { return m_inst != null; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
{
if (names == null)
throw new ArgumentNullException("names");
if (names.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names");
Contract.EndContractBlock();
if (m_inst != null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet"));
for (int i = 0; i < names.Length; i ++)
if (names[i] == null)
throw new ArgumentNullException("names");
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked"));
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
for (int i = 0; i < names.Length; i ++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
internal void ThrowIfGeneric () { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException (); }
#endregion
#region Public Members
[System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
// we only "tokenize" a method when requested. But the order in which the methods are tokenized
// didn't change: the same order the MethodBuilders are constructed. The recursion introduced
// will overflow the stack when there are many methods on the same type (10000 in my experiment).
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
// I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
MethodBuilder currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
// We need to lock here to prevent a method from being "tokenized" twice.
// We don't need to synchronize this with Type.DefineMethod because it only appends newly
// constructed MethodBuilders to the end of m_listMethods
lock (m_containingType.m_listMethods)
{
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
// If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller
// than the index of the current method.
for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i)
{
currentMethod = m_containingType.m_listMethods[i];
currentToken = currentMethod.GetTokenNoLock();
if (currentMethod == this)
break;
}
m_containingType.m_lastTokenizedMethod = i;
}
Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
Contract.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
[System.Security.SecurityCritical] // auto-generated
private MethodToken GetTokenNoLock()
{
Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);
m_tkMethod = new MethodToken(token);
if (m_inst != null)
foreach (GenericTypeParameterBuilder tb in m_inst)
if (!tb.m_type.IsCreated()) tb.m_type.CreateType();
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags);
return m_tkMethod;
}
public void SetParameters (params Type[] parameterTypes)
{
CheckContext(parameterTypes);
SetSignature (null, null, null, parameterTypes, null, null);
}
public void SetReturnType (Type returnType)
{
CheckContext(returnType);
SetSignature (returnType, null, null, null, null, null);
}
public void SetSignature(
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
if (m_tkMethod.Token != 0)
return;
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
ThrowIfGeneric();
if (returnType != null)
{
m_returnType = returnType;
}
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy (parameterTypes, m_parameterTypes, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
[System.Security.SecuritySafeCritical] // auto-generated
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
Contract.EndContractBlock();
ThrowIfGeneric();
m_containingType.ThrowIfCreated ();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
attributes = attributes & ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
ThrowIfGeneric ();
// set Marshal info for the return type
m_containingType.ThrowIfCreated();
if (m_retParam == null)
{
m_retParam = new ParameterBuilder(this, 0, 0, null);
}
m_retParam.SetMarshal(unmanagedMarshal);
}
private List<SymCustomAttr> m_symCustomAttrs;
private struct SymCustomAttr
{
public SymCustomAttr(String name, byte[] data)
{
m_name = name;
m_data = data;
}
public String m_name;
public byte[] m_data;
}
public void SetSymCustomAttribute(String name, byte[] data)
{
// Note that this API is rarely used. Support for custom attributes in PDB files was added in
// Whidbey and as of 8/2007 the only known user is the C# compiler. There seems to be little
// value to this for Reflection.Emit users since they can always use metadata custom attributes.
// Some versions of the symbol writer used in the CLR will ignore these entirely. This API has
// been removed from the Silverlight API surface area, but we should also consider removing it
// from future desktop product versions as well.
ThrowIfGeneric ();
// This is different from CustomAttribute. This is stored into the SymWriter.
m_containingType.ThrowIfCreated();
ModuleBuilder dynMod = (ModuleBuilder) m_module;
if ( dynMod.GetSymWriter() == null)
{
// Cannot SetSymCustomAttribute when it is not a debug module
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
}
if (m_symCustomAttrs == null)
m_symCustomAttrs = new List<SymCustomAttr>();
m_symCustomAttrs.Add(new SymCustomAttr(name, data));
}
#if FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
{
if (pset == null)
throw new ArgumentNullException("pset");
Contract.EndContractBlock();
ThrowIfGeneric ();
#pragma warning disable 618
if (!Enum.IsDefined(typeof(SecurityAction), action) ||
action == SecurityAction.RequestMinimum ||
action == SecurityAction.RequestOptional ||
action == SecurityAction.RequestRefuse)
{
throw new ArgumentOutOfRangeException("action");
}
#pragma warning restore 618
// cannot declarative security after type is created
m_containingType.ThrowIfCreated();
// Translate permission set into serialized format (uses standard binary serialization format).
byte[] blob = null;
int length = 0;
if (!pset.IsEmpty())
{
blob = pset.EncodeXml();
length = blob.Length;
}
// Write the blob into the metadata.
TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length);
}
#endif // FEATURE_CAS_POLICY
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (il == null)
{
throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array"));
}
if (maxStack < 0)
{
throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
}
m_containingType.ThrowIfCreated();
ThrowIfGeneric();
byte[] newLocalSignature = null;
ExceptionHandler[] newHandlers = null;
int[] newTokenFixups = null;
byte[] newIL = (byte[])il.Clone();
if (localSignature != null)
{
newLocalSignature = (byte[])localSignature.Clone();
}
if (exceptionHandlers != null)
{
newHandlers = ToArray(exceptionHandlers);
CheckExceptionHandlerRanges(newHandlers, newIL.Length);
// Note: Fixup entries for type tokens stored in ExceptionHandlers are added by the method body emitter.
}
if (tokenFixups != null)
{
newTokenFixups = ToArray(tokenFixups);
int maxTokenOffset = newIL.Length - 4;
for (int i = 0; i < newTokenFixups.Length; i++)
{
// Check that fixups are within the range of this method's IL, otherwise some random memory might get "fixed up".
if (newTokenFixups[i] < 0 || newTokenFixups[i] > maxTokenOffset)
{
throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxTokenOffset));
}
}
}
m_ubBody = newIL;
m_localSignature = newLocalSignature;
m_exceptions = newHandlers;
m_mdMethodFixups = newTokenFixups;
m_maxStack = maxStack;
// discard IL generator, all information stored in it is now irrelevant
m_ilGenerator = null;
m_bIsBaked = true;
}
private static T[] ToArray<T>(IEnumerable<T> sequence)
{
T[] array = sequence as T[];
if (array != null)
{
return (T[])array.Clone();
}
return new List<T>(sequence).ToArray();
}
private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset)
{
// Basic checks that the handler ranges are within the method body (ranges are end-exclusive).
// Doesn't verify that the ranges are otherwise correct - it is very well possible to emit invalid IL.
for (int i = 0; i < exceptionHandlers.Length; i++)
{
var handler = exceptionHandlers[i];
if (handler.m_filterOffset > maxOffset || handler.m_tryEndOffset > maxOffset || handler.m_handlerEndOffset > maxOffset)
{
throw new ArgumentOutOfRangeException("exceptionHandlers[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset));
}
// Type token might be 0 if the ExceptionHandler was created via a default constructor.
// Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it,
// and we can't check for valid tokens until the module is baked.
if (handler.Kind == ExceptionHandlingClauseOptions.Clause && handler.ExceptionTypeToken == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", handler.ExceptionTypeToken), "exceptionHandlers[" + i + "]");
}
}
}
/// <summary>
/// Obsolete.
/// </summary>
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void CreateMethodBody(byte[] il, int count)
{
ThrowIfGeneric();
// Note that when user calls this function, there are a few information that client is
// not able to supply: local signature, exception handlers, max stack size, a list of Token fixup, a list of RVA fixup
if (m_bIsBaked)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
}
m_containingType.ThrowIfCreated();
if (il != null && (count < 0 || count > il.Length))
{
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (il == null)
{
m_ubBody = null;
return;
}
m_ubBody = new byte[count];
Array.Copy(il,m_ubBody,count);
m_localSignature = null;
m_exceptions = null;
m_mdMethodFixups = null;
m_maxStack = DefaultMaxStack;
m_bIsBaked = true;
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric ();
m_containingType.ThrowIfCreated ();
m_dwMethodImplFlags = attributes;
m_canBeRuntimeImpl = true;
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes);
}
public ILGenerator GetILGenerator() {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this);
return m_ilGenerator;
}
public ILGenerator GetILGenerator(int size) {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
ThrowIfGeneric ();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this, size);
return m_ilGenerator;
}
private void ThrowIfShouldNotHaveBody() {
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
m_isDllImport)
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"));
}
}
public bool InitLocals
{
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
get { ThrowIfGeneric (); return m_fInitLocals; }
set { ThrowIfGeneric (); m_fInitLocals = value; }
}
public Module GetModule()
{
return GetModuleBuilder();
}
public String Signature
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return GetMethodSignature().ToString();
}
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException("con");
if (binaryAttribute == null)
throw new ArgumentNullException("binaryAttribute");
Contract.EndContractBlock();
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal,
((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
if (IsKnownCA(con))
ParseCA(con, binaryAttribute);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException("customBuilder");
Contract.EndContractBlock();
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con, customBuilder.m_blob);
}
// this method should return true for any and every ca that requires more work
// than just setting the ca
private bool IsKnownCA(ConstructorInfo con)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true;
else if (caType == typeof(DllImportAttribute)) return true;
else return false;
}
private void ParseCA(ConstructorInfo con, byte[] blob)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
// for now we simply set a flag that relaxes the check when saving and
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
else if (caType == typeof(DllImportAttribute)) {
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
}
internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
#endregion
#if !FEATURE_CORECLR
void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
internal class LocalSymInfo
{
// This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
internal String[] m_strName;
internal byte[][] m_ubSignature;
internal int[] m_iLocalSlot;
internal int[] m_iStartOffset;
internal int[] m_iEndOffset;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
internal String[] m_namespace;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
#region Constructor
internal LocalSymInfo()
{
// initialize data variables
m_iLocalSymCount = 0;
m_iNameSpaceCount = 0;
}
#endregion
#region Private Members
private void EnsureCapacityNamespace()
{
if (m_iNameSpaceCount == 0)
{
m_namespace = new String[InitialSize];
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
String [] strTemp = new String [checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, strTemp, m_iNameSpaceCount);
m_namespace = strTemp;
}
}
private void EnsureCapacity()
{
if (m_iLocalSymCount == 0)
{
// First time. Allocate the arrays.
m_strName = new String[InitialSize];
m_ubSignature = new byte[InitialSize][];
m_iLocalSlot = new int[InitialSize];
m_iStartOffset = new int[InitialSize];
m_iEndOffset = new int[InitialSize];
}
else if (m_iLocalSymCount == m_strName.Length)
{
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
int[] temp = new int [newSize];
Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount);
m_iLocalSlot = temp;
temp = new int [newSize];
Array.Copy(m_iStartOffset, temp, m_iLocalSymCount);
m_iStartOffset = temp;
temp = new int [newSize];
Array.Copy(m_iEndOffset, temp, m_iLocalSymCount);
m_iEndOffset = temp;
String [] strTemp = new String [newSize];
Array.Copy(m_strName, strTemp, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount);
m_ubSignature = ubTemp;
}
}
#endregion
#region Internal Members
internal void AddLocalSymInfo(String strName,byte[] signature,int slot,int startOffset,int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
m_iStartOffset[m_iLocalSymCount] = startOffset;
m_iEndOffset[m_iLocalSymCount] = endOffset;
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
checked {m_iLocalSymCount++; }
}
internal void AddUsingNamespace(String strNamespace)
{
EnsureCapacityNamespace();
m_namespace[m_iNameSpaceCount] = strNamespace;
checked { m_iNameSpaceCount++; }
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
for (i = 0; i < m_iLocalSymCount; i ++)
{
symWriter.DefineLocalVariable(
m_strName[i],
FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
0, // addr2 is not used yet
0, // addr3 is not used
m_iStartOffset[i],
m_iEndOffset[i]);
}
for (i = 0; i < m_iNameSpaceCount; i ++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
}
#endregion
}
/// <summary>
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
[ComVisible(false)]
public struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
internal readonly int m_filterOffset;
internal readonly int m_handlerStartOffset;
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
public int ExceptionTypeToken
{
get { return m_exceptionClass; }
}
public int TryOffset
{
get { return m_tryStartOffset; }
}
public int TryLength
{
get { return m_tryEndOffset - m_tryStartOffset; }
}
public int FilterOffset
{
get { return m_filterOffset; }
}
public int HandlerOffset
{
get { return m_handlerStartOffset; }
}
public int HandlerLength
{
get { return m_handlerEndOffset - m_handlerStartOffset; }
}
public ExceptionHandlingClauseOptions Kind
{
get { return m_kind; }
}
#region Constructors
/// <summary>
/// Creates a description of an exception handler.
/// </summary>
/// <param name="tryOffset">The offset of the first instruction protected by this handler.</param>
/// <param name="tryLength">The number of bytes protected by this handler.</param>
/// <param name="filterOffset">The filter code begins at the specified offset and ends at the first instruction of the handler block. Specify 0 if not applicable (this is not a filter handler).</param>
/// <param name="handlerOffset">The offset of the first instruction of this handler.</param>
/// <param name="handlerLength">The number of bytes of the handler.</param>
/// <param name="kind">The kind of handler, the handler might be a catch handler, filter handler, fault handler, or finally handler.</param>
/// <param name="exceptionTypeToken">The token of the exception type handled by this handler. Specify 0 if not applicable (this is finally handler).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Some of the instruction offset is negative,
/// the end offset of specified range is less than its start offset,
/// or <paramref name="kind"/> has an invalid value.
/// </exception>
public ExceptionHandler(int tryOffset, int tryLength, int filterOffset, int handlerOffset, int handlerLength,
ExceptionHandlingClauseOptions kind, int exceptionTypeToken)
{
if (tryOffset < 0)
{
throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (tryLength < 0)
{
throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (filterOffset < 0)
{
throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerOffset < 0)
{
throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (handlerLength < 0)
{
throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if ((long)tryOffset + tryLength > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset));
}
if ((long)handlerOffset + handlerLength > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset));
}
// Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it,
// and we can't check for valid tokens until the module is baked.
if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken");
}
Contract.EndContractBlock();
if (!IsValidKind(kind))
{
throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
m_tryStartOffset = tryOffset;
m_tryEndOffset = tryOffset + tryLength;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerOffset;
m_handlerEndOffset = handlerOffset + handlerLength;
m_kind = kind;
m_exceptionClass = exceptionTypeToken;
}
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
Contract.Assert(tryStartOffset >= 0);
Contract.Assert(tryEndOffset >= 0);
Contract.Assert(filterOffset >= 0);
Contract.Assert(handlerStartOffset >= 0);
Contract.Assert(handlerEndOffset >= 0);
Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerStartOffset;
m_handlerEndOffset = handlerEndOffset;
m_kind = (ExceptionHandlingClauseOptions)kind;
m_exceptionClass = exceptionTypeToken;
}
private static bool IsValidKind(ExceptionHandlingClauseOptions kind)
{
switch (kind)
{
case ExceptionHandlingClauseOptions.Clause:
case ExceptionHandlingClauseOptions.Filter:
case ExceptionHandlingClauseOptions.Finally:
case ExceptionHandlingClauseOptions.Fault:
return true;
default:
return false;
}
}
#endregion
#region Equality
public override int GetHashCode()
{
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
public override bool Equals(Object obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
public bool Equals(ExceptionHandler other)
{
return
other.m_exceptionClass == m_exceptionClass &&
other.m_tryStartOffset == m_tryStartOffset &&
other.m_tryEndOffset == m_tryEndOffset &&
other.m_filterOffset == m_filterOffset &&
other.m_handlerStartOffset == m_handlerStartOffset &&
other.m_handlerEndOffset == m_handlerEndOffset &&
other.m_kind == m_kind;
}
public static bool operator ==(ExceptionHandler left, ExceptionHandler right)
{
return left.Equals(right);
}
public static bool operator !=(ExceptionHandler left, ExceptionHandler right)
{
return !left.Equals(right);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteTablesOperations operations.
/// </summary>
internal partial class RouteTablesOperations : IServiceOperations<NetworkManagementClient>, IRouteTablesOperations
{
/// <summary>
/// Initializes a new instance of the RouteTablesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteTablesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteTable>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_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>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteTable> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteTable>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_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;
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer
{
public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture>
{
public TypeInferrerTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition)
{
var root = await document.GetSyntaxRootAsync();
var node = FindExpressionSyntaxFromSpan(root, textSpan);
var typeInference = document.GetLanguageService<ITypeInferenceService>();
var inferredType = useNodeStartPosition
? typeInference.InferType(await document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None), node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None)
: typeInference.InferType(await document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None);
var typeSyntax = inferredType.GenerateTypeSyntax();
Assert.Equal(expectedType, typeSyntax.ToString());
}
private async Task TestInClassAsync(string text, string expectedType)
{
text = @"class C
{
$
}".Replace("$", text);
await TestAsync(text, expectedType);
}
private async Task TestInMethodAsync(string text, string expectedType, bool testNode = true, bool testPosition = true)
{
text = @"class C
{
void M()
{
$
}
}".Replace("$", text);
await TestAsync(text, expectedType, testNode: testNode, testPosition: testPosition);
}
private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan)
{
var token = root.FindToken(textSpan.Start);
var currentNode = token.Parent;
while (currentNode != null)
{
ExpressionSyntax result = currentNode as ExpressionSyntax;
if (result != null && result.Span == textSpan)
{
return result;
}
currentNode = currentNode.Parent;
}
return null;
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional1()
{
// We do not support position inference here as we're before the ? and we only look
// backwards to infer a type here.
await TestInMethodAsync("var q = [|Foo()|] ? 1 : 2;", "System.Boolean",
testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional2()
{
await TestInMethodAsync("var q = a ? [|Foo()|] : 2;", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional3()
{
await TestInMethodAsync(@"var q = a ? """" : [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestVariableDeclarator1()
{
await TestInMethodAsync("int q = [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestVariableDeclarator2()
{
await TestInMethodAsync("var q = [|Foo()|];", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce1()
{
await TestInMethodAsync("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce2()
{
await TestInMethodAsync(@"bool? b;
var q = b ?? [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce3()
{
await TestInMethodAsync(@"string s;
var q = s ?? [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce4()
{
await TestInMethodAsync("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryExpression1()
{
await TestInMethodAsync(@"string s;
var q = s + [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryExpression2()
{
await TestInMethodAsync(@"var s;
var q = s || [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryOperator1()
{
await TestInMethodAsync(@"var q = x << [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryOperator2()
{
await TestInMethodAsync(@"var q = x >> [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestAssignmentOperator3()
{
await TestInMethodAsync(@"var q <<= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestAssignmentOperator4()
{
await TestInMethodAsync(@"var q >>= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestOverloadedConditionalLogicalOperatorsInferBool()
{
await TestAsync(@"using System;
class C
{
public static C operator &(C c, C d) { return null; }
public static bool operator true(C c) { return true; }
public static bool operator false(C c) { return false; }
static void Main(string[] args)
{
var c = new C() && [|Foo()|];
}
}", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a || [|7|];
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a && [|7|];
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | b | c || d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a | b | [|c|] || d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] | y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] | y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & b & c && d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a & b & [|c|] && d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] & y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] & y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ b ^ c && d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a ^ b ^ [|c|] && d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] ^ y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^ y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] |= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] |= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] &= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] &= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] ^= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn1()
{
await TestInClassAsync(@"int M() { return [|Foo()|]; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn2()
{
await TestInMethodAsync("return [|Foo()|];", "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn3()
{
await TestInClassAsync(@"int Property { get { return [|Foo()|]; } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
public async Task TestYieldReturn()
{
var markup =
@"using System.Collections.Generic;
class Program
{
IEnumerable<int> M()
{
yield return [|abc|]
}
}";
await TestAsync(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturnInLambda()
{
await TestInMethodAsync("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestLambda()
{
await TestInMethodAsync("System.Func<string, int> f = s => [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThrow()
{
await TestInMethodAsync("throw [|Foo()|];", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCatch()
{
await TestInMethodAsync("try { } catch ([|Foo|] ex) { }", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIf()
{
await TestInMethodAsync(@"if ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestWhile()
{
await TestInMethodAsync(@"while ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestDo()
{
await TestInMethodAsync(@"do { } while ([|Foo()|])", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor1()
{
await TestInMethodAsync(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor2()
{
await TestInMethodAsync(@"for (string i = [|Foo()|]; ; ) { }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor3()
{
await TestInMethodAsync(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing1()
{
await TestInMethodAsync(@"using ([|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing2()
{
await TestInMethodAsync(@"using (int i = [|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing3()
{
await TestInMethodAsync(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestForEach()
{
await TestInMethodAsync(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression1()
{
await TestInMethodAsync(@"var q = +[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression2()
{
await TestInMethodAsync(@"var q = -[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression3()
{
await TestInMethodAsync(@"var q = ~[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression4()
{
await TestInMethodAsync(@"var q = ![|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression5()
{
await TestInMethodAsync(@"var q = System.DayOfWeek.Monday & ~[|Foo()|];", "global::System.DayOfWeek");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayRankSpecifier()
{
await TestInMethodAsync(@"var q = new string[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch1()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch2()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { default: }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch3()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { case ""a"": }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall1()
{
await TestInMethodAsync(@"Bar([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall2()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall3()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall4()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall5()
{
await TestInClassAsync(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall1()
{
await TestInMethodAsync(@"new C([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall2()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall3()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C() { }", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall4()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall5()
{
await TestInClassAsync(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThisConstructorInitializer1()
{
await TestAsync(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThisConstructorInitializer2()
{
await TestAsync(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBaseConstructorInitializer()
{
await TestAsync(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexAccess1()
{
await TestInMethodAsync(@"string[] i; i[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall1()
{
await TestInMethodAsync(@"this[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall2()
{
// Update this when binding of indexers is working.
await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall3()
{
// Update this when binding of indexers is working.
await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall5()
{
await TestInClassAsync(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreationSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { 1, [|2|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
int Foo() { return 2; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation2()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation3()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
}";
await TestAsync(text, "System.Object");
}
[Fact]
public async Task TestArrayInitializerInEqualsValueClauseSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { 1, [|2|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInEqualsValueClause()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
new List<int>() { [|Foo()|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer2()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { [|Foo()|], """" } };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer3()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { 0, [|Foo()|] } };
}
}";
await TestAsync(text, "System.String");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod1()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { [|a|] };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod2()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { ""test"", [|b|] } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod3()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { [|s|], true } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference1()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference1_Position()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference2()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
await TestAsync(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference2_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
await TestAsync(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference3()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[]", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference3_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference4()
{
var text =
@"
using System;
class A
{
void Foo()
{
Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] };
}
}";
await TestAsync(text, "global::System.Func<System.Int32,System.Int32>");
}
[WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestInsideLambda2()
{
var text =
@"using System;
class C
{
void M()
{
Func<int,int> f = i => [|here|]
}
}";
await TestAsync(text, "System.Int32");
}
[WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPointer1()
{
var text =
@"class C
{
void M(int* i)
{
var q = i[[|Foo()|]];
}
}";
await TestAsync(text, "System.Int32");
}
[WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestDynamic1()
{
var text =
@"class C
{
void M(dynamic i)
{
var q = i[[|Foo()|]];
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestChecked1()
{
var text =
@"class C
{
void M()
{
string q = checked([|Foo()|]);
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
int x = await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTaskOfTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
Task<int> x = await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTask()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")]
public async Task TestLockStatement()
{
var text =
@"class C
{
void M()
{
lock([|Foo()|])
{
}
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")]
public async Task TestAwaitExpressionInLockStatement()
{
var text =
@"class C
{
async void M()
{
lock(await [|Foo()|])
{
}
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Object>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
public async Task TestReturnFromAsyncTaskOfT()
{
var markup =
@"using System.Threading.Tasks;
class Program
{
async Task<int> M()
{
await Task.Delay(1);
return [|ab|]
}
}";
await TestAsync(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments1()
{
var markup =
@"[A([|dd|], ee, Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "global::System.DayOfWeek");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments2()
{
var markup =
@"[A(dd, [|ee|], Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "System.Double");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments3()
{
var markup =
@"[A(dd, ee, Y = [|ff|])]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")]
public async Task TestReturnStatementWithinDelegateWithinAMethodCall()
{
var text =
@"using System;
class Program
{
delegate string A(int i);
static void Main(string[] args)
{
B(delegate(int i) { return [|M()|]; });
}
private static void B(A a)
{
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause()
{
var text =
@"
try
{ }
catch (Exception) if ([|M()|])
}";
await TestInMethodAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause1()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|])
}";
await TestInMethodAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause2()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|].N)
}";
await TestInMethodAsync(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public async Task TestAwaitExpressionWithChainingMethod()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M()|].ConfigureAwait(false);
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public async Task TestAwaitExpressionWithChainingMethod2()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; });
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public async Task TestAwaitExpressionWithGenericMethod1()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await X([|Test()|]);
}
private async Task<T> X<T>(T t) { return t; }
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public async Task TestAwaitExpressionWithGenericMethod2()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await Task.Run(() => [|Test()|]);;
}
private async Task<T> X<T>(T t) { return t; }
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator1()
{
var text =
@"class C
{
void M()
{
object z = [|a|]?? null;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator2()
{
var text =
@"class C
{
void M()
{
object z = [|a|] ?? b ?? c;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator3()
{
var text =
@"class C
{
void M()
{
object z = a ?? [|b|] ?? c;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public async Task TestSelectLambda()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[||])
}
}";
await TestAsync(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public async Task TestSelectLambda2()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[|b|])
}
}";
await TestAsync(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")]
public async Task TestReturnInAsyncLambda1()
{
var text =
@"using System;
using System.IO;
using System.Threading.Tasks;
public class C
{
public async void M()
{
Func<Task<int>> t2 = async () => { return [|a|]; };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")]
public async Task TestReturnInAsyncLambda2()
{
var text =
@"using System;
using System.IO;
using System.Threading.Tasks;
public class C
{
public async void M()
{
Func<Task<int>> t2 = async delegate () { return [|a|]; };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")]
public async Task TestDefaultStatement1()
{
var text =
@"class C
{
static void Main(string[] args)
{
System.ConsoleModifiers c = default([||])
}
}";
await TestAsync(text, "global::System.ConsoleModifiers", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")]
public async Task TestDefaultStatement2()
{
var text =
@"class C
{
static void Foo(System.ConsoleModifiers arg)
{
Foo(default([||])
}
}";
await TestAsync(text, "global::System.ConsoleModifiers", testNode: false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
** Private version of List<T> for internal System.Private.CoreLib use. This
** permits sharing more source between BCL and System.Private.CoreLib (as well as the
** fact that List<T> is just a useful class in general.)
**
** This does not strive to implement the full api surface area
** (but any portion it does implement should match the real List<T>'s
** behavior.)
**
** This file is a subset of System.Collections\System\Collections\Generics\List.cs
** and should be kept in sync with that file.
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
/// <summary>
/// LowLevelList with no interface implementation to minimize both code and data size
/// Data size is smaller because there will be minimal virtual function table.
/// Code size is smaller because only functions called will be in the binary.
/// Use LowLevelListWithIList<T> for IList support
/// </summary>
[DebuggerDisplay("Count = {Count}")]
#if TYPE_LOADER_IMPLEMENTATION
[System.Runtime.CompilerServices.ForceDictionaryLookups]
#endif
internal class LowLevelList<T>
{
private const int _defaultCapacity = 4;
protected T[] _items;
[ContractPublicPropertyName("Count")]
protected int _size;
protected int _version;
private static readonly T[] s_emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to 16, and then increased in multiples of two as required.
public LowLevelList()
{
_items = s_emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public LowLevelList(int capacity)
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
Contract.EndContractBlock();
if (capacity == 0)
_items = s_emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public LowLevelList(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
if (count == 0)
{
_items = s_emptyArray;
}
else
{
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else
{
_size = 0;
_items = s_emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
Contract.EndContractBlock();
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
Array.Copy(_items, 0, newItems, 0, _size);
_items = newItems;
}
else
{
_items = s_emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
// Sets or Gets the element at the given index.
//
public T this[int index]
{
get
{
// Following trick can reduce the range check by one
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item)
{
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
//if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
#if !TYPE_LOADER_IMPLEMENTATION
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
public void AddRange(IEnumerable<T> collection)
{
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
// Clears the contents of List.
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item)
{
if ((object)item == null)
{
for (int i = 0; i < _size; i++)
if ((object)_items[i] == null)
return true;
return false;
}
else
{
int index = IndexOf(item);
if (index >= 0)
return true;
return false;
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (_size - index < count)
{
throw new ArgumentException();
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item)
{
// Note that insertions at the end are legal.
if ((uint)index > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
public void InsertRange(int index, IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if ((uint)index > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{ // if collection is ICollection<T>
int count = c.Count;
if (count > 0)
{
EnsureCapacity(_size + count);
if (index < _size)
{
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c)
{
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index + count, _items, index * 2, _size - index);
}
else
{
T[] itemsToInsert = new T[count];
c.CopyTo(itemsToInsert, 0);
Array.Copy(itemsToInsert, 0, _items, index, count);
}
_size += count;
}
}
else
{
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Insert(index++, en.Current);
}
}
}
_version++;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if (freeIndex >= _size) return 0;
int current = freeIndex + 1;
while (current < _size)
{
// Find the first item which needs to be kept.
while (current < _size && match(_items[current])) current++;
if (current < _size)
{
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
Array.Clear(_items, freeIndex, _size - freeIndex);
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index)
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
// ToArray returns a new Object array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray()
{
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
#endif
}
#if !TYPE_LOADER_IMPLEMENTATION
/// <summary>
/// LowLevelList<T> with full IList<T> implementation
/// </summary>
internal sealed class LowLevelListWithIList<T> : LowLevelList<T>, IList<T>
{
public LowLevelListWithIList()
{
}
public LowLevelListWithIList(int capacity)
: base(capacity)
{
}
public LowLevelListWithIList(IEnumerable<T> collection)
: base(collection)
{
}
// Is this List read-only?
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
private struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private LowLevelListWithIList<T> _list;
private int _index;
private int _version;
private T _current;
internal Enumerator(LowLevelListWithIList<T> list)
{
_list = list;
_index = 0;
_version = list._version;
_current = default(T);
}
public void Dispose()
{
}
public bool MoveNext()
{
LowLevelListWithIList<T> localList = _list;
if (_version == localList._version && ((uint)_index < (uint)localList._size))
{
_current = localList._items[_index];
_index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (_version != _list._version)
{
throw new InvalidOperationException();
}
_index = _list._size + 1;
_current = default(T);
return false;
}
public T Current
{
get
{
return _current;
}
}
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || _index == _list._size + 1)
{
throw new InvalidOperationException();
}
return Current;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _list._version)
{
throw new InvalidOperationException();
}
_index = 0;
_current = default(T);
}
}
}
#endif // !TYPE_LOADER_IMPLEMENTATION
}
| |
#define ibox
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class PlayerUnits{
[HideInInspector] public int factionID=-1;
//[HideInInspector]
public List<UnitTB> starting=new List<UnitTB>();
//[HideInInspector] public List<UnitTB> undeployed=new List<UnitTB>();
[HideInInspector] public bool showInInspector=false;
public PlayerUnits(int ID){
factionID=ID;
}
}
public class UnitControl : MonoBehaviour {
public delegate void NewFactionPlacementHandler(PlayerUnits pUnits);
public static event NewFactionPlacementHandler onNewPlacementE;
public delegate void PlacementUpdateHandler();
public static event PlacementUpdateHandler onPlacementUpdateE;
public delegate void NewUnitInRuntimeHandler(UnitTB unit);
public static event NewUnitInRuntimeHandler onNewUnitInRuntimeE;
public delegate void FactionDefeatedHandler(int ID);
public static event FactionDefeatedHandler onFactionDefeatedE;
[HideInInspector]
public List<PlayerUnits> playerUnits=new List<PlayerUnits>();
[HideInInspector]
public List<UnitTB> startingUnit=new List<UnitTB>();
[HideInInspector] public List<UnitTB> undeployedUnit=new List<UnitTB>();
[HideInInspector]
public List<Color> factionColors=new List<Color>();
[HideInInspector]
public List<UnitTB> allUnits=new List<UnitTB>();
private List<UnitTB> allUnitsMoved=new List<UnitTB>();
[HideInInspector]
public List<Faction> allFactionList=new List<Faction>();
public static int activeFactionCount=0; //indicate how many faction are still in the game, defeated faction excluded
public static UnitTB selectedUnit; //player selected unit
public static UnitTB hoveredUnit;
public static UnitControl instance;
//for unity-based turn mode, indicatring which unit turn it's current
public static int currentUnitTurnID=-1;
//for singleUnitRealtime, the highest speed among all the unit
private int highestUnitPriority=0;
//flag to indicate if waitingTime of the units should be reduced
//used in singleUnitRealtime only
//set to true if there are unit with the same moveOrder in the turn
private bool holdWaitedTime=false;
//public float unitMoveSpeed;
//public static float GetUnitMoveSpeed(){
// return instance.unitMoveSpeed;
//}
//flag to indicate if the unit gameObject should be destroy when the unit is killed
public bool hideUnitWhenKilled=true;
public bool destroyUnitObject=true;
public static bool HideUnitWhenKilled(){
return instance.hideUnitWhenKilled;
}
public static bool DestroyUnitObject(){
return instance.destroyUnitObject;
}
void Awake(){
instance=this;
List<Tile> allTiles=GridManager.GetAllTiles();
foreach(Tile tile in allTiles){
if(tile.unit!=null){
UnitTB unit=tile.unit;
allUnits.Add(unit);
}
}
currentUnitTurnID=-1;
#if ibox
if(playerUnits==null || playerUnits.Count==0){
playerUnits=new List<PlayerUnits>();
playerUnits.Add(new PlayerUnits(GameControlTB.instance.playerFactionID[0]));
}
#endif
}
// Use this for initialization
void Start () {
#if ibox
#else
if(playerUnits==null || playerUnits.Count==0){
playerUnits=new List<PlayerUnits>();
playerUnits.Add(new PlayerUnits(GameControlTB.instance.playerFactionID[0]));
}
#endif
if(GameControlTB.LoadMode()==_LoadMode.UsePersistantData){
if(!GlobalStatsTB.loaded){ GlobalStatsTB.Init(); }
//int playerFactionCount=GlobalStatsTB.GetPlayerFactionCount();
//for(int i=0; i<playerFactionCount; i++){
// playerUnits[i].starting=GlobalStatsTB.GetPlayerUnitList(i);
//}
playerUnits[0].starting=GlobalStatsTB.GetPlayerUnitList();
}
else if(GameControlTB.LoadMode()==_LoadMode.UseTemporaryData){
int playerFactionCount=GlobalStatsTB.GetPlayerFactionCount();
for(int i=0; i<playerFactionCount; i++){
playerUnits[i].starting=GlobalStatsTB.GetTempPlayerUnitList();
}
//playerUnits[0].starting=GlobalStatsTB.GetTempPlayerUnitList();
}
#if UnityEditor
Transform unitParent=transform.root;
foreach(Transform child in transform.root){
if(child.gameObject.name=="Units") unitParent=child;
}
#endif
//instantiate the starting unit in playerUnits, for hotseat mode, not in use
for(int j=0; j<playerUnits.Count; j++){
PlayerUnits pUnits=playerUnits[j];
for(int i=0; i<pUnits.starting.Count; i++){
if(pUnits.starting[i]!=null){
GameObject obj=(GameObject)Instantiate(pUnits.starting[i].gameObject, new Vector3(0, 9999, 0), Quaternion.identity);
pUnits.starting[i]=obj.GetComponent<UnitTB>();
pUnits.starting[i].factionID=pUnits.factionID;
#if UnityEditor
obj.transform.parent=unitParent;
#endif
}
}
}
//make sure none of the element is empty, shrink the list
for(int j=0; j<playerUnits.Count; j++){
PlayerUnits pUnits=playerUnits[j];
for(int i=0; i<pUnits.starting.Count; i++){
if(pUnits.starting[i]==null){
pUnits.starting.RemoveAt(i); i-=1;
}
}
}
//instantiate the starting unit
/*
for(int i=0; i<startingUnit.Count; i++){
if(startingUnit[i]!=null){
GameObject obj=(GameObject)Instantiate(startingUnit[i].gameObject, new Vector3(0, 9999, 0), Quaternion.identity);
startingUnit[i]=obj.GetComponent<UnitTB>();
#if UnityEditor
obj.transform.parent=unitParent;
#endif
}
//make sure none of the element is empty, shrink the list
}
for(int i=0; i<startingUnit.Count; i++){
if(startingUnit[i]==null){
startingUnit.RemoveAt(i); i-=1;
}
}
*/
//external code, not TBTK related
//if(isWarCorpAlpha) WarCorpInitRoutine();
//if(startingUnit.Count>0){
if(playerUnits!=null && playerUnits.Count>0 && playerUnits[0].starting.Count>0){
if(GameControlTB.EnableUnitPlacement()){
//to inform GridManager to show the correct placeale tile
if(onNewPlacementE!=null) onNewPlacementE(playerUnits[facPlacementID]);
//to update UI and other stuff
if(onPlacementUpdateE!=null) onPlacementUpdateE();
}
else{
_AutoPlaceUnit();
StartCoroutine(UnitPlacementCompleted());
}
}
else{
StartCoroutine(UnitPlacementCompleted());
}
}
IEnumerator UnitPlacementCompleted(){
yield return null;
GameControlTB.UnitPlacementCompleted();
}
void OnEnable(){
GameControlTB.onBattleStartE += OnBattleStart;
GameControlTB.onNewRoundE += OnNewRound;
GameControlTB.onNextTurnE += OnNextTurn;
GameControlTB.onBattleEndE += OnBattleEnd;
UnitTB.onUnitSelectedE += OnUnitSelected;
UnitTB.onUnitDeselectedE += OnUnitDeselected;
UnitTB.onUnitDestroyedE += OnUnitDestroyed;
}
void OnDisable(){
GameControlTB.onBattleStartE -= OnBattleStart;
GameControlTB.onNewRoundE -= OnNewRound;
GameControlTB.onNextTurnE -= OnNextTurn;
GameControlTB.onBattleEndE -= OnBattleEnd;
UnitTB.onUnitSelectedE -= OnUnitSelected;
UnitTB.onUnitDeselectedE -= OnUnitDeselected;
UnitTB.onUnitDestroyedE -= OnUnitDestroyed;
}
void OnUnitSelected(UnitTB sUnit){
selectedUnit=sUnit;
}
void OnUnitDeselected(){
selectedUnit=null;
}
// Update is called once per frame
void Update () {
/*
if(Input.GetKeyDown(KeyCode.L)){
foreach(UnitTB unit in allUnits){
unit.GainAP(100);
}
}
*/
if(Input.GetKeyDown(KeyCode.F)){
_AutoPlaceUnit();
}
}
//battle start, initiated the faction info
void OnBattleStart(){
//store away all the unused unit
undeployedUnit=startingUnit;
foreach(UnitTB unit in undeployedUnit){
if(unit!=null){
//Utility.SetActive(unit.thisObj, false);
Utility.SetActive(unit.gameObject, false);
}
}
startingUnit=null;
InitFaction();
_TurnMode turnMode=GameControlTB.GetTurnMode();
if(turnMode==_TurnMode.SingleUnitRealTime || turnMode==_TurnMode.SingleUnitRealTimeNoRound){
highestUnitPriority=0;
for(int i=0; i<allUnits.Count; i++){
if(allUnits[i].GetTurnPriority()>highestUnitPriority) highestUnitPriority=allUnits[i].GetTurnPriority();
}
float highest=-1;
for(int i=0; i<allUnits.Count; i++){
if(allUnits[i].GetTurnPriority()>highest){
highest=allUnits[i].GetTurnPriority();
}
}
for(int i=0; i<allUnits.Count; i++){
//allUnits[i].waitingTime=Mathf.Floor(highest/allUnits[i].speed);
allUnits[i].waitingTime=(highest/allUnits[i].GetTurnPriority());
}
}
GameControlTB.OnNewRound();
}
//function called for a new round event
void OnNewRound(int roundCounter){
//clear all the moved flag for all faction
for(int i=0; i<allFactionList.Count; i++){
if(allFactionList[i].allUnitList.Count>0) allFactionList[i].allUnitMoved=false;
//allFactionList[i].numOfUnitMoved=0;
}
_TurnMode turnMode=GameControlTB.GetTurnMode();
if(turnMode==_TurnMode.SingleUnitPerTurn){
currentUnitTurnID=-1;
ArrangeAllUnitOnTurnPriority();
}
else if(turnMode==_TurnMode.SingleUnitRealTime || turnMode==_TurnMode.SingleUnitRealTimeNoRound){
//ArrangeAllUnitOnTurnPriority();
for(int i=0; i<allUnits.Count; i++) allUnits[i].waitedTime=allUnits[i].waitingTime;
}
else{
if(GameControlTB.GetMoveOrder()==_MoveOrder.Free){
ResetFactionUnitMoveList(); //reset the yetToMove list
}
else if(GameControlTB.GetMoveOrder()==_MoveOrder.FixedRandom){
if(roundCounter==1) ShuffleAllUnit(); //randomly rearrange all unit
}
else if(GameControlTB.GetMoveOrder()==_MoveOrder.FixedStatsBased){
ArrangeFactionUnitOnTurnPriority(); //arrange all unit within faction based on stats
}
}
}
//****************************************************************************************************************************
//switch to next unit
//switch to next unit via event
public static void OnNextUnit(){
instance.OnNextTurn();
}
void OnNextTurn(){
if(GameControlTB.battleEnded) return;
_TurnMode turnMode=GameControlTB.GetTurnMode();
if(turnMode==_TurnMode.FactionAllUnitPerTurn){
if(GameControlTB.IsPlayerTurn()) SwitchToNextUnitInTurn();
else AIManager.AIRoutine(GameControlTB.turnID);
}
else if(turnMode==_TurnMode.FactionSingleUnitPerTurnAll){
SwitchToNextUnitInTurn();
}
else if(turnMode==_TurnMode.FactionSingleUnitPerTurnSingle){
SwitchToNextUnitInTurn();
}
else if(turnMode==_TurnMode.SingleUnitPerTurn){
SwitchToNextUnitInTurn();
}
else if(turnMode==_TurnMode.SingleUnitRealTime || turnMode==_TurnMode.SingleUnitRealTimeNoRound){
for(int i=0; i<allUnits.Count; i++){
if(!holdWaitedTime) allUnits[i].waitedTime-=1;
}
SwitchToNextUnitInTurn();
}
}
//switch to next unit via direct function call, called by GameControl in UnitActionDepleted()
public static void SwitchToNextUnit(){
instance.StartCoroutine(instance.DelaySwitchUnit());
}
IEnumerator DelaySwitchUnit(){
//make sure current action sequence is finished
while(GameControlTB.IsActionInProgress()) yield return null;
SwitchToNextUnitInTurn();
}
//called when the current selected player unit has used up all available move
public static void SwitchToNextUnitInTurn(){
GridManager.Deselect();
_TurnMode turnMode=GameControlTB.GetTurnMode();
//select next unit for this round, if all unit has been moved, start new round
if(turnMode==_TurnMode.SingleUnitPerTurn){
currentUnitTurnID+=1;
if(currentUnitTurnID>=instance.allUnits.Count){
currentUnitTurnID=-1;
//if all unit has been moved, issue a new round,
GameControlTB.OnNewRound();
}
else{
//Unit with the highest turnPriority move first
//all unit has been arrange in order using function ArrangeAllUnitToTurnPriority() at every new round, check OnNewRound
//so we simply select next unit based on currentUnitTurnID
selectedUnit=instance.allUnits[currentUnitTurnID];
selectedUnit.occupiedTile.Select();
GameControlTB.turnID=selectedUnit.factionID;
if(!GameControlTB.IsPlayerFaction(selectedUnit.factionID)) AIManager.MoveUnit(selectedUnit);
//if(selectedUnit.factionID!=GameControlTB.GetPlayerFactionID()) AIManager.MoveUnit(selectedUnit);
}
}
else if(turnMode==_TurnMode.SingleUnitRealTime || turnMode==_TurnMode.SingleUnitRealTimeNoRound){
if(turnMode==_TurnMode.SingleUnitRealTime){
if(instance.allUnitsMoved.Count==instance.allUnits.Count){
GameControlTB.OnNewRound();
instance.allUnitsMoved=new List<UnitTB>();
return;
}
}
float lowest=100000;
instance.holdWaitedTime=false;
UnitTB currentSelected=null;
for(int i=0; i<instance.allUnits.Count; i++){
UnitTB unit=instance.allUnits[i];
if(unit.waitedTime<=0){
if(unit.waitedTime==lowest) {
instance.holdWaitedTime=true;
}
if(unit.waitedTime<lowest){
lowest=unit.waitedTime;
currentSelected=unit;
}
}
}
if(currentSelected==null){
instance.OnNextTurn();
return;
}
selectedUnit=currentSelected;
selectedUnit.waitedTime=selectedUnit.waitingTime;
selectedUnit.OnNewRound(0);
selectedUnit.occupiedTile.Select();
if(!instance.allUnitsMoved.Contains(selectedUnit)) instance.allUnitsMoved.Add(selectedUnit);
GameControlTB.turnID=selectedUnit.factionID;
if(!GameControlTB.IsPlayerFaction(selectedUnit.factionID)) AIManager.MoveUnit(selectedUnit);
//if(selectedUnit.factionID!=GameControlTB.GetPlayerFactionID()) AIManager.MoveUnit(selectedUnit);
}
else{
if(turnMode==_TurnMode.FactionAllUnitPerTurn){
//when in FactionAllUnitPerTurn
//this section is only called when the faction in turn belongs to player
//otherwise AIROutine is called to move all AI's units
if(!GameControlTB.IsPlayerTurn()) return;
}
//get the faction in turn and make sure a unit has been selected successfully
Faction faction=instance.allFactionList[GameControlTB.turnID];
if(!instance.SelectNexUnit(faction)) return;
if(turnMode!=_TurnMode.FactionAllUnitPerTurn){
//if the selecte unit doesnt belong to player, call AI to move the unit
if(!GameControlTB.IsPlayerFaction(selectedUnit.factionID)){
AIManager.MoveUnit(selectedUnit);
}
else{
//Debug.Log("UC unit switched, player's turn");
}
//if(selectedUnit.factionID!=GameControlTB.GetPlayerFactionID()) AIManager.MoveUnit(selectedUnit);
}
}
}
//switch to next unit in turn, return true if there's a next unit exist for the faction, false if otherwise
bool SelectNexUnit(Faction faction){
//make sure there is unit to be selected
if(faction.allUnitList.Count==0){
Debug.Log("Error, UnitControl tried to select unit from empty faction");
faction.allUnitMoved=true;
GameControlTB.OnEndTurn();
return false;
}
//make sure there is unit to be selected
if(faction.allUnitMoved){
Debug.Log("Error, UnitControl tried to select unit from faction with all unit moved");
GameControlTB.OnEndTurn();
return false;
}
//if move order is free, randomly select a unit
if(GameControlTB.GetMoveOrder()==_MoveOrder.Free){
int rand=UnityEngine.Random.Range(0, faction.unitYetToMove.Count);
faction.currentTurnID=faction.unitYetToMove[rand];
}
//select the unit
selectedUnit=faction.allUnitList[faction.currentTurnID];
selectedUnit.occupiedTile.Select();
if(GameControlTB.GetMoveOrder()!=_MoveOrder.Free){
//move the currentTurnID so in the next turn, the next unit in line will be selected
faction.currentTurnID+=1;
if(faction.currentTurnID>=faction.allUnitList.Count){
faction.currentTurnID=0;
//faction.numOfUnitMoved+=1;
faction.allUnitMoved=true;
}
}
return true;
}
//end switch to next unit
//****************************************************************************************************************************
//***********************************************************************************************************************
//create faction, add unit to faction, etc...
//called when battle started (after unit placement is done)
void InitFaction(){
List<int> factionIDExisted=new List<int>();
activeFactionCount=0;
//get all the factionID so it can be reformat to the lowest numerical figure
foreach(UnitTB unit in allUnits){
if(!factionIDExisted.Contains(unit.factionID)){
activeFactionCount+=1;
factionIDExisted.Add(unit.factionID);
}
}
/*
//make sure all faction ID and are formated to lowest numerical figure (1, 2, 3....) so it sync with turnID in gameControl
foreach(UnitTB unit in allUnits){
for(int i=0; i<factionIDExisted.Count; i++){
if(unit.factionID==factionIDExisted[i]){
unit.factionID=i;
break;
}
}
}
*/
bool match=false;
List<int> IDList=GameControlTB.GetPlayerFactionIDS();
for(int i=0; i<IDList.Count; i++){
if(factionIDExisted.Contains(IDList[i])) match=true;
}
if(!match) Debug.Log("Warning: there's no player faction");
GameControlTB.totalFactionInGame=factionIDExisted.Count;
if(GameControlTB.totalFactionInGame==1){
Debug.Log("Warning: only 1 faction exist in this battle");
return;
}
List<int> playerFacIDList=GameControlTB.GetPlayerFactionIDS();
GameControlTB.playerFactionTurnID=new List<int>();
for(int i=0; i<playerFacIDList.Count; i++){
GameControlTB.playerFactionTurnID.Add(-1);
}
_TurnMode turnMode=GameControlTB.GetTurnMode();
for(int i=0; i<GameControlTB.totalFactionInGame; i++){
Faction faction=new Faction();
faction.factionID=factionIDExisted[i];
if(i<factionColors.Count){
faction.color=factionColors[i];
}
else{
faction.color=new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
}
foreach(UnitTB unit in allUnits){
if(unit.factionID==factionIDExisted[i]){
faction.allUnitList.Add(unit);
}
}
for(int n=0; n<playerFacIDList.Count; n++){
if(playerFacIDList[n]==faction.factionID){
faction.isPlayerControl=true;
//for singleUnit turnMode, turnID in gameControl is assigned based on factionID of each unit
if((int)turnMode>2) GameControlTB.playerFactionTurnID[n]=faction.factionID;
//for faction turnMode, turnID in gameControl uses a chronological numeric counter
else GameControlTB.playerFactionTurnID[n]=i;
GameControlTB.playerFactionExisted=true;
}
}
//obsoleted code
//~ if(faction.factionID==GameControlTB.GetPlayerFactionID()){
//~ faction.isPlayerControl=true;
//~ GameControlTB.playerFactionTurnID=i;
//~ GameControlTB.playerFactionExisted=true;
//~ }
allFactionList.Add(faction);
}
GameControlTB.instance._playerFactionTurnID=GameControlTB.playerFactionTurnID;
}
public static Texture GetFactionIcon(int ID){
if(instance!=null){
foreach(Faction faction in instance.allFactionList){
if(faction.factionID==ID) return faction.icon;
}
}
return null;
}
public static Color GetFactionColor(int ID){
if(instance!=null){
foreach(Faction faction in instance.allFactionList){
if(faction.factionID==ID) return faction.color;
}
}
return Color.white;
}
//end faction related code
//***********************************************************************************************************************
//*****************************************************************************************************************************
//code related for unit placement in unit placement phase
private int facPlacementID=0;
public static int GetFactionPlacementID(){
return instance.unitPlacementID;
}
public static PlayerUnits GetPlayerUnitsBeingPlaced(){
return instance.playerUnits[instance.facPlacementID];
}
public static void NextFactionPlacementID(){
ResetUnitPlacementID();
if(instance.playerUnits[instance.facPlacementID].starting.Count==0){
instance.playerUnits.RemoveAt(0);
}
if(onNewPlacementE!=null) onNewPlacementE(instance.playerUnits[0]);
if(onPlacementUpdateE!=null) onPlacementUpdateE();
//instance.facPlacementID+=1;
}
public static int GetPlayerUnitsRemainng(){
return instance.playerUnits.Count;
}
private int unitPlacementID=0;
public static int GetUnitPlacementID(){
return instance.unitPlacementID;
}
public static void NextUnitPlacementID(){
instance.unitPlacementID+=1;
if(instance.unitPlacementID>=instance.playerUnits[instance.facPlacementID].starting.Count) instance.unitPlacementID=0;
//Debug.Log("next "+instance.unitPlacementID);
}
public static void PrevUnitPlacementID(){
instance.unitPlacementID-=1;
if(instance.unitPlacementID<0) instance.unitPlacementID=instance.playerUnits[instance.facPlacementID].starting.Count-1;
//Debug.Log("prev "+instance.unitPlacementID);
}
public static void ResetUnitPlacementID(){
instance.unitPlacementID=0;
}
//place unit at a tile
public static void PlaceUnitAt(Tile tile){
if(instance.playerUnits.Count==0){
return;
}
if(instance.playerUnits[instance.facPlacementID].starting.Count==0){
return;
}
PlayerUnits pUnits=instance.playerUnits[instance.facPlacementID];
if(pUnits.starting[instance.unitPlacementID]==null){
pUnits.starting.RemoveAt(instance.unitPlacementID);
if(instance.unitPlacementID>=pUnits.starting.Count){
instance.unitPlacementID-=1;
//Debug.Log("next "+instance.unitPlacementID+" "+pUnits.starting.Count);
}
return;
}
UnitTB unit=pUnits.starting[instance.unitPlacementID];
unit.transform.position=tile.thisT.position;
unit.occupiedTile=tile;
tile.unit=unit;
pUnits.starting.RemoveAt(instance.unitPlacementID);
instance.allUnits.Add(unit);
GridManager.PlaceUnitAt(tile);
if(instance.unitPlacementID>=pUnits.starting.Count){
instance.unitPlacementID-=1;
//Debug.Log("next "+instance.unitPlacementID+" "+pUnits.starting.Count);
}
//Debug.Log(instance.unitPlacementID);
if(onPlacementUpdateE!=null) onPlacementUpdateE();
}
//remove a unit from the grid
public static void RemoveUnit(UnitTB unit){
GridManager.RemoveUnitAt(unit.occupiedTile);
instance.playerUnits[instance.facPlacementID].starting.Insert(0, unit);
unit.occupiedTile.unit=null;
unit.occupiedTile=null;
unit.transform.position=new Vector3(0, 9999, 0);
instance.allUnits.Remove(unit);
if(instance.unitPlacementID<0) instance.unitPlacementID=0;
if(onPlacementUpdateE!=null) onPlacementUpdateE();
}
public static void AutoPlaceUnit(){
instance._AutoPlaceUnit();
}
public void _AutoPlaceUnit(){
List<Tile> tileList=GridManager.GetAllPlaceableTiles();
for(int i=0; i<tileList.Count; i++){
if(tileList[i].unit!=null){
tileList.RemoveAt(i); i-=1;
}
}
//for(int i=0; i<playerUnits.Count; i++){
PlayerUnits pUnits=playerUnits[facPlacementID];
while(pUnits.starting.Count>0){
int ID=Random.Range(0, tileList.Count);
PlaceUnitAt(tileList[ID]); //tileList will be remove at GridManager when unit is placed
if(tileList.Count<=0) break;
}
//}
}
public static bool IsAllFactionPlaced(){
if(instance.playerUnits.Count==1 && instance.playerUnits[0].starting.Count==0) return true;
return false;
}
public static bool IsFactionAllUnitPlaced(){
if(instance.playerUnits[instance.facPlacementID].starting.Count==0) return true;
return false;
}
/*
//place unit at a tile
public static void PlaceUnitAt(Tile tile){
if(instance.startingUnit.Count==0) return;
if(instance.startingUnit[instance.unitPlacementID]==null){
instance.startingUnit.RemoveAt(instance.unitPlacementID);
if(instance.unitPlacementID>=instance.startingUnit.Count){
instance.unitPlacementID-=1;
}
return;
}
UnitTB unit=instance.startingUnit[instance.unitPlacementID];
unit.transform.position=tile.thisT.position;
unit.occupiedTile=tile;
tile.unit=unit;
instance.startingUnit.RemoveAt(instance.unitPlacementID);
instance.allUnits.Add(unit);
GridManager.PlaceUnitAt(tile);
if(instance.unitPlacementID>=instance.startingUnit.Count){
instance.unitPlacementID-=1;
}
//Debug.Log(instance.unitPlacementID);
if(onPlacementUpdateE!=null) onPlacementUpdateE();
}
//remove a unit from the grid
public static void RemoveUnit(UnitTB unit){
GridManager.RemoveUnitAt(unit.occupiedTile);
instance.startingUnit.Insert(0, unit);
unit.occupiedTile.unit=null;
unit.occupiedTile=null;
unit.transform.position=new Vector3(0, 9999, 0);
instance.allUnits.Remove(unit);
if(instance.unitPlacementID<0) instance.unitPlacementID=0;
if(onPlacementUpdateE!=null) onPlacementUpdateE();
}
public static void AutoPlaceUnit(){
instance._AutoPlaceUnit();
}
public void _AutoPlaceUnit(){
List<Tile> tileList=GridManager.GetAllPlaceableTiles();
//to make sure there's sufficient tile
//if(tileList.Count<startingUnit.Count){
// Debug.Log("not enough space");
// return;
//}
while(startingUnit.Count>0){
int ID=Random.Range(0, tileList.Count);
PlaceUnitAt(tileList[ID]); //tileList will be remove at GridManager when unit is placed
if(tileList.Count<=0) break;
}
}
private int unitPlacementID=0;
public static int GetUnitPlacementID(){
return instance.unitPlacementID;
}
public static void NextUnitPlacementID(){
instance.unitPlacementID+=1;
if(instance.unitPlacementID>=instance.startingUnit.Count) instance.unitPlacementID=0;
}
//~ public static void ResetUnitPlacementID(){
//~ instance.unitPlacementID=0;
//~ }
public static bool IsAllUnitPlaced(){
if(instance.startingUnit.Count==0) return true;
return false;
}
*/
//to place a unit in runtime, untested, will probably cause issue with certain turnMode
public static void InsertUnit(UnitTB unit, Tile tile, int factionID, int duration){
if(unit==null){
Debug.Log("no unit is specified");
return;
}
if(tile.unit!=null){
Debug.Log("tile is occupied");
return;
}
GameObject unitObj=(GameObject)Instantiate(unit.gameObject);
unit=unitObj.GetComponent<UnitTB>();
unit.SetSpawnInGameFlag(true);
if(duration>0) unit.SetSpawnDuration(duration);
//if(unit.occupiedTile!=null){
// unit.occupiedTile.unit=null;
//}
unit.factionID=factionID;
unit.transform.position=tile.thisT.position;
unit.occupiedTile=tile;
tile.unit=unit;
for(int i=0; i<instance.allFactionList.Count; i++){
Faction faction=instance.allFactionList[i];
if(faction.factionID==factionID){
faction.allUnitList.Add(unit);
break;
}
}
instance.allUnits.Add(unit);
if(onNewUnitInRuntimeE!=null) onNewUnitInRuntimeE(unit);
selectedUnit.occupiedTile.Select();
}
public delegate void UnitFactionChangedHandler(UnitTB unit);
public static event UnitFactionChangedHandler onUnitFactionChangedE;
public static void ChangeUnitFaction(UnitTB scUnit, int targetFactionID){
Faction srcFaction=null;
Faction tgtFaction=null;
for(int i=0; i<instance.allFactionList.Count; i++){
Faction faction=instance.allFactionList[i];
if(faction.factionID==scUnit.factionID){
srcFaction=faction;
}
}
for(int i=0; i<instance.allFactionList.Count; i++){
Faction faction=instance.allFactionList[i];
if(faction.factionID==targetFactionID){
tgtFaction=faction;
}
}
if(srcFaction!=null && tgtFaction!=null){
for(int i=0; i<srcFaction.allUnitList.Count; i++){
UnitTB unit=srcFaction.allUnitList[i];
if(unit==scUnit){
srcFaction.allUnitList.RemoveAt(i);
}
}
tgtFaction.allUnitList.Add(scUnit);
scUnit.factionID=targetFactionID;
if(onUnitFactionChangedE!=null) onUnitFactionChangedE(scUnit);
}
else{
Debug.Log("faction doesn't exist");
}
}
//end code related for unit placement in unit placement phase
//*****************************************************************************************************************************
//reset the yetToMove list in each faction
//for random MoveOrder, called in every new round event
public static void ResetFactionUnitMoveList(){
for(int n=0; n<instance.allFactionList.Count; n++){
Faction faction=instance.allFactionList[n];
faction.unitYetToMove=new List<int>();
for(int i=0; i<faction.allUnitList.Count; i++) faction.unitYetToMove.Add(i);
}
}
//called to register that a unit has been moved
//registered which unit has been moved for each faction so they wont been selected again in the same round
public static void MoveUnit(UnitTB unit){
if(GameControlTB.GetMoveOrder()!=_MoveOrder.Free) return;
bool match=false;
//get the matching faction
for(int n=0; n<instance.allFactionList.Count; n++){
if(unit.factionID==instance.allFactionList[n].factionID){
//get the matching unit
for(int i=0; i<instance.allFactionList[n].allUnitList.Count; i++){
if(instance.allFactionList[n].allUnitList[i]==unit){
//~ if(unit.IsAllActionCompleted()){
//remove the unit ID form yetToMove list
instance.allFactionList[n].unitYetToMove.Remove(i);
//instance.allFactionList[n].numOfUnitMoved+=1;
if(instance.allFactionList[n].unitYetToMove.Count==0)
instance.allFactionList[n].allUnitMoved=true;
//~ }
match=true;
break;
}
}
}
}
if(!match) Debug.Log("Error: no unit found trying to registered a unit moved ");
}
//*************************************************************************************************************************************
//initiating unit turn for each mode
//for turnMode of FactionBasedSingleUnit, each faction takes turn to move one unit at each turn,
//unit with highest initiative in the faction get to move first
//this function arrange unitList in all faction accordingly, unit will be place with their speed in descending order
//for StatsBased MoveOrder
//arrange the units of within each faction locally based on the turnPriority in descending order, unit with the highest value goes first
public static void ArrangeFactionUnitOnTurnPriority(){
foreach(Faction faction in instance.allFactionList){
List<UnitTB> tempList=new List<UnitTB>();
while(faction.allUnitList.Count>0){
float currentHighest=-1;
int highestID=0;
for(int i=0; i<faction.allUnitList.Count; i++){
if(faction.allUnitList[i].GetTurnPriority()>currentHighest){
currentHighest=faction.allUnitList[i].GetTurnPriority();
highestID=i;
}
}
tempList.Add(faction.allUnitList[highestID]);
faction.allUnitList.RemoveAt(highestID);
}
faction.allUnitList=tempList;
}
}
//for SingleUnitPerTurn TurnMode
//arrange the all unit in the game based on the turnPriority in descending order, unit with the highest value goes first
public static void ArrangeAllUnitOnTurnPriority(){
List<UnitTB> tempList=new List<UnitTB>();
while(instance.allUnits.Count>0){
float currentHighest=-Mathf.Infinity;
int highestID=0;
for(int i=0; i<instance.allUnits.Count; i++){
if(instance.allUnits[i].GetTurnPriority()>currentHighest){
currentHighest=instance.allUnits[i].GetTurnPriority();
highestID=i;
}
}
tempList.Add(instance.allUnits[highestID]);
instance.allUnits.RemoveAt(highestID);
}
instance.allUnits=tempList;
}
//for random MoveOrder, randomly rearrange the units within all faction
public static void ShuffleAllUnit(){
for(int n=0; n<instance.allFactionList.Count; n++){
Faction faction=instance.allFactionList[n];
List<UnitTB> shuffledList=new List<UnitTB>();
List<int> IDList=new List<int>();
for(int i=0; i<faction.allUnitList.Count; i++) IDList.Add(i);
for(int i=0; i<faction.allUnitList.Count; i++){
int rand=UnityEngine.Random.Range(0, IDList.Count);
int ID=IDList[rand];
shuffledList.Add(faction.allUnitList[ID]);
IDList.RemoveAt(rand);
}
faction.allUnitList=shuffledList;
}
}
//no longer in use
//for turnMode of UnitPriorityBasedNoCap, all unit simply take turn to move based on stats, there will be no round,
//first calculate the unit baseTurnPriority and turn priority, then rearrange the unitList so the first unit will get to move first
/*
public static void ArrangeAllUnitToTurnPriorityNoCap(){
float currentHighest=-1;
for(int i=0; i<instance.allUnits.Count; i++){
if(instance.allUnits[i].speed>currentHighest){
currentHighest=instance.allUnits[i].speed;
}
}
for(int i=0; i<instance.allUnits.Count; i++){
instance.allUnits[i].turnPriority=currentHighest/instance.allUnits[i].speed;
instance.allUnits[i].baseTurnPriority=instance.allUnits[i].turnPriority;
}
ArrangeAllUnitBasedOnTurnPriority();
}
*/
//end initiating unit turn for each mode
//*************************************************************************************************************************************
void OnBattleEnd(int vicFactionID){
//if persistant data mode is used, save the data
if(!GameControlTB.IsHotSeatMode() && GameControlTB.playerFactionExisted){
if(GameControlTB.LoadMode()!=_LoadMode.UseCurrentData){
List<UnitTB> remainingUnit=new List<UnitTB>();
if(undeployedUnit.Count>0){
remainingUnit=undeployedUnit;
List<UnitTB> tempList=GetAllUnitsOfFaction(GameControlTB.GetPlayerFactionIDS()[0]);
foreach(UnitTB unit in tempList){
if(!unit.GetSpawnInGameFlag()) remainingUnit.Add(unit);
}
}
else{
List<UnitTB> tempList=GetAllUnitsOfFaction(GameControlTB.GetPlayerFactionIDS()[0]);
foreach(UnitTB unit in tempList) if(!unit.GetSpawnInGameFlag()) remainingUnit.Add(unit);
}
if(GameControlTB.LoadMode()!=_LoadMode.UsePersistantData)
GlobalStatsTB.SetPlayerUnitList(remainingUnit);
else if(GameControlTB.LoadMode()!=_LoadMode.UseTemporaryData){
//GlobalStatsTB.SetTempPlayerUnitList(remainingUnit);
}
}
}
}
void OnUnitDestroyed(UnitTB unit){
if(unit.factionID == 0){
Debug.Log ("player unit kill command sent");
GameObject.Find("UI").BroadcastMessage("KillPlayerUnit");
}
if(unit==selectedUnit){
//OnUnitDeselected();
GridManager.Deselect();
}
//reduce currentUnitTurnID by 1 if the unit priority is earlier than this.
//otherwise the next unit following the current unit selected will be skipped
//for unitprioritybased turn mode only
if(GameControlTB.GetTurnMode()==_TurnMode.SingleUnitPerTurn){
int ID=allUnits.IndexOf(unit);
if(ID<=currentUnitTurnID) currentUnitTurnID-=1;
}
allUnits.Remove(unit);
//check if the faction still has other active unit.
int factionID=unit.factionID;
Faction faction=GetFaction(factionID);
if(faction==null) Debug.Log("Error? cant find supposed faction with ID:"+factionID);
//set the turn order, etc.
bool match=false;
if(GameControlTB.GetMoveOrder()==_MoveOrder.Free){
for(int i=0; i<faction.allUnitList.Count; i++){
if(faction.allUnitList[i]==unit){
match=true;
if(faction.unitYetToMove.Contains(i)){
faction.unitYetToMove.Remove(i);
if(faction.unitYetToMove.Count==0)
faction.allUnitMoved=true;
}
for(int n=0; n<faction.unitYetToMove.Count; n++){
if(faction.unitYetToMove[n]>i){
faction.unitYetToMove[n]-=1;
}
}
break;
}
}
if(!match) Debug.Log("Error? cant find unit in supposed faction");
faction.allUnitList.Remove(unit);
}
else{
//reduce currentUnitTurnID by 1 if the unit priority is earlier than this.
int ID=faction.allUnitList.IndexOf(unit);
if(ID<=faction.currentTurnID){
faction.currentTurnID-=1;
if(faction.currentTurnID<0)
faction.currentTurnID=0;
}
faction.allUnitList.Remove(unit);
if(CheckUnmovedUnitInFaction(faction)==0) faction.allUnitMoved=true;
}
//check if faction is still in play
if(faction.allUnitList.Count==0){
activeFactionCount-=1;
if(onFactionDefeatedE!=null) onFactionDefeatedE(factionID);
}
//check if all faction has been defeated
if(activeFactionCount==1){
List<Faction> factionWithUnit=GetFactionsWithUnitRemain();
if(factionWithUnit.Count==1){
GameControlTB.BattleEnded(factionWithUnit[0].factionID);
//if(factionWithUnit[0].isPlayerControl) GameControlTB.BattleEnded(true);
//else GameControlTB.BattleEnded(false);
}
else if(factionWithUnit.Count<=0){
Debug.Log("all unit is dead. error?");
}
}
//for abilities duration tracking
for(int i=0; i<allUnits.Count; i++){
allUnits[i].ReduceUnitAbilityCountTillNextDown();
}
}
//*****************************************************************************************************************************
//Utility function
//check how many unit within the faction has been moved
public static int CheckMovedUnitInFaction(Faction faction){
int count=0;
for(int i=0; i<faction.allUnitList.Count; i++){
if(faction.allUnitList[i].IsAllActionCompleted()) count+=1;
}
return count;
}
//check how many unit within the faction has not been moved
public static int CheckUnmovedUnitInFaction(Faction faction){
int count=0;
for(int i=0; i<faction.allUnitList.Count; i++){
if(!faction.allUnitList[i].IsAllActionCompleted()) count+=1;
}
return count;
}
//return a list of faction that still have active unit in the game
List<Faction> GetFactionsWithUnitRemain(){
List<Faction> factionWithUnit=new List<Faction>();
foreach(Faction faction in allFactionList){
if(faction.allUnitList.Count>0){
factionWithUnit.Add(faction);
}
}
return factionWithUnit;
}
public static int GetActiveFactionsCount(){
return activeFactionCount;
}
//check if faction still have a unit in the game
public static bool IsFactionStillActive(int ID){
if(ID<0 || ID>=instance.allFactionList.Count){
Debug.Log("Faction doesnt exist");
return false;
}
if(instance.allFactionList[ID].allUnitList.Count>0) return true;
return false;
}
//check if all units within a faction has moved
public static bool AllUnitInFactionMoved(int factionID){
if(instance.allFactionList[factionID].allUnitMoved) return true;
return false;
}
//check if all units of all factions has moved
public static bool AllUnitInAllFactionMoved(){
for(int i=0; i<instance.allFactionList.Count; i++){
if(!instance.allFactionList[i].allUnitMoved) return false;
}
return true;
}
public static Faction GetFactionInTurn(int turnID){
return instance.allFactionList[turnID];
}
public static Faction GetFaction(int factionID){
for(int i=0; i<instance.allFactionList.Count; i++){
if(instance.allFactionList[i].factionID==factionID){
return instance.allFactionList[i];
}
}
return null;
}
//~ public static Faction GetPlayerFaction(){
//~ int factionID=GameControlTB.GetPlayerFactionID();
//~ for(int i=0; i<instance.allFactionList.Count; i++){
//~ if(instance.allFactionList[i].factionID==factionID){
//~ return instance.allFactionList[i];
//~ }
//~ }
//~ return null;
//~ }
//return the ID of the first player faction in all faction List, first faction gets to move first
public static int GetPlayerFactionTurnID(){
List<int> factionIDs=GameControlTB.GetPlayerFactionIDS();
for(int i=0; i<instance.allFactionList.Count; i++){
if(factionIDs.Contains(instance.allFactionList[i].factionID)){
return i;
}
}
return -1;
}
//return all the unplaced unit during unit placement phase
public static List<UnitTB> GetUnplacedUnit(){
return instance.playerUnits[instance.facPlacementID].starting;
//return instance.playerUnits[0].starting;
//return instance.startingUnit;
}
//return all unit, unplaced unit not included
public static List<UnitTB> GetAllUnit(){
return instance.allUnits;
}
public static int GetAllUnitCount(){
return instance.allUnits.Count;
}
public static List<UnitTB> GetAllUnitsOfFaction(int factionID){
List<UnitTB> list=new List<UnitTB>();
foreach(UnitTB unit in instance.allUnits){
if(unit.factionID==factionID){
list.Add(unit);
}
}
return list;
}
//get all unit hostile to the faction with faction ID given
public static List<UnitTB> GetAllHostile(int factionID){
List<UnitTB> list=new List<UnitTB>();
foreach(UnitTB unit in instance.allUnits){
if(unit.factionID!=factionID){
list.Add(unit);
}
}
return list;
}
//called by AIManager
public static UnitTB GetNearestHostile(UnitTB srcUnit){
UnitTB targetUnit=null;
float currentNearest=Mathf.Infinity;
foreach(UnitTB unit in instance.allUnits){
if(unit.factionID!=srcUnit.factionID){
float dist=Vector3.Distance(srcUnit.occupiedTile.pos, unit.occupiedTile.pos);
if(dist<currentNearest){
targetUnit=unit;
currentNearest=dist;
}
}
}
return targetUnit;
}
public static UnitTB GetNearestHostileFromList(UnitTB srcUnit, List<UnitTB> targets){
UnitTB targetUnit=null;
float currentNearest=Mathf.Infinity;
for(int i=0; i<targets.Count; i++){
float dist=Vector3.Distance(srcUnit.occupiedTile.pos, targets[i].occupiedTile.pos);
if(dist<currentNearest){
targetUnit=targets[i];
currentNearest=dist;
}
}
return targetUnit;
}
public static List<UnitTB> GetUnitInLOSFromList(UnitTB srcUnit, List<UnitTB> targets){
List<UnitTB> visibleList=GetAllUnitsOfFaction(srcUnit.factionID);
for(int i=0; i<targets.Count; i++){
if(GridManager.IsInLOS(srcUnit.occupiedTile, targets[i].occupiedTile)){
visibleList.Add(targets[i]);
}
}
return visibleList;
}
public static List<UnitTB> GetAllHostileWithinFactionSight(int factionID){
List<UnitTB> AllFriendlies=GetAllUnitsOfFaction(factionID);
List<UnitTB> AllHostiles=GetAllHostile(factionID);
List<UnitTB> hostilesInSight=new List<UnitTB>();
for(int i=0; i<AllFriendlies.Count; i++){
UnitTB friendly=AllFriendlies[i];
for(int j=0; j<AllHostiles.Count; j++){
UnitTB hostile=AllHostiles[j];
if(GridManager.IsInLOS(friendly.occupiedTile, hostile.occupiedTile)){
if(GridManager.Distance(friendly.occupiedTile, hostile.occupiedTile)<=friendly.GetSight()){
hostilesInSight.Add(hostile);
}
}
}
}
return hostilesInSight;
}
public static List<UnitTB> GetAllHostileWithinUnitSight(UnitTB srcUnit){
List<UnitTB> potentialTargets=GetAllHostile(srcUnit.factionID);
List<UnitTB> hostilesInUnitSight=new List<UnitTB>();
for(int i=0; i<potentialTargets.Count; i++){
if(GridManager.IsInLOS(srcUnit.occupiedTile, potentialTargets[i].occupiedTile)){
hostilesInUnitSight.Add(potentialTargets[i]);
}
}
return hostilesInUnitSight;
}
//get possible target from a specific tile for a faction
public static List<UnitTB> GetHostileInRangeFromTile(Tile srcTile, UnitTB srcUnit){
return GetHostileInRangeFromTile(srcTile, srcUnit, false);
}
public static List<UnitTB> GetVisibleHostileInRangeFromTile(Tile srcTile, UnitTB srcUnit){
return GetHostileInRangeFromTile(srcTile, srcUnit, true);
}
public static List<UnitTB> GetHostileInRangeFromTile(Tile srcTile, UnitTB srcUnit, bool visibleOnly){
int unitMinRange=srcUnit.GetUnitAttackRangeMin();
int unitMaxRange=srcUnit.GetUnitAttackRangeMax();
List<Tile> tilesInRange=GridManager.GetTilesWithinRange(srcTile, unitMinRange, unitMaxRange);
List<UnitTB> hostilesList=new List<UnitTB>();
for(int i=0; i<tilesInRange.Count; i++){
if(tilesInRange[i].unit!=null && tilesInRange[i].unit.factionID!=srcUnit.factionID){
if(visibleOnly){
if(GridManager.IsInLOS(srcTile, tilesInRange[i])){
hostilesList.Add(tilesInRange[i].unit);
}
}
else{
hostilesList.Add(tilesInRange[i].unit);
}
}
}
return hostilesList;
}
//*************************************************************************************************************
//external code, not in used
/*
private bool isWarCorpAlpha=true;
void WarCorpInitRoutine(){
if(GameControlTB.LoadMode()==_LoadMode.UseTemporaryData){
List<Mech> squadList=UnitManager.GetSquadList();
for(int i=0; i<startingUnit.Count; i++){
if(squadList[i]!=null){
startingUnit[i].instanceID=squadList[i].instanceID;
}
}
//List<Mech> squadList=UnitManager.GetSquadList();
//for(int i=0; i<squadList.Count; i++){
// if(squadList[i]==null){
// squadList.RemoveAt(i);
// startingUnit.RemoveAt(i);
// i-=1;
// }
//}
for(int i=0; i<startingUnit.Count; i++){
if(startingUnit[i]!=null){
Mech mech=squadList[i];
UnitTB unit=startingUnit[i];
unit.unitName=mech.name;
unit.rangeDamageMin=mech.weap.damageMin;
unit.rangeDamageMax=mech.weap.damageMax;
unit.criticalRange=mech.weap.critChance;
unit.APCostAttack=mech.weap.apCost;
unit.attack=mech.pilot.attack;
unit.defend=mech.pilot.defend*0.5f;
unit.HP=(int)Mathf.Round(mech.status*0.01f*unit.GetFullHP());
if(mech.weap.weapClass==mech.pilot.weapClass) unit.attack+=0.05f;
if(mech.mechClass==mech.pilot.mechClass) unit.defend+=0.05f;
}
}
Debug.Log(squadList.Count);
}
}
*/
//end external code
public void OnDrawGizmos(){
if(selectedUnit!=null){
//Debug.Log(selectedUnit+" "+selectedUnit.moved+" "+selectedUnit.attacked+" "+ selectedUnit.transform.position);
//Gizmos.DrawSphere(selectedUnit.transform.position, 1);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpegfx;
using Microsoft.Protocols.TestSuites.Rdpbcgr;
using Microsoft.Protocols.TestSuites.Rdp;
namespace Microsoft.Protocols.TestSuites.Rdpegfx
{
public partial class RdpegfxTestSuite : RdpTestClassBase
{
[TestMethod]
[Priority(0)]
[TestCategory("BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to test SurfacetoCache, and CacheToSurface command.")]
public void RDPEGFX_CacheManagement_PositiveTest()
{
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
// Build muliple cache to surface messages to cover the surface by cacheRect
ushort cacheW = (ushort)(RdpegfxTestUtility.cacheRect.right - RdpegfxTestUtility.cacheRect.left);
ushort cacheH = (ushort)(RdpegfxTestUtility.cacheRect.bottom - RdpegfxTestUtility.cacheRect.top);
ushort currRectTop = 0;
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
while (currRectTop < surf.Height)
{
ushort currRectLeft = 0;
while (currRectLeft < surf.Width)
{
RDPGFX_POINT16 pos = new RDPGFX_POINT16(currRectLeft, currRectTop);
destPointList.Add(pos);
currRectLeft += cacheW;
}
currRectTop += cacheH;
}
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled by cached bitmap in frame: {0}", fid);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when receiving RDPGFX_SURFACE_TO_CACHE_PDU with the max cacheSlot number.")]
public void RDPEGFX_CacheManagement_PositiveTest_SurfaceToCache_MaxCacheSlot()
{
ushort maxCacheSlot = RdpegfxTestUtility.maxCacheSlot;
if (this.isSmallCache)
{
maxCacheSlot = RdpegfxTestUtility.maxCacheSlotForSmallCache;
}
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
RDPGFX_POINT16 pos = new RDPGFX_POINT16(RdpegfxTestUtility.cacheRect.right, RdpegfxTestUtility.cacheRect.bottom);
destPointList.Add(pos);
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy a rect to cache; and copy the cached rect to surface, using max cacheSlot: {0}.", maxCacheSlot);
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), maxCacheSlot, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled by cached bitmap in frame: {0}, use max cacheSlot number {1}.", fid, maxCacheSlot);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when its cache reached max size.")]
public void RDPEGFX_CacheManagement_PositiveTest_SurfaceToCache_MaxCacheSize()
{
int maxCacheSize = RdpegfxTestUtility.maxCacheSize;
if (this.isSmallCache)
{
maxCacheSize = RdpegfxTestUtility.maxCacheSizeForSmallCache;
}
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
// Add Image to cache, 1M for each image
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy rects of surface to cache, each rect is 1M, there are {0} slot in total to reach max size.", maxCacheSize);
for (ushort slot = 1; slot <= maxCacheSize; slot++)
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy a rect of surface to cache, slot is {0}.", slot);
uint fid = this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, slot, RdpegfxTestUtility.fillColorRed);
this.rdpegfxAdapter.ExpectFrameAck(fid);
}
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process correctly when receiving RDPGFX_SURFACE_TO_CACHE_PDU whose srcRect specific borders overlapped with surface.")]
public void RDPEGFX_CacheManagement_PositiveTest_SurfaceToCache_SrcRectBorderOverlapSurface()
{
ushort maxCacheSlot = RdpegfxTestUtility.maxCacheSlot;
if (this.isSmallCache)
{
maxCacheSlot = RdpegfxTestUtility.maxCacheSlotForSmallCache;
}
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
// Create srcRect, in the bottom-right corner of surface
RDPGFX_RECT16 srcRect = new RDPGFX_RECT16();
srcRect.left = (ushort)(RdpegfxTestUtility.surfWidth - RdpegfxTestUtility.smallWidth);
srcRect.top = (ushort)(RdpegfxTestUtility.surfHeight - RdpegfxTestUtility.smallHeight);
srcRect.right = RdpegfxTestUtility.surfWidth;
srcRect.bottom = RdpegfxTestUtility.surfHeight;
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy a rect to cache; and copy the cached rect to surface.");
RDPGFX_POINT16[] destPoints = new RDPGFX_POINT16[] { RdpegfxTestUtility.imgPos };
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, srcRect, RdpegfxTestUtility.cacheKey, destPoints, null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled by cached bitmap in frame: {0}.", fid, maxCacheSlot);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when receiving RDPGFX_SURFACE_TO_CACHE_PDU with a used cacheSlot number.")]
public void RDPEGFX_CacheManagement_PositiveTest_SurfaceToCache_UpdateCache()
{
ushort cacheSlot = 1;
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Cache a rect of Surface to cache.");
uint fid = this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, cacheSlot, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Debug, "Cache a rect in surface, slot is {0}.", cacheSlot);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Cache a rect of Surface to cache with same cacheSlot.");
fid = this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, cacheSlot, RdpegfxTestUtility.fillColorGreen);
this.TestSite.Log.Add(LogEntryKind.Debug, "Cache a rect in surface, slot is {0}.", cacheSlot);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Fill the Surface with cached slot.");
RDPGFX_POINT16[] destPoints = new RDPGFX_POINT16[] { new RDPGFX_POINT16(RdpegfxTestUtility.cacheRect.right, RdpegfxTestUtility.cacheRect.bottom) };
fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, cacheSlot, destPoints);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when receiving RDPGFX_CACHE_TO_SURFACE_PDU whose dest rects specific borders overlapped with surface.")]
public void RDPEGFX_CacheManagement_PositiveTest_CacheToSurface_DestRectsBorderOverlapSurface()
{
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
ushort cacheW = (ushort)(RdpegfxTestUtility.cacheRect.right - RdpegfxTestUtility.cacheRect.left);
ushort cacheH = (ushort)(RdpegfxTestUtility.cacheRect.bottom - RdpegfxTestUtility.cacheRect.top);
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
RDPGFX_POINT16 pos = new RDPGFX_POINT16(
(ushort)(RdpegfxTestUtility.surfWidth - cacheW),
(ushort)(RdpegfxTestUtility.surfHeight - cacheH));
destPointList.Add(pos);
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy a rect to cache; and copy the cached rect to surface.");
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled by cached bitmap in frame: {0}.", fid);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when receiving RDPGFX_CACHE_TO_SURFACE_PDU whose dest rects partially overlapped with each other.")]
public void RDPEGFX_CacheManagement_PositiveTest_CacheToSurface_DestRectsOverlapped()
{
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
// Send solid fill request to client to fill a rect to green color
this.TestSite.Log.Add(LogEntryKind.Comment, "Send solid fill request to client to fill a rect to green color.");
RDPGFX_RECT16 fillSurfRect = new RDPGFX_RECT16(0, 0, RdpegfxTestUtility.smallWidth, RdpegfxTestUtility.smallHeight);
RDPGFX_RECT16[] fillRects = { fillSurfRect }; // Relative to surface
uint fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorGreen, fillRects);
this.rdpegfxAdapter.ExpectFrameAck(fid);
// Send solid fill request to client to fill a rect to red color
this.TestSite.Log.Add(LogEntryKind.Comment, "Send solid fill request to client to fill a rect to red color.");
RDPGFX_RECT16 fillSurfRect2 = new RDPGFX_RECT16(RdpegfxTestUtility.smallWidth, RdpegfxTestUtility.smallHeight, (ushort)(RdpegfxTestUtility.smallWidth * 2), (ushort)(RdpegfxTestUtility.smallHeight * 2));
RDPGFX_RECT16[] fillRects2 = { fillSurfRect2 }; // Relative to surface
fid = this.rdpegfxAdapter.SolidFillSurface(surf, RdpegfxTestUtility.fillColorRed, fillRects2);
this.rdpegfxAdapter.ExpectFrameAck(fid);
RDPGFX_RECT16 srcRect = new RDPGFX_RECT16(0, 0, (ushort)(RdpegfxTestUtility.smallWidth * 2), (ushort)(RdpegfxTestUtility.smallHeight * 2));
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
RDPGFX_POINT16 pos = new RDPGFX_POINT16((ushort)(RdpegfxTestUtility.smallWidth * 2), (ushort)(RdpegfxTestUtility.smallHeight * 2));
destPointList.Add(pos);
pos = new RDPGFX_POINT16((ushort)(RdpegfxTestUtility.smallWidth * 3), (ushort)(RdpegfxTestUtility.smallHeight * 3));
destPointList.Add(pos);
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy a rect to cache; and copy the cached rect to surface.");
fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), null, null);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface is filled by cached bitmap in frame: {0}.", fid);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
RDPGFX_RECT16 verifyRect = new RDPGFX_RECT16(
(ushort)(RdpegfxTestUtility.smallWidth * 2), (ushort)(RdpegfxTestUtility.smallHeight * 2),
(ushort)(RdpegfxTestUtility.smallWidth * 5), (ushort)(RdpegfxTestUtility.smallHeight * 5));
this.VerifySUTDisplay(false, surfRect);
// Delete the surface after wait 3 seconds.
this.rdpegfxAdapter.DeleteSurface(surf.Id);
this.TestSite.Log.Add(LogEntryKind.Debug, "Surface {0} is deleted", surf.Id);
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Positive")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("This test case is used to verify RDP client can process cache correctly when receiving RDPGFX_EVICT_CACHE_ENTRY_PDU to delete a slot.")]
public void RDPEGFX_CacheManagement_PositiveTest_EvictCache_DeleteCacheSlot()
{
ushort cacheSlot = 1;
// Init for capability exchange
RDPEGFX_CapabilityExchange();
// Create a surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Surface.");
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.surfWidth, RdpegfxTestUtility.surfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Fill a rect on surface and cache this rect.");
uint fid = this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.cacheRect, RdpegfxTestUtility.cacheKey, cacheSlot, RdpegfxTestUtility.fillColorRed);
this.rdpegfxAdapter.ExpectFrameAck(fid);
this.TestSite.Log.Add(LogEntryKind.Comment, "Evict the cache slot.");
fid = this.rdpegfxAdapter.EvictCachEntry(cacheSlot);
this.rdpegfxAdapter.ExpectFrameAck(fid);
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
RDPGFX_POINT16 pos = new RDPGFX_POINT16(RdpegfxTestUtility.cacheRect.right, RdpegfxTestUtility.cacheRect.bottom);
destPointList.Add(pos);
this.TestSite.Log.Add(LogEntryKind.Comment, "Copy image from deleted slot.");
fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, cacheSlot, destPointList.ToArray());
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Negative")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("The server attempts to allocate cache slots which exceeds size upper limitation for default cache flag")]
public void RDPEGFX_CacheManagement_Negative_Default_ExceedMaxCacheSize()
{
this.TestSite.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ...");
StartRDPConnection();
this.TestSite.Log.Add(LogEntryKind.Debug, "Creating dynamic virtual channels for MS-RDPEGFX ...");
bool bProtocolSupported = this.rdpegfxAdapter.ProtocolInitialize(this.rdpedycServer);
TestSite.Assert.IsTrue(bProtocolSupported, "Client should support this protocol.");
this.TestSite.Log.Add(LogEntryKind.Debug, "Expecting capability advertise from client.");
RDPGFX_CAPS_ADVERTISE capsAdv = this.rdpegfxAdapter.ExpectCapabilityAdvertise();
this.TestSite.Assert.IsNotNull(capsAdv, "RDPGFX_CAPS_ADVERTISE is received.");
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending capability confirm with default capability flag to client.");
// Set capability flag to default, then the max cache size is 100MB
CapsFlags capFlag = CapsFlags.RDPGFX_CAPS_FLAG_DEFAULT;
this.rdpegfxAdapter.SendCapabilityConfirm(capFlag);
// Create & output a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.CacheManagement_Default_ExceedMaxCacheSize);
this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.CacheManagement_Default_ExceedMaxCacheSize);
// Send message to trigger client to allocate cache slots with cache size exceed the max value 100MB
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to allocate cache slots with cache size exceed the max value 100MB");
this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Negative")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("Check if client can use an inexistent surface as source for cache successfully")]
public void RDPEGFX_CacheManagement_Negative_SurfaceToCache_InexistentSurface()
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange.");
RDPEGFX_CapabilityExchange();
// Create a surface & output a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.CacheManagement_SurfaceToCache_InexistentSurface);
this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.CacheManagement_SurfaceToCache_InexistentSurface);
// Send message to trigger client to allocate cache slots with cache size exceed the max value 100MB
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to use an inexistent surface as source for cache");
this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Negative")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("Check if client can copy cached bitmap data to inexistent surface")]
public void RDPEGFX_CacheManagement_Negative_CacheToSurface_InexistentSurface()
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange.");
RDPEGFX_CapabilityExchange();
// Create a surface & output a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.CacheManagement_CacheToSurface_InexistentSurface);
this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.CacheManagement_CacheToSurface_InexistentSurface);
// Build mutliple cache to surface messages to cover the surface by cacheRect
ushort cacheW = (ushort)(RdpegfxTestUtility.largeCacheRect.right - RdpegfxTestUtility.largeCacheRect.left);
ushort cacheH = (ushort)(RdpegfxTestUtility.largeCacheRect.bottom - RdpegfxTestUtility.largeCacheRect.top);
ushort currRectTop = 0;
// DestPointList is a list of positions in destination surface where the bitmap cache will copy to
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
while (currRectTop < surf.Height)
{
ushort currRectLeft = 0;
while (currRectLeft < surf.Width)
{
RDPGFX_POINT16 pos = new RDPGFX_POINT16(currRectLeft, currRectTop);
destPointList.Add(pos);
currRectLeft += cacheW;
}
currRectTop += cacheH;
}
// Trigger the client to copy cached bitmap data to inexistent surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger the client to copy cached bitmap data to inexistent surface.");
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Negative")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("Check if client can copy cached bitmap from an inexistent cache slot to destination surface")]
public void RDPEGFX_CacheManagement_Negative_CacheToSurface_InexistentCacheSlot()
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange.");
RDPEGFX_CapabilityExchange();
// Create a surface & output a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.CacheManagement_CacheToSurface_InexistentCacheSlot);
this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.CacheManagement_CacheToSurface_InexistentCacheSlot);
// Build mutliple cache to surface messages to cover the surface by cacheRect
ushort cacheW = (ushort)(RdpegfxTestUtility.largeCacheRect.right - RdpegfxTestUtility.largeCacheRect.left);
ushort cacheH = (ushort)(RdpegfxTestUtility.largeCacheRect.bottom - RdpegfxTestUtility.largeCacheRect.top);
ushort currRectTop = 0;
// DestPointList is a list of positions in destination surface where the bitmap cache will copy to
List<RDPGFX_POINT16> destPointList = new List<RDPGFX_POINT16>();
while (currRectTop < surf.Height)
{
ushort currRectLeft = 0;
while (currRectLeft < surf.Width)
{
RDPGFX_POINT16 pos = new RDPGFX_POINT16(currRectLeft, currRectTop);
destPointList.Add(pos);
currRectLeft += cacheW;
}
currRectTop += cacheH;
}
// Trigger the client to copy cached bitmap from an inexsitent cache slot to destination surface
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger the client to copy cached bitmap from an inexistent cache slot to destination surface.");
uint fid = this.rdpegfxAdapter.FillSurfaceByCachedBitmap(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, destPointList.ToArray(), null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
[TestMethod]
[Priority(1)]
[TestCategory("Non-BVT")]
[TestCategory("Negative")]
[TestCategory("RDP8.0")]
[TestCategory("RDPEGFX")]
[Description("Check if client can handle a request of deleting an inexistent cache slot")]
public void RDPEGFX_CacheManagement_Negative_Delete_InexistentCacheSlot()
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Do capability exchange.");
RDPEGFX_CapabilityExchange();
// Create a surface
RDPGFX_RECT16 surfRect = RdpegfxTestUtility.ConvertToRect(RdpegfxTestUtility.surfPos, RdpegfxTestUtility.largeSurfWidth, RdpegfxTestUtility.largeSurfHeight);
Surface surf = this.rdpegfxAdapter.CreateAndOutputSurface(surfRect, PixelFormat.PIXEL_FORMAT_ARGB_8888);
this.TestSite.Assert.IsNotNull(surf, "Surface {0} is created", surf.Id);
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdpegfxNegativeTypes.CacheManagement_Delete_InexistentCacheSlot);
this.rdpegfxAdapter.SetTestType(RdpegfxNegativeTypes.CacheManagement_Delete_InexistentCacheSlot);
// Trigger the client to delete an inexistent cache slot
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger the client to delete an inexistent cache slot.");
this.rdpegfxAdapter.CacheSurface(surf, RdpegfxTestUtility.largeCacheRect, RdpegfxTestUtility.cacheKey, null, RdpegfxTestUtility.fillColorRed);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "RDP client should terminate the connection when invalid message received.");
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VUserInfo class.
/// </summary>
[Serializable]
public partial class VUserInfoCollection : ReadOnlyList<VUserInfo, VUserInfoCollection>
{
public VUserInfoCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vUserInfo view.
/// </summary>
[Serializable]
public partial class VUserInfo : ReadOnlyRecord<VUserInfo>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vUserInfo", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarLastActivityDate = new TableSchema.TableColumn(schema);
colvarLastActivityDate.ColumnName = "LastActivityDate";
colvarLastActivityDate.DataType = DbType.DateTime;
colvarLastActivityDate.MaxLength = 0;
colvarLastActivityDate.AutoIncrement = false;
colvarLastActivityDate.IsNullable = false;
colvarLastActivityDate.IsPrimaryKey = false;
colvarLastActivityDate.IsForeignKey = false;
colvarLastActivityDate.IsReadOnly = false;
schema.Columns.Add(colvarLastActivityDate);
TableSchema.TableColumn colvarUserName = new TableSchema.TableColumn(schema);
colvarUserName.ColumnName = "UserName";
colvarUserName.DataType = DbType.String;
colvarUserName.MaxLength = 256;
colvarUserName.AutoIncrement = false;
colvarUserName.IsNullable = false;
colvarUserName.IsPrimaryKey = false;
colvarUserName.IsForeignKey = false;
colvarUserName.IsReadOnly = false;
schema.Columns.Add(colvarUserName);
TableSchema.TableColumn colvarCreateDate = new TableSchema.TableColumn(schema);
colvarCreateDate.ColumnName = "CreateDate";
colvarCreateDate.DataType = DbType.DateTime;
colvarCreateDate.MaxLength = 0;
colvarCreateDate.AutoIncrement = false;
colvarCreateDate.IsNullable = false;
colvarCreateDate.IsPrimaryKey = false;
colvarCreateDate.IsForeignKey = false;
colvarCreateDate.IsReadOnly = false;
schema.Columns.Add(colvarCreateDate);
TableSchema.TableColumn colvarEmail = new TableSchema.TableColumn(schema);
colvarEmail.ColumnName = "Email";
colvarEmail.DataType = DbType.String;
colvarEmail.MaxLength = 256;
colvarEmail.AutoIncrement = false;
colvarEmail.IsNullable = true;
colvarEmail.IsPrimaryKey = false;
colvarEmail.IsForeignKey = false;
colvarEmail.IsReadOnly = false;
schema.Columns.Add(colvarEmail);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.String;
colvarComment.MaxLength = 1073741823;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
schema.Columns.Add(colvarComment);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vUserInfo",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VUserInfo()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VUserInfo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VUserInfo(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VUserInfo(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("LastActivityDate")]
[Bindable(true)]
public DateTime LastActivityDate
{
get
{
return GetColumnValue<DateTime>("LastActivityDate");
}
set
{
SetColumnValue("LastActivityDate", value);
}
}
[XmlAttribute("UserName")]
[Bindable(true)]
public string UserName
{
get
{
return GetColumnValue<string>("UserName");
}
set
{
SetColumnValue("UserName", value);
}
}
[XmlAttribute("CreateDate")]
[Bindable(true)]
public DateTime CreateDate
{
get
{
return GetColumnValue<DateTime>("CreateDate");
}
set
{
SetColumnValue("CreateDate", value);
}
}
[XmlAttribute("Email")]
[Bindable(true)]
public string Email
{
get
{
return GetColumnValue<string>("Email");
}
set
{
SetColumnValue("Email", value);
}
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get
{
return GetColumnValue<string>("Comment");
}
set
{
SetColumnValue("Comment", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string UserId = @"UserId";
public static string LastActivityDate = @"LastActivityDate";
public static string UserName = @"UserName";
public static string CreateDate = @"CreateDate";
public static string Email = @"Email";
public static string Comment = @"Comment";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace QText {
internal class TabFiles : TabControl {
public TabFiles()
: base() {
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
Appearance = TabAppearance.Normal;
DrawMode = TabDrawMode.Normal;
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
}
private readonly StringFormat StringFormat = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center };
protected override void OnDrawItem(DrawItemEventArgs e) {
if (e == null) { return; }
base.OnDrawItem(e);
var tab = (TabFile)TabPages[e.Index];
var x = e.Bounds.Left;
var y = e.Bounds.Top + e.Bounds.Height / 2;
e.Graphics.FillRectangle(SystemBrushes.Control, e.Bounds);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) {
var selectionColor = Color.FromArgb(128, SystemColors.Highlight.R, SystemColors.Highlight.G, SystemColors.Highlight.B);
using (var selectionBrush = new LinearGradientBrush(e.Bounds, selectionColor, SystemColors.Control, LinearGradientMode.Vertical) { Blend = new Blend() { Positions = new float[] { 0.75F, 1 } } }) {
e.Graphics.FillRectangle(selectionBrush, e.Bounds);
}
x += SystemInformation.SizingBorderWidth;
} else {
x += SystemInformation.Border3DSize.Width;
y += SystemInformation.Border3DSize.Height;
}
if (tab.BaseFile.IsEncrypted) {
e.Graphics.DrawString(tab.Text, Font, Brushes.DarkGreen, x, y, StringFormat);
} else {
e.Graphics.DrawString(tab.Text, Font, SystemBrushes.ControlText, x, y, StringFormat);
}
}
protected override void OnGotFocus(EventArgs e) {
base.OnGotFocus(e);
if (SelectedTab != null) { SelectedTab.Select(); }
}
protected override void OnSelected(TabControlEventArgs e) {
if (e.TabPage is TabFile tabFile) { tabFile.BaseFile.Selected = true; }
}
public DocumentFolder CurrentFolder { get; private set; }
public ContextMenuStrip TabContextMenuStrip { get; set; }
public void FolderOpen(DocumentFolder folder, bool saveBeforeOpen = true) {
if ((CurrentFolder != null) && (saveBeforeOpen)) { FolderSave(); }
var initialVisibility = Visible;
Visible = false;
SelectedTab = null;
TabPages.Clear();
CurrentFolder = folder ?? throw new ArgumentNullException("folder", "Folder cannot be null.");
foreach (var tab in Helper.GetTabs(CurrentFolder.GetFiles(), TabContextMenuStrip)) {
TabPages.Add(tab);
}
var selectedTab = (TabCount > 0) ? (TabFile)TabPages[0] : null;
foreach (TabFile tab in TabPages) {
if (tab.BaseFile.Equals(folder.SelectedFile)) {
selectedTab = tab;
}
}
SelectNextTab(selectedTab);
if (SelectedTab != null) {
SelectedTab.Select();
OnSelectedIndexChanged(new EventArgs());
}
Visible = initialVisibility;
if (SelectedTab != null) {
SelectedTab.Select();
OnSelectedIndexChanged(new EventArgs());
}
}
public void SelectNextTab(TabFile preferredTab) {
if (preferredTab == null) { return; }
if (preferredTab.BaseFile.IsEncrypted) {
var currIndex = TabPages.IndexOf(preferredTab);
preferredTab = null; //remove it in case that no unencrypted tab is found
for (var i = 0; i < TabPages.Count; i++) {
var nextIndex = (currIndex + i) % TabPages.Count;
var nextTab = (TabFile)TabPages[nextIndex];
if (nextTab.BaseFile.IsEncrypted == false) {
preferredTab = nextTab;
break;
}
}
}
SelectedTab = preferredTab;
}
public void FolderSave() {
foreach (TabFile file in TabPages) {
if (file.IsChanged) { file.Save(); }
}
}
private TabPage GetTabPageFromXY(int x, int y) {
for (var i = 0; i <= base.TabPages.Count - 1; i++) {
if (base.GetTabRect(i).Contains(x, y)) {
return base.TabPages[i];
}
}
return null;
}
internal new TabFile SelectedTab {
get {
try {
if (base.SelectedTab == null) { return null; }
return base.SelectedTab as QText.TabFile;
} catch (NullReferenceException) { //work around for bug (Bajus)
return null;
}
}
set {
if (value != null) { value.BaseFile.Selected = true; }
base.SelectedTab = value;
}
}
#region File operations
public void AddTab(string title, bool isRichText) {
var t = TabFile.Create(CurrentFolder, title, isRichText ? DocumentKind.RichText : DocumentKind.PlainText);
t.ContextMenuStrip = TabContextMenuStrip;
if (SelectedTab != null) {
TabPages.Insert(TabPages.IndexOf(SelectedTab) + 1, t);
} else {
TabPages.Add(t);
}
SelectedTab = t;
}
public void DeleteTab(TabFile tab) {
RemoveTab(tab);
tab.BaseFile.Delete();
}
public void RemoveTab(TabFile tab) {
SelectedTab = GetNextTab();
TabPages.Remove(tab);
if (SelectedTab != null) {
SelectedTab.Open();
}
}
#endregion
#region Drag & drop
private TabPage _dragTabPage = null;
protected override void OnMouseDown(MouseEventArgs e) {
if ((e != null) && (e.Button == MouseButtons.Left) && (base.SelectedTab != null) && (!base.GetTabRect(base.SelectedIndex).IsEmpty)) {
_dragTabPage = base.SelectedTab;
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
if ((e != null) && (e.Button == MouseButtons.Left) && (_dragTabPage != null)) {
var currTabPage = GetTabPageFromXY(e.X, e.Y);
if ((currTabPage != null)) {
_ = base.GetTabRect(base.TabPages.IndexOf(currTabPage));
if ((base.TabPages.IndexOf(currTabPage) < base.TabPages.IndexOf(_dragTabPage))) {
base.Cursor = Cursors.PanWest;
} else if ((base.TabPages.IndexOf(currTabPage) > base.TabPages.IndexOf(_dragTabPage))) {
base.Cursor = Cursors.PanEast;
} else {
base.Cursor = Cursors.Default;
}
} else {
Cursor = Cursors.No;
}
} else {
Cursor = Cursors.Default;
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e) {
if ((e != null) && (e.Button == MouseButtons.Left) && (_dragTabPage != null)) {
var currTabPage = GetTabPageFromXY(e.X, e.Y);
if ((currTabPage != null) && (!currTabPage.Equals(_dragTabPage))) {
_ = base.GetTabRect(base.TabPages.IndexOf(currTabPage));
base.Enabled = false;
if ((base.TabPages.IndexOf(currTabPage) < base.TabPages.IndexOf(_dragTabPage))) {
base.TabPages.Remove(_dragTabPage);
base.TabPages.Insert(base.TabPages.IndexOf(currTabPage), _dragTabPage);
base.SelectedTab = _dragTabPage;
var pivotTab = currTabPage as TabFile;
var movedTab = _dragTabPage as TabFile;
movedTab.BaseFile.OrderBefore(pivotTab.BaseFile);
} else if ((base.TabPages.IndexOf(currTabPage) > base.TabPages.IndexOf(_dragTabPage))) {
base.TabPages.Remove(_dragTabPage);
base.TabPages.Insert(base.TabPages.IndexOf(currTabPage) + 1, _dragTabPage);
base.SelectedTab = _dragTabPage;
var pivotTab = currTabPage as TabFile;
var movedTab = _dragTabPage as TabFile;
movedTab.BaseFile.OrderAfter(pivotTab.BaseFile);
}
base.Enabled = true;
}
}
_dragTabPage = null;
base.Cursor = Cursors.Default;
base.OnMouseUp(e);
}
#endregion
private TabFile GetNextTab() {
var tindex = TabPages.IndexOf(SelectedTab) + 1; //select next tab
if (tindex >= TabPages.Count) {
tindex -= 2; //go to one in front of it
}
if ((tindex > 0) && (tindex < TabPages.Count)) {
return (TabFile)TabPages[tindex];
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Http;
namespace System.ServiceModel.Channels
{
public sealed class HttpRequestMessageProperty : IMessageProperty, IMergeEnabledMessageProperty
{
private TraditionalHttpRequestMessageProperty _traditionalProperty;
private HttpRequestMessageBackedProperty _httpBackedProperty;
private bool _initialCopyPerformed;
private bool _useHttpBackedProperty;
public HttpRequestMessageProperty()
{
_traditionalProperty = new TraditionalHttpRequestMessageProperty();
_useHttpBackedProperty = false;
}
internal HttpRequestMessageProperty(WebHeaderCollection originalHeaders)
{
_traditionalProperty = new TraditionalHttpRequestMessageProperty(originalHeaders);
_useHttpBackedProperty = false;
}
internal HttpRequestMessageProperty(HttpRequestMessage httpRequestMessage)
{
_httpBackedProperty = new HttpRequestMessageBackedProperty(httpRequestMessage);
_useHttpBackedProperty = true;
}
public static string Name
{
get { return "httpRequest"; }
}
public WebHeaderCollection Headers
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.Headers :
_traditionalProperty.Headers;
}
}
public string Method
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.Method :
_traditionalProperty.Method;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (_useHttpBackedProperty)
{
_httpBackedProperty.Method = value;
}
else
{
_traditionalProperty.Method = value;
}
}
}
public string QueryString
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.QueryString :
_traditionalProperty.QueryString;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (_useHttpBackedProperty)
{
_httpBackedProperty.QueryString = value;
}
else
{
_traditionalProperty.QueryString = value;
}
}
}
public bool SuppressEntityBody
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.SuppressEntityBody :
_traditionalProperty.SuppressEntityBody;
}
set
{
if (_useHttpBackedProperty)
{
_httpBackedProperty.SuppressEntityBody = value;
}
else
{
_traditionalProperty.SuppressEntityBody = value;
}
}
}
public HttpRequestMessage HttpRequestMessage
{
get
{
if (_useHttpBackedProperty)
{
return _httpBackedProperty.HttpRequestMessage;
}
return null;
}
}
internal static HttpRequestMessage GetHttpRequestMessageFromMessage(Message message)
{
HttpRequestMessage httpRequestMessage = null;
HttpRequestMessageProperty property = message.Properties.GetValue<HttpRequestMessageProperty>(HttpRequestMessageProperty.Name);
if (property != null)
{
httpRequestMessage = property.HttpRequestMessage;
if (httpRequestMessage != null)
{
httpRequestMessage.CopyPropertiesFromMessage(message);
message.EnsureReadMessageState();
}
}
return httpRequestMessage;
}
IMessageProperty IMessageProperty.CreateCopy()
{
if (!_useHttpBackedProperty ||
!_initialCopyPerformed)
{
_initialCopyPerformed = true;
return this;
}
return _httpBackedProperty.CreateTraditionalRequestMessageProperty();
}
bool IMergeEnabledMessageProperty.TryMergeWithProperty(object propertyToMerge)
{
// The ImmutableDispatchRuntime will merge MessageProperty instances from the
// OperationContext (that were created before the response message was created) with
// MessageProperty instances on the message itself. The message's version of the
// HttpRequestMessageProperty may hold a reference to an HttpRequestMessage, and this
// cannot be discarded, so values from the OperationContext's property must be set on
// the message's version without completely replacing the message's property.
if (_useHttpBackedProperty)
{
HttpRequestMessageProperty requestProperty = propertyToMerge as HttpRequestMessageProperty;
if (requestProperty != null)
{
if (!requestProperty._useHttpBackedProperty)
{
_httpBackedProperty.MergeWithTraditionalProperty(requestProperty._traditionalProperty);
requestProperty._traditionalProperty = null;
requestProperty._httpBackedProperty = _httpBackedProperty;
requestProperty._useHttpBackedProperty = true;
}
return true;
}
}
return false;
}
private class TraditionalHttpRequestMessageProperty
{
public const string DefaultMethod = "POST";
public const string DefaultQueryString = "";
private string _method;
public TraditionalHttpRequestMessageProperty()
{
_method = DefaultMethod;
this.QueryString = DefaultQueryString;
}
private WebHeaderCollection _headers;
private WebHeaderCollection _originalHeaders;
public TraditionalHttpRequestMessageProperty(WebHeaderCollection originalHeaders) : this()
{
_originalHeaders = originalHeaders;
}
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new WebHeaderCollection();
if (_originalHeaders != null)
{
foreach (var headerKey in _originalHeaders.AllKeys)
{
_headers[headerKey] = _originalHeaders[headerKey];
}
_originalHeaders = null;
}
}
return _headers;
}
}
public string Method
{
get
{
return _method;
}
set
{
_method = value;
this.HasMethodBeenSet = true;
}
}
public bool HasMethodBeenSet { get; private set; }
public string QueryString { get; set; }
public bool SuppressEntityBody { get; set; }
}
private class HttpRequestMessageBackedProperty
{
public HttpRequestMessageBackedProperty(HttpRequestMessage httpRequestMessage)
{
Contract.Assert(httpRequestMessage != null, "The 'httpRequestMessage' property should never be null.");
this.HttpRequestMessage = httpRequestMessage;
}
public HttpRequestMessage HttpRequestMessage { get; private set; }
private WebHeaderCollection _headers;
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = this.HttpRequestMessage.ToWebHeaderCollection();
}
return _headers;
}
}
public string Method
{
get
{
return this.HttpRequestMessage.Method.Method;
}
set
{
this.HttpRequestMessage.Method = new HttpMethod(value);
}
}
public string QueryString
{
get
{
string query = this.HttpRequestMessage.RequestUri.Query;
return query.Length > 0 ? query.Substring(1) : string.Empty;
}
set
{
UriBuilder uriBuilder = new UriBuilder(this.HttpRequestMessage.RequestUri);
uriBuilder.Query = value;
this.HttpRequestMessage.RequestUri = uriBuilder.Uri;
}
}
public bool SuppressEntityBody
{
get
{
HttpContent content = this.HttpRequestMessage.Content;
if (content != null)
{
long? contentLength = content.Headers.ContentLength;
if (!contentLength.HasValue ||
(contentLength.HasValue && contentLength.Value > 0))
{
return false;
}
}
return true;
}
set
{
HttpContent content = this.HttpRequestMessage.Content;
if (value && content != null &&
(!content.Headers.ContentLength.HasValue ||
content.Headers.ContentLength.Value > 0))
{
HttpContent newContent = new ByteArrayContent(Array.Empty<byte>());
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
{
newContent.Headers.AddHeaderWithoutValidation(header);
}
this.HttpRequestMessage.Content = newContent;
content.Dispose();
}
else if (!value && content == null)
{
this.HttpRequestMessage.Content = new ByteArrayContent(Array.Empty<byte>());
}
}
}
public HttpRequestMessageProperty CreateTraditionalRequestMessageProperty()
{
HttpRequestMessageProperty copiedProperty = new HttpRequestMessageProperty();
foreach (var headerKey in this.Headers.AllKeys)
{
copiedProperty.Headers[headerKey] = this.Headers[headerKey];
}
if (this.Method != TraditionalHttpRequestMessageProperty.DefaultMethod)
{
copiedProperty.Method = this.Method;
}
copiedProperty.QueryString = this.QueryString;
copiedProperty.SuppressEntityBody = this.SuppressEntityBody;
return copiedProperty;
}
public void MergeWithTraditionalProperty(TraditionalHttpRequestMessageProperty propertyToMerge)
{
if (propertyToMerge.HasMethodBeenSet)
{
this.Method = propertyToMerge.Method;
}
if (propertyToMerge.QueryString != TraditionalHttpRequestMessageProperty.DefaultQueryString)
{
this.QueryString = propertyToMerge.QueryString;
}
this.SuppressEntityBody = propertyToMerge.SuppressEntityBody;
this.HttpRequestMessage.MergeWebHeaderCollection(propertyToMerge.Headers);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CustomerInsights
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AuthorizationPoliciesOperations.
/// </summary>
public static partial class AuthorizationPoliciesOperationsExtensions
{
/// <summary>
/// Creates an authorization policy or updates an existing authorization
/// policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate authorization policy operation.
/// </param>
public static AuthorizationPolicyResourceFormat CreateOrUpdate(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName, AuthorizationPolicyResourceFormat parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, hubName, authorizationPolicyName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization policy or updates an existing authorization
/// policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate authorization policy operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AuthorizationPolicyResourceFormat> CreateOrUpdateAsync(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName, AuthorizationPolicyResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, authorizationPolicyName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an authorization policy in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
public static AuthorizationPolicyResourceFormat Get(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName)
{
return operations.GetAsync(resourceGroupName, hubName, authorizationPolicyName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an authorization policy in the hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AuthorizationPolicyResourceFormat> GetAsync(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, hubName, authorizationPolicyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the authorization policies in a specified hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
public static IPage<AuthorizationPolicyResourceFormat> ListByHub(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName)
{
return operations.ListByHubAsync(resourceGroupName, hubName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the authorization policies in a specified hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AuthorizationPolicyResourceFormat>> ListByHubAsync(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHubWithHttpMessagesAsync(resourceGroupName, hubName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the primary policy key of the specified authorization policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
public static AuthorizationPolicy RegeneratePrimaryKey(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName)
{
return operations.RegeneratePrimaryKeyAsync(resourceGroupName, hubName, authorizationPolicyName).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the primary policy key of the specified authorization policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AuthorizationPolicy> RegeneratePrimaryKeyAsync(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegeneratePrimaryKeyWithHttpMessagesAsync(resourceGroupName, hubName, authorizationPolicyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the secondary policy key of the specified authorization policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
public static AuthorizationPolicy RegenerateSecondaryKey(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName)
{
return operations.RegenerateSecondaryKeyAsync(resourceGroupName, hubName, authorizationPolicyName).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the secondary policy key of the specified authorization policy.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='hubName'>
/// The name of the hub.
/// </param>
/// <param name='authorizationPolicyName'>
/// The name of the policy.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AuthorizationPolicy> RegenerateSecondaryKeyAsync(this IAuthorizationPoliciesOperations operations, string resourceGroupName, string hubName, string authorizationPolicyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateSecondaryKeyWithHttpMessagesAsync(resourceGroupName, hubName, authorizationPolicyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the authorization policies in a specified hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<AuthorizationPolicyResourceFormat> ListByHubNext(this IAuthorizationPoliciesOperations operations, string nextPageLink)
{
return operations.ListByHubNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the authorization policies in a specified hub.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<AuthorizationPolicyResourceFormat>> ListByHubNextAsync(this IAuthorizationPoliciesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHubNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Fee
/// </summary>
[Entity(PropertiesToAlwaysSerialize = nameof(FeeType))]
public sealed partial class Fee : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<decimal?>? _amount;
private DirtyValue<decimal?>? _amountPerDay;
private DirtyValue<decimal?>? _borPaidAmount;
private DirtyValue<DateTime?>? _dateFrom;
private DirtyValue<DateTime?>? _dateTo;
private DirtyValue<int?>? _days;
private DirtyValue<decimal?>? _deedAmount;
private DirtyValue<string?>? _description;
private DirtyValue<StringEnumValue<FeeFeeType>>? _feeType;
private DirtyValue<bool?>? _fHA;
private DirtyValue<string?>? _fWBC;
private DirtyValue<string?>? _fWSC;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _includeAboveNumber;
private DirtyValue<decimal?>? _lenderCoverage;
private DirtyValue<decimal?>? _monthlyPayment;
private DirtyValue<decimal?>? _mortgageAmount;
private DirtyValue<NA<decimal>>? _newHUDBorPaidAmount;
private DirtyValue<int?>? _numberOfMonths;
private DirtyValue<decimal?>? _ownerCoverage;
private DirtyValue<StringEnumValue<PaidBy>>? _paidBy;
private DirtyValue<decimal?>? _paidInAdvance;
private DirtyValue<decimal?>? _paidToBroker;
private DirtyValue<string?>? _paidToName;
private DirtyValue<decimal?>? _paidToOthers;
private DirtyValue<decimal?>? _percentage;
private DirtyValue<bool?>? _pFC;
private DirtyValue<bool?>? _pOC;
private DirtyValue<StringEnumValue<PTB>>? _pTB;
private DirtyValue<decimal?>? _releasesAmount;
private DirtyValue<decimal?>? _sellerPaidAmount;
private DirtyValue<decimal?>? _truncatedAmountPerDay;
private DirtyValue<bool?>? _use4Decimals;
/// <summary>
/// Fee Amount
/// </summary>
public decimal? Amount { get => _amount; set => SetField(ref _amount, value); }
/// <summary>
/// Fees Interest Per Day [333]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_4)]
public decimal? AmountPerDay { get => _amountPerDay; set => SetField(ref _amountPerDay, value); }
/// <summary>
/// Fee BorPaidAmount
/// </summary>
public decimal? BorPaidAmount { get => _borPaidAmount; set => SetField(ref _borPaidAmount, value); }
/// <summary>
/// Fees Interest From [L244]
/// </summary>
public DateTime? DateFrom { get => _dateFrom; set => SetField(ref _dateFrom, value); }
/// <summary>
/// Fees Interest To [L245]
/// </summary>
public DateTime? DateTo { get => _dateTo; set => SetField(ref _dateTo, value); }
/// <summary>
/// Fees Interest # of Days [332]
/// </summary>
public int? Days { get => _days; set => SetField(ref _days, value); }
/// <summary>
/// Fee DeedAmount
/// </summary>
public decimal? DeedAmount { get => _deedAmount; set => SetField(ref _deedAmount, value); }
/// <summary>
/// Fee Description
/// </summary>
public string? Description { get => _description; set => SetField(ref _description, value); }
/// <summary>
/// Fee FeeType
/// </summary>
public StringEnumValue<FeeFeeType> FeeType { get => _feeType; set => SetField(ref _feeType, value); }
/// <summary>
/// Fee FHA
/// </summary>
public bool? FHA { get => _fHA; set => SetField(ref _fHA, value); }
/// <summary>
/// Fee FWBC
/// </summary>
public string? FWBC { get => _fWBC; set => SetField(ref _fWBC, value); }
/// <summary>
/// Fee FWSC
/// </summary>
public string? FWSC { get => _fWSC; set => SetField(ref _fWSC, value); }
/// <summary>
/// Fee Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Fee IncludeAboveNumber [1879], [1880]
/// </summary>
public string? IncludeAboveNumber { get => _includeAboveNumber; set => SetField(ref _includeAboveNumber, value); }
/// <summary>
/// Fees Line 1109 Lender's Coverage Amount [2409]
/// </summary>
public decimal? LenderCoverage { get => _lenderCoverage; set => SetField(ref _lenderCoverage, value); }
/// <summary>
/// Fee MonthlyPayment
/// </summary>
public decimal? MonthlyPayment { get => _monthlyPayment; set => SetField(ref _monthlyPayment, value); }
/// <summary>
/// Fee MortgageAmount
/// </summary>
public decimal? MortgageAmount { get => _mortgageAmount; set => SetField(ref _mortgageAmount, value); }
/// <summary>
/// Fee NewHUDBorPaidAmount [NEWHUD.X571], [NEWHUD.X572]
/// </summary>
public NA<decimal> NewHUDBorPaidAmount { get => _newHUDBorPaidAmount; set => SetField(ref _newHUDBorPaidAmount, value); }
/// <summary>
/// Fee NumberOfMonths
/// </summary>
public int? NumberOfMonths { get => _numberOfMonths; set => SetField(ref _numberOfMonths, value); }
/// <summary>
/// Fees Line 1110 Owner's Coverage Amount [2410]
/// </summary>
public decimal? OwnerCoverage { get => _ownerCoverage; set => SetField(ref _ownerCoverage, value); }
/// <summary>
/// Fee PaidBy
/// </summary>
public StringEnumValue<PaidBy> PaidBy { get => _paidBy; set => SetField(ref _paidBy, value); }
/// <summary>
/// Fee PaidInAdvance
/// </summary>
public decimal? PaidInAdvance { get => _paidInAdvance; set => SetField(ref _paidInAdvance, value); }
/// <summary>
/// Fee PaidToBroker
/// </summary>
public decimal? PaidToBroker { get => _paidToBroker; set => SetField(ref _paidToBroker, value); }
/// <summary>
/// Fee PaidToName
/// </summary>
public string? PaidToName { get => _paidToName; set => SetField(ref _paidToName, value); }
/// <summary>
/// Fee PaidToOthers
/// </summary>
public decimal? PaidToOthers { get => _paidToOthers; set => SetField(ref _paidToOthers, value); }
/// <summary>
/// Fee Percentage
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? Percentage { get => _percentage; set => SetField(ref _percentage, value); }
/// <summary>
/// Fee PFC
/// </summary>
public bool? PFC { get => _pFC; set => SetField(ref _pFC, value); }
/// <summary>
/// Fee POC
/// </summary>
public bool? POC { get => _pOC; set => SetField(ref _pOC, value); }
/// <summary>
/// Fee PTB
/// </summary>
public StringEnumValue<PTB> PTB { get => _pTB; set => SetField(ref _pTB, value); }
/// <summary>
/// Fees Recording Fee Releases Amount [2404]
/// </summary>
public decimal? ReleasesAmount { get => _releasesAmount; set => SetField(ref _releasesAmount, value); }
/// <summary>
/// Fee SellerPaidAmount
/// </summary>
public decimal? SellerPaidAmount { get => _sellerPaidAmount; set => SetField(ref _sellerPaidAmount, value); }
/// <summary>
/// Unrounded and Truncated Fees Interest Per Day [335]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TruncatedAmountPerDay { get => _truncatedAmountPerDay; set => SetField(ref _truncatedAmountPerDay, value); }
/// <summary>
/// Number of Decimals for Fees Interest # of Days [SYS.X8]
/// </summary>
public bool? Use4Decimals { get => _use4Decimals; set => SetField(ref _use4Decimals, 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.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace System.Net.Sockets
{
// The System.Net.Sockets.UdpClient class provides access to UDP services at a higher abstraction
// level than the System.Net.Sockets.Socket class. System.Net.Sockets.UdpClient is used to
// connect to a remote host and to receive connections from a remote client.
public class UdpClient : IDisposable
{
private const int MaxUDPSize = 0x10000;
private Socket _clientSocket;
private bool _active;
private byte[] _buffer = new byte[MaxUDPSize];
private AddressFamily _family = AddressFamily.InterNetwork;
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient(AddressFamily family)
{
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), "family");
}
_family = family;
CreateClientSocket();
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
//
// NOTE: We should obsolete this. This also breaks IPv6-only scenarios.
// But fixing it has many complications that we have decided not
// to fix it and instead obsolete it later.
public UdpClient(int port) : this(port, AddressFamily.InterNetwork)
{
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
public UdpClient(int port, AddressFamily family)
{
// Validate input parameters.
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.net_protocol_invalid_family, "family");
}
IPEndPoint localEP;
_family = family;
if (_family == AddressFamily.InterNetwork)
{
localEP = new IPEndPoint(IPAddress.Any, port);
}
else
{
localEP = new IPEndPoint(IPAddress.IPv6Any, port);
}
CreateClientSocket();
Client.Bind(localEP);
}
// Creates a new instance of the UdpClient class that communicates on the
// specified end point.
public UdpClient(IPEndPoint localEP)
{
// Validate input parameters.
if (localEP == null)
{
throw new ArgumentNullException("localEP");
}
// IPv6 Changes: Set the AddressFamily of this object before
// creating the client socket.
_family = localEP.AddressFamily;
CreateClientSocket();
Client.Bind(localEP);
}
// Used by the class to provide the underlying network socket.
public Socket Client
{
get
{
return _clientSocket;
}
set
{
_clientSocket = value;
}
}
// Used by the class to indicate that a connection to a remote host has been made.
protected bool Active
{
get
{
return _active;
}
set
{
_active = value;
}
}
public int Available
{
get
{
return _clientSocket.Available;
}
}
public short Ttl
{
get
{
return _clientSocket.Ttl;
}
set
{
_clientSocket.Ttl = value;
}
}
public bool DontFragment
{
get
{
return _clientSocket.DontFragment;
}
set
{
_clientSocket.DontFragment = value;
}
}
public bool MulticastLoopback
{
get
{
return _clientSocket.MulticastLoopback;
}
set
{
_clientSocket.MulticastLoopback = value;
}
}
public bool EnableBroadcast
{
get
{
return _clientSocket.EnableBroadcast;
}
set
{
_clientSocket.EnableBroadcast = value;
}
}
public bool ExclusiveAddressUse
{
get
{
return _clientSocket.ExclusiveAddressUse;
}
set
{
_clientSocket.ExclusiveAddressUse = value;
}
}
private bool _cleanedUp = false;
private void FreeResources()
{
// The only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
// to flush the data to the network, close the stream and (in the
// NetoworkStream code) close the socket as well.
if (_cleanedUp)
{
return;
}
Socket chkClientSocket = Client;
if (chkClientSocket != null)
{
// If the NetworkStream wasn't retrieved, the Socket might
// still be there and needs to be closed to release the effect
// of the Bind() call and free the bound IPEndPoint.
chkClientSocket.InternalShutdown(SocketShutdown.Both);
chkClientSocket.Dispose();
Client = null;
}
_cleanedUp = true;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
GlobalLog.Print("UdpClient::Dispose()");
FreeResources();
GC.SuppressFinalize(this);
}
}
private bool _isBroadcast;
private void CheckForBroadcast(IPAddress ipAddress)
{
// Here we check to see if the user is trying to use a Broadcast IP address
// we only detect IPAddress.Broadcast (which is not the only Broadcast address)
// and in that case we set SocketOptionName.Broadcast on the socket to allow its use.
// if the user really wants complete control over Broadcast addresses he needs to
// inherit from UdpClient and gain control over the Socket and do whatever is appropriate.
if (Client != null && !_isBroadcast && IsBroadcast(ipAddress))
{
// We need to set the Broadcast socket option.
// Note that once we set the option on the Socket we never reset it.
_isBroadcast = true;
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
}
private bool IsBroadcast(IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// No such thing as a broadcast address for IPv6.
return false;
}
else
{
return address.Equals(IPAddress.Broadcast);
}
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (datagram == null)
{
throw new ArgumentNullException("datagram");
}
if (bytes > datagram.Length || bytes < 0)
{
throw new ArgumentOutOfRangeException("bytes");
}
if (_active && endPoint != null)
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
if (endPoint == null)
{
return Client.BeginSend(datagram, 0, bytes, SocketFlags.None, requestCallback, state);
}
CheckForBroadcast(endPoint.Address);
return Client.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state);
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
{
if (_active && ((hostname != null) || (port != 0)))
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
IPEndPoint ipEndPoint = null;
if (hostname != null && port != 0)
{
IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult();
int i = 0;
for (; i < addresses.Length && addresses[i].AddressFamily != _family; i++)
{
}
if (addresses.Length == 0 || i == addresses.Length)
{
throw new ArgumentException(SR.net_invalidAddressList, "hostname");
}
CheckForBroadcast(addresses[i]);
ipEndPoint = new IPEndPoint(addresses[i], port);
}
return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state);
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
{
return BeginSend(datagram, bytes, null, requestCallback, state);
}
internal int EndSend(IAsyncResult asyncResult)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_active)
{
return Client.EndSend(asyncResult);
}
else
{
return Client.EndSendTo(asyncResult);
}
}
internal IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Due to the nature of the ReceiveFrom() call and the ref parameter convention,
// we need to cast an IPEndPoint to its base class EndPoint and cast it back down
// to IPEndPoint.
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
return Client.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
}
internal byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
int received = Client.EndReceiveFrom(asyncResult, ref tempRemoteEP);
remoteEP = (IPEndPoint)tempRemoteEP;
// Because we don't return the actual length, we need to ensure the returned buffer
// has the appropriate length.
if (received < MaxUDPSize)
{
byte[] newBuffer = new byte[received];
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, received);
return newBuffer;
}
return _buffer;
}
// Joins a multicast address group.
public void JoinMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
}
public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_family != AddressFamily.InterNetwork)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins an IPv6 multicast address group.
public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins a multicast address group with the specified time to live (TTL).
public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive)
{
// parameter validation;
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255))
{
throw new ArgumentOutOfRangeException("timeToLive");
}
// Join the Multicast Group.
JoinMulticastGroup(multicastAddr);
// Set Time To Live (TTL).
Client.SetSocketOption(
(_family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6,
SocketOptionName.MulticastTimeToLive,
timeToLive);
}
// Leaves a multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.DropMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
}
// Leaves an IPv6 multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr, int ifindex)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
public Task<int> SendAsync(byte[] datagram, int bytes)
{
return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, null);
}
public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint)
{
return Task<int>.Factory.FromAsync(BeginSend, EndSend, datagram, bytes, endPoint, null);
}
public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port)
{
return Task<int>.Factory.FromAsync((callback, state) => BeginSend(datagram, bytes, hostname, port, callback, state), EndSend, null);
}
public Task<UdpReceiveResult> ReceiveAsync()
{
return Task<UdpReceiveResult>.Factory.FromAsync((callback, state) => BeginReceive(callback, state), (ar) =>
{
IPEndPoint remoteEP = null;
Byte[] buffer = EndReceive(ar, ref remoteEP);
return new UdpReceiveResult(buffer, remoteEP);
}, null);
}
private void CreateClientSocket()
{
// Common initialization code.
//
// IPv6 Changes: Use the AddressFamily of this class rather than hardcode.
Client = new Socket(_family, SocketType.Dgram, ProtocolType.Udp);
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 374175 $
* $LastChangedDate: 2006-04-30 18:01:40 +0200 (dim., 30 avr. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace IBatisNet.Common.Utilities.Objects.Members
{
/// <summary>
/// The <see cref="EmitFieldSetAccessor"/> class provides an IL-based set access
/// to a field of a specified target class.
/// </summary>
/// <remarks>Will Throw FieldAccessException on private field</remarks>
public sealed class EmitFieldSetAccessor : BaseAccessor, ISetAccessor
{
private const BindingFlags VISIBILITY = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
/// <summary>
/// The field name
/// </summary>
private string _fieldName = string.Empty;
/// <summary>
/// The class parent type
/// </summary>
private Type _fieldType = null;
/// <summary>
/// The IL emitted ISet
/// </summary>
private ISet _emittedSet = null;
private Type _targetType = null;
/// <summary>
/// Initializes a new instance of the <see cref="EmitFieldGetAccessor"/> class.
/// </summary>
/// <param name="targetObjectType">Type of the target object.</param>
/// <param name="fieldName">Name of the field.</param>
/// <param name="assemblyBuilder">The assembly builder.</param>
/// <param name="moduleBuilder">The module builder.</param>
public EmitFieldSetAccessor(Type targetObjectType, string fieldName, AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder)
{
_targetType = targetObjectType;
_fieldName = fieldName;
FieldInfo fieldInfo = _targetType.GetField(fieldName, VISIBILITY);
// Make sure the field exists
if (fieldInfo == null)
{
throw new NotSupportedException(
string.Format("Field \"{0}\" does not exist for type "
+ "{1}.", fieldName, targetObjectType));
}
else
{
_fieldType = fieldInfo.FieldType;
this.EmitIL(assemblyBuilder, moduleBuilder);
}
}
/// <summary>
/// This method create a new type oject for the the property accessor class
/// that will provide dynamic access.
/// </summary>
/// <param name="assemblyBuilder">The assembly builder.</param>
/// <param name="moduleBuilder">The module builder.</param>
private void EmitIL(AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder)
{
// Create a new type object for the the field accessor class.
EmitType(moduleBuilder);
// Create a new instance
_emittedSet = assemblyBuilder.CreateInstance("SetFor" + _targetType.FullName + _fieldName) as ISet;
this.nullInternal = this.GetNullInternal(_fieldType);
if (_emittedSet == null)
{
throw new NotSupportedException(
string.Format("Unable to create a set field accessor for '{0}' field on class '{0}'.", _fieldName, _fieldType));
}
}
/// <summary>
/// Create an type that will provide the set access method.
/// </summary>
/// <remarks>
/// new ReflectionPermission(PermissionState.Unrestricted).Assert();
/// CodeAccessPermission.RevertAssert();
/// </remarks>
/// <param name="moduleBuilder">The module builder.</param>
private void EmitType(ModuleBuilder moduleBuilder)
{
// Define a public class named "SetFor.FullTargetTypeName.FieldName" in the assembly.
TypeBuilder typeBuilder = moduleBuilder.DefineType("SetFor" + _targetType.FullName + _fieldName, TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed);
// Mark the class as implementing ISet.
typeBuilder.AddInterfaceImplementation(typeof(ISet));
// Add a constructor
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
#region Emit Set
// Define a method named "Set" for the set operation (IMemberAccessor).
Type[] setParamTypes = new Type[] { typeof(object), typeof(object) };
MethodBuilder setMethod = typeBuilder.DefineMethod("Set",
MethodAttributes.Public | MethodAttributes.Virtual,
null,
setParamTypes);
// Get an ILGenerator and used to emit the IL that we want.
ILGenerator setIL = setMethod.GetILGenerator();
FieldInfo targetField = _targetType.GetField(_fieldName, VISIBILITY);
// Emit the IL for the set access.
if (targetField != null)
{
setIL.Emit(OpCodes.Ldarg_1);//Load the first argument (target object)
setIL.Emit(OpCodes.Castclass, _targetType); //Cast to the source type
setIL.Emit(OpCodes.Ldarg_2);//Load the second argument (value object)
if (_fieldType.IsValueType)
{
setIL.Emit(OpCodes.Unbox, _fieldType); //Unbox it
if (typeToOpcode[_fieldType] != null)
{
OpCode load = (OpCode)typeToOpcode[_fieldType];
setIL.Emit(load); //and load
}
else
{
setIL.Emit(OpCodes.Ldobj, _fieldType);
}
setIL.Emit(OpCodes.Stfld, targetField); //Set the field value
}
else
{
// setIL.Emit(OpCodes.Castclass, _fieldType); //Cast class
setIL.Emit(OpCodes.Stfld, targetField);
}
}
else
{
setIL.ThrowException(typeof(MissingMethodException));
}
setIL.Emit(OpCodes.Ret);
#endregion
// Load the type
typeBuilder.CreateType();
}
#region IAccessor Members
/// <summary>
/// Gets the field's name.
/// </summary>
/// <value></value>
public string Name
{
get { return _fieldName; }
}
/// <summary>
/// Gets the field's type.
/// </summary>
/// <value></value>
public Type MemberType
{
get { return _fieldType; }
}
#endregion
#region ISet Members
/// <summary>
/// Sets the field for the specified target.
/// </summary>
/// <param name="target">Target object.</param>
/// <param name="value">Value to set.</param>
public void Set(object target, object value)
{
object newValue = value;
if (newValue == null)
{
// If the value to assign is null, assign null internal value
newValue = nullInternal;
}
_emittedSet.Set(target, newValue);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace QText {
internal class TabFile : TabPage {
public TabFile(DocumentFile file)
: base() {
BaseFile = file;
Padding = new Padding(0, SystemInformation.Border3DSize.Height, 0, 0);
base.Text = Title;
GotFocus += txt_GotFocus;
if (Settings.Current.FilesPreload && (BaseFile.IsEncrypted == false)) {
Open();
}
}
private void AddTextBox(RichTextBoxEx txt) {
if (TextBox != null) { throw new InvalidOperationException("TextBox already exists"); }
TextBox = txt;
TextBox.ContextMenuStrip = ContextMenuStrip;
TextBox.Enter += txt_GotFocus;
TextBox.TextChanged += txt_TextChanged;
TextBox.PreviewKeyDown += txt_PreviewKeyDown;
base.Controls.Add(TextBox);
}
private static RichTextBoxEx GetEmptyTextBox() {
var tb = new RichTextBoxEx {
AcceptsTab = true,
BackColor = Settings.Current.DisplayBackgroundColor,
Dock = DockStyle.Fill,
Font = Settings.Current.DisplayFont,
ForeColor = Settings.Current.DisplayForegroundColor,
HideSelection = false,
MaxLength = 0,
Multiline = true,
ShortcutsEnabled = false,
DetectUrls = Settings.Current.DetectUrls
};
switch (Settings.Current.ScrollBars) {
case ScrollBars.None:
tb.ScrollBars = RichTextBoxScrollBars.None;
break;
case ScrollBars.Horizontal:
tb.ScrollBars = RichTextBoxScrollBars.ForcedHorizontal;
break;
case ScrollBars.Vertical:
tb.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
break;
case ScrollBars.Both:
tb.ScrollBars = RichTextBoxScrollBars.ForcedBoth;
break;
}
tb.WordWrap = Settings.Current.DisplayWordWrap;
return tb;
}
private static readonly UTF8Encoding Utf8EncodingWithoutBom = new UTF8Encoding(false);
public DocumentFile BaseFile { get; private set; }
public string Title { get { return BaseFile.Title; } }
public bool IsOpened { get; private set; }
private bool _isChanged;
public bool IsChanged {
get {
return _isChanged && IsOpened; //only open file can be changed
}
private set {
_isChanged = value;
UpdateText();
}
}
public RichTextBoxEx TextBox { get; private set; }
private ContextMenuStrip _contextMenuStrip;
public override ContextMenuStrip ContextMenuStrip {
get { return _contextMenuStrip; }
set {
_contextMenuStrip = value;
if (TextBox != null) {
TextBox.ContextMenuStrip = value;
}
}
}
public static TabFile Create(DocumentFolder folder, string title, DocumentKind kind) {
var newFile = folder.NewFile(title, kind);
if (kind == DocumentKind.RichText) {
using (var dummy = new RichTextBox()) {
dummy.BackColor = Settings.Current.DisplayBackgroundColor;
dummy.Font = Settings.Current.DisplayFont;
dummy.ForeColor = Settings.Current.DisplayForegroundColor;
using (var stream = new MemoryStream()) {
dummy.SaveFile(stream, RichTextBoxStreamType.RichText);
newFile.Write(stream);
}
}
}
return new TabFile(newFile);
}
public void Open() {
Reopen();
}
public void Close() {
if (IsOpened) {
if (TextBox != null) {
Controls.Remove(TextBox);
TextBox = null;
}
BaseFile.Password = null;
IsOpened = false;
}
}
public void ConvertToPlainText() {
if (IsOpened == false) { throw new InvalidOperationException("File is not loaded."); }
if (BaseFile.IsPlainText) { throw new InvalidOperationException("File is already in plain text format."); }
SaveAsPlain();
BaseFile.ChangeStyle(DocumentStyle.PlainText);
Reopen();
}
public void ConvertToRichText() {
if (IsOpened == false) { throw new InvalidOperationException("File is not loaded."); }
if (BaseFile.IsRichText) { throw new InvalidOperationException("File is already in rich text format."); }
_ = TextBox.Text;
BaseFile.ChangeStyle(DocumentStyle.RichText);
SaveAsRich();
Reopen();
}
public void Encrypt(string password) {
if (IsOpened == false) { throw new InvalidOperationException("File is not loaded."); }
if (BaseFile.IsEncrypted) { throw new InvalidOperationException("File is already encrypted."); }
_ = TextBox.Text;
BaseFile.Encrypt(password);
Reopen();
}
public void Decrypt() {
if (IsOpened == false) { throw new InvalidOperationException("File is not loaded."); }
if (BaseFile.IsEncrypted == false) { throw new InvalidOperationException("File is already decrypted."); }
if (!BaseFile.HasPassword) { throw new InvalidOperationException("No decryption password found."); }
_ = TextBox.Text;
BaseFile.Decrypt();
Save();
Reopen();
}
public void Reopen() {
if (BaseFile.IsEncrypted && !BaseFile.HasPassword) { throw new InvalidOperationException("No password provided."); }
try {
var txt = TextBox ?? GetEmptyTextBox();
var oldSelStart = txt.SelectionStart;
var oldSelLength = txt.SelectionLength;
IsOpened = false;
if (BaseFile.IsRichText) {
try {
OpenAsRich(txt);
} catch (ArgumentException) {
OpenAsPlain(txt);
}
} else {
OpenAsPlain(txt);
}
if (TextBox == null) { AddTextBox(txt); }
UpdateTabWidth();
TextBox.SelectionStart = oldSelStart;
TextBox.SelectionLength = oldSelLength;
TextBox.ClearUndo();
IsChanged = false;
IsOpened = true;
} catch (Exception ex) {
throw new InvalidOperationException(ex.Message, ex);
}
}
public void QuickSaveWithoutException() {
try {
Save();
} catch (Exception) { }
}
private int QuickSaveFailedCounter;
public void QuickSave() { //allow for three failed attempts
try {
Save();
QuickSaveFailedCounter = 0;
} catch (Exception) {
QuickSaveFailedCounter += 1;
if (QuickSaveFailedCounter == 4) {
throw;
}
}
}
public void Save() {
if (IsOpened == false) { return; }
if (BaseFile.IsRichText) {
SaveAsRich();
} else {
SaveAsPlain();
}
IsChanged = false;
base.Text = Title;
}
public void Rename(string newTitle) {
if (newTitle == null) { throw new ArgumentNullException("newTitle", "Title cannot be null."); }
BaseFile.Rename(newTitle);
UpdateText();
}
#region txt
private void txt_GotFocus(object sender, EventArgs e) {
if (TextBox != null) {
TextBox.Select();
}
}
private void txt_TextChanged(object sender, EventArgs e) {
if (IsOpened && (IsChanged == false)) {
IsChanged = true;
}
}
private void txt_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
Debug.WriteLine("TabFile.PreviewKeyDown: " + e.KeyData.ToString());
switch (e.KeyData) {
case Keys.Control | Keys.X:
Cut(QText.Settings.Current.ForceTextCopyPaste);
e.IsInputKey = false;
break;
case Keys.Control | Keys.C:
Copy(QText.Settings.Current.ForceTextCopyPaste);
e.IsInputKey = false;
break;
case Keys.Control | Keys.V:
Paste(QText.Settings.Current.ForceTextCopyPaste);
e.IsInputKey = false;
break;
case Keys.Control | Keys.Shift | Keys.X:
case Keys.Shift | Keys.Delete:
Cut(true);
e.IsInputKey = false;
break;
case Keys.Control | Keys.Shift | Keys.C:
case Keys.Control | Keys.Insert:
Copy(true);
e.IsInputKey = false;
break;
case Keys.Control | Keys.Shift | Keys.V:
case Keys.Shift | Keys.Insert:
Paste(true);
e.IsInputKey = false;
break;
case Keys.Control | Keys.Z:
Undo();
e.IsInputKey = false;
break;
case Keys.Control | Keys.Y:
Redo();
e.IsInputKey = false;
break;
case Keys.X:
e.IsInputKey = false;
break;
case Keys.Control | Keys.A:
TextBox.SelectAll();
e.IsInputKey = false;
break;
}
}
#endregion
#region Cut/Copy/Paste/Undo/Redo
public bool CanCut {
get { return (TextBox != null) && (TextBox.SelectionLength > 0); }
}
public void Cut(bool forceText) {
try {
if (CanCopy) {
if (BaseFile.IsPlainText || forceText) {
CopyTextToClipboard(TextBox);
TextBox.SelectedText = "";
} else {
TextBox.Cut();
}
}
} catch (ExternalException) {
}
}
public bool CanCopy {
get { return (TextBox != null) && !TextBox.IsSelectionEmpty; }
}
public void Copy(bool forceText) {
try {
if (CanCopy) {
if (BaseFile.IsPlainText || forceText) {
CopyTextToClipboard(TextBox);
} else {
TextBox.Copy();
}
}
} catch (ExternalException) { }
}
public bool CanPaste(bool forceText = false) {
try {
if (TextBox != null) {
if (BaseFile.IsRichText) {
if (Settings.Current.UnrestrictedRichTextClipboard) {
return TextBox.CanPaste(DataFormats.GetFormat(DataFormats.UnicodeText))
|| TextBox.CanPaste(DataFormats.GetFormat(DataFormats.Text))
|| (TextBox.CanPaste(DataFormats.GetFormat(DataFormats.Rtf)) && !forceText)
|| (TextBox.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)) && !forceText)
|| (TextBox.CanPaste(DataFormats.GetFormat(DataFormats.EnhancedMetafile)) && !forceText);
} else {
return Clipboard.ContainsText(TextDataFormat.UnicodeText) || Clipboard.ContainsText(TextDataFormat.Text);
}
} else {
return Clipboard.ContainsText(TextDataFormat.UnicodeText) || Clipboard.ContainsText(TextDataFormat.Text);
}
}
} catch (ExternalException) { }
return false;
}
public void Paste(bool forceText) {
try {
if (CanPaste(forceText)) {
if (BaseFile.IsPlainText || forceText) {
var text = GetTextFromClipboard();
if (text != null) {
TextBox.SelectionFont = Settings.Current.DisplayFont;
TextBox.SelectedText = text;
}
} else {
var text = GetRichTextFromClipboard(out var isRich);
if (text != null) {
if (isRich) {
TextBox.SelectedRtf = text;
} else {
TextBox.SelectedText = text;
}
} else if (Settings.Current.UnrestrictedRichTextClipboard) { //maybe an image
TextBox.Paste(); //just do raw paste
}
}
}
} catch (ExternalException) { }
}
public bool CanUndo {
get { return (TextBox != null) && TextBox.CanUndo; }
}
public void Undo() {
if (CanUndo) {
TextBox.Undo();
}
}
public bool CanRedo {
get { return (TextBox != null) && TextBox.CanRedo; }
}
public void Redo() {
if (CanRedo) {
TextBox.Redo();
}
}
#endregion
#region Font
public bool IsTextBold {
get { return (TextBox != null) && (TextBox.SelectionFont != null) && (TextBox.SelectionFont.Bold); }
}
public bool IsTextItalic {
get { return (TextBox != null) && (TextBox.SelectionFont != null) && (TextBox.SelectionFont.Italic); }
}
public bool IsTextUnderline {
get { return (TextBox != null) && (TextBox.SelectionFont != null) && (TextBox.SelectionFont.Underline); }
}
public bool IsTextStrikeout {
get { return (TextBox != null) && (TextBox.SelectionFont != null) && (TextBox.SelectionFont.Strikeout); }
}
public bool IsTextBulleted {
get { return (TextBox != null) && TextBox.SelectionBullet; }
}
public bool IsTextNumbered {
get { return (TextBox != null) && TextBox.SelectionNumbered; }
}
#endregion
#region Search
public bool Find(string text, bool caseSensitive) {
StringComparison comparisionType;
if (caseSensitive) {
comparisionType = StringComparison.CurrentCulture;
} else {
comparisionType = StringComparison.CurrentCultureIgnoreCase;
}
if (!(IsOpened)) {
if (BaseFile.NeedsPassword && !BaseFile.HasPassword) { return false; }
Open();
}
var index = TextBox.Text.IndexOf(text, TextBox.SelectionStart + TextBox.SelectionLength, comparisionType);
if ((index < 0) && (TextBox.SelectionStart + TextBox.SelectionLength > 0)) {
index = TextBox.Text.IndexOf(text, 0, comparisionType);
}
if (index >= 0) {
TextBox.SelectionStart = index;
TextBox.SelectionLength = text.Length;
return true;
} else {
return false;
}
}
public bool FindForward(string text, bool caseSensitive, int startingIndex) {
StringComparison comparisionType;
if (caseSensitive) {
comparisionType = StringComparison.CurrentCulture;
} else {
comparisionType = StringComparison.CurrentCultureIgnoreCase;
}
if (!(IsOpened)) {
if (BaseFile.NeedsPassword && !BaseFile.HasPassword) { return false; }
Open();
}
var index = TextBox.Text.IndexOf(text, startingIndex, comparisionType);
if ((index >= 0) && (index < int.MaxValue)) {
TextBox.SelectionStart = index;
TextBox.SelectionLength = text.Length;
return true;
} else {
return false;
}
}
public Rectangle GetSelectedRectangle() {
var pt1 = TextBox.PointToScreen(TextBox.GetPositionFromCharIndex(TextBox.SelectionStart));
var ptEnd = TextBox.PointToScreen(TextBox.GetPositionFromCharIndex(TextBox.SelectionStart + TextBox.SelectionLength));
var pt2 = default(Point);
using (var g = TextBox.CreateGraphics()) {
if ((TextBox != null) && (TextBox.SelectionFont != null)) {
pt2 = new Point(ptEnd.X, ptEnd.Y + g.MeasureString("XXX", TextBox.SelectionFont).ToSize().Height);
} else {
pt2 = new Point(ptEnd.X, ptEnd.Y + g.MeasureString("XXX", TextBox.Font).ToSize().Height);
}
}
var thisRectangle = RectangleToScreen(Bounds);
var left = Math.Max(Math.Min(pt1.X, pt2.X), thisRectangle.Left) - 32;
var top = Math.Max(Math.Min(pt1.Y, pt2.Y), thisRectangle.Top) - 32;
var right = Math.Min(Math.Max(pt1.X, pt2.X), thisRectangle.Right) + 32;
var bottom = Math.Min(Math.Max(pt1.Y, pt2.Y), thisRectangle.Bottom) + 32;
return new Rectangle(left, top, right - left, bottom - top);
}
#endregion
public void UpdateTabWidth() {
if (TextBox == null) { return; }
var dotWidth = TextRenderer.MeasureText(".", Settings.Current.DisplayFont, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding).Width;
var dotXWidth = TextRenderer.MeasureText("X.", Settings.Current.DisplayFont, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding).Width;
var charWidth = dotXWidth - dotWidth;
var tabs2 = new List<int>();
for (var i = 1; i <= 32; i++) { tabs2.Add((i * charWidth) * Settings.Current.DisplayTabWidth); }
var ss = TextBox.SelectionStart;
var sl = TextBox.SelectionLength;
TextBox.SelectAll();
TextBox.SelectionTabs = tabs2.ToArray();
TextBox.SelectionStart = TextBox.TextLength;
TextBox.SelectionLength = 0;
TextBox.SelectionTabs = tabs2.ToArray();
TextBox.SelectionStart = ss;
TextBox.SelectionLength = sl;
TextBox.Refresh();
}
private void UpdateText() {
base.Text = IsChanged ? Title + "*" : Title;
}
public override string ToString() {
return Title;
}
#region Open/Save
private void OpenAsPlain(RichTextBoxEx txt) {
using (var stream = new MemoryStream()) {
BaseFile.Read(stream);
using (var sr = new StreamReader(stream, Utf8EncodingWithoutBom)) {
var text = sr.ReadToEnd();
var lines = text.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
txt.ResetText();
txt.Text = string.Join("\n", lines);
}
}
}
private void SaveAsPlain() {
using (var stream = new MemoryStream()) {
var text = string.Join(Settings.Current.PlainLineEndsWithLf ? "\n" : Environment.NewLine, TextBox.Lines);
var bytes = Utf8EncodingWithoutBom.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
BaseFile.Write(stream);
}
}
private void OpenAsRich(RichTextBoxEx txt) {
using (var stream = new MemoryStream()) {
BaseFile.Read(stream);
txt.LoadFile(stream, RichTextBoxStreamType.RichText);
}
}
private void SaveAsRich() {
using (var stream = new MemoryStream()) {
TextBox.SaveFile(stream, RichTextBoxStreamType.RichText);
BaseFile.Write(stream);
}
}
private static void CopyTextToClipboard(RichTextBoxEx textBox) {
var text = textBox.SelectedText.Replace("\n", Environment.NewLine);
var data = new DataObject();
data.SetText(text, TextDataFormat.Text);
data.SetText(text, TextDataFormat.UnicodeText);
Clipboard.SetDataObject(data, copy: true, 5, 100);
}
private static string GetTextFromClipboard() {
if (Clipboard.ContainsText(TextDataFormat.UnicodeText)) {
return Clipboard.GetText(TextDataFormat.UnicodeText);
} else if (Clipboard.ContainsText(TextDataFormat.Text)) {
return Clipboard.GetText(TextDataFormat.Text);
}
return null;
}
private static string GetRichTextFromClipboard(out bool isRich) {
if (Clipboard.ContainsText(TextDataFormat.Rtf)) {
isRich = true;
var richText = Clipboard.GetText(TextDataFormat.Rtf);
return Helper.FilterRichText(richText) ?? GetTextFromClipboard();
} else if (Clipboard.ContainsText(TextDataFormat.UnicodeText)) {
isRich = false;
return Clipboard.GetText(TextDataFormat.UnicodeText);
} else if (Clipboard.ContainsText(TextDataFormat.Text)) {
isRich = false;
return Clipboard.GetText(TextDataFormat.Text);
}
isRich = false;
return null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace BraveHaxvius.Data
{
public class Variable
{
public static readonly String Encrypted = "t7n6cVWf";
public static readonly String UserId = "9Tbns0eI";
public static readonly String UserName = "9qh17ZUf";
public static readonly String Password = "JC61TPqS";
public static readonly String OperatingSystem = "io30YcLA";
public static readonly String CountryCode = "Y76dKryw";
public static readonly String ContactId = "e8Si6TGh";
public static readonly String PurchaseSignature = "K1G4fBjF";
public static readonly String BuildVersion = "1WKh6Xqe";
public static readonly String Time = "64anJRhx";
public static readonly String FriendId = "m3Wghr1j";
public static readonly String NotFriendId = "w40YsHIz";
public static readonly String ModelChangeCnt = "6Nf5risL";
public static readonly String MacroToolRunningStatus = "ma6Ac53v";
public static readonly String Ymd = "D2I1Vtog";
public static readonly String AppVersion = "9K0Pzcpd";
public static readonly String GumiId = "mESKDlqL";
public static readonly String GumiToken = "iVN1HD3p";
public static readonly String TransferCode = "c52MWCji";
public static readonly String TransferPin = "D3fzIL1s";
public static readonly String DateCreatedShort = "F0bCxp5m";
public static readonly String DateCreated = "Tx6MGkJ1";
public static readonly String DateLinked = "XBZ40ms5";
public static readonly String Time0 = "3ES8GAu4";
public static readonly String DeviceId = "6e4ik6kA";
public static readonly String AdvertisingId = "NggnPgQC";
public static readonly String FacebookUserId = "X6jT6zrQ";
public static readonly String FacebookToken = "DOFV3qRF";
public static readonly String UsingFacebook = "K2jzG6bp";
public static readonly String Data = "qrVcDe48";
public static readonly String Level = "7wV3QZ80";
public static readonly String Experience = "B6H34Mea";
public static readonly String Energy = "B6kyCQ9M";
public static readonly String EnergyTimer = "n4LtSU7G";
public static readonly String EnergyMax = "m0bD2zwU";
public static readonly String ColosseumOrb = "xDm19iGS";
public static readonly String ColosseumOrbTimer = "4ywDFuU9";
public static readonly String ColosseumOrbMax = "zo76TkaG";
public static readonly String RaidOrb = "Ddsg1be4";
public static readonly String RaidOrbTimer = "nhdY37pu";
public static readonly String RaidOrbMax = "Le8Z5cS0";
public static readonly String ExtraUnits = "T1Lm7WdD";
public static readonly String ExtraFriends = "tsT4vP7w";
public static readonly String ExtraEquipment = "Xu7L1dNM";
public static readonly String ExtraItems = "4BI0WKjQ";
public static readonly String ExtraMaterials = "9w3Pi6XJ";
public static readonly String ExtraMateria = "92LoiU76";
public static readonly String LastLoginYMD = "3TzVX8nZ";
public static readonly String SerialLogin = "68Vn2FrK";
public static readonly String Gil = "7UR4J2SE";
public static readonly String FriendPoints = "0XUs3Tv6";
public static readonly String Gift = "Utx8P1Qo";
public static readonly String Message = "Wk1v6upb";
public static readonly String KeyName = "a4hXTIm0";
public static readonly String Value = "wM9AfX6I";
public static readonly String UniqueUnitId = "og2GHy49";
public static readonly String UnitId = "3HriTp6B";
public static readonly String LastAccessBase = "Z06cK4Qi";
public static readonly String Rarity = "9fW0TePj";
public static readonly String GenderId = "UbSL8C7i";
public static readonly String JobId = "IWv3u1xX";
public static readonly String TribeId = "a9qg8vnP";
public static readonly String GameId = "taQ69cIx";
public static readonly String BaseUnitId = "woghJa61";
public static readonly String UnitMaxLevel = "aU3o2D4t";
public static readonly String EquipIds = "yY7U9TsP";
public static readonly String IsCombatUnit = "wSB84Usi";
public static readonly String IsPotUnit = "2odVXyT8";
public static readonly String IsSummonable = "Fzmtn2Q5";
public static readonly String MateriaSlots = "19ykfMgL";
public static readonly String UnitSellPrice = "FBjo93gK";
public static readonly String UnitSellIds = "S5Ib7En1";
public static readonly String UnitLvl = "10fNKueF";
public static readonly String UnitHp = "em5hx4FX";
public static readonly String UnitMp = "L0MX7edB";
public static readonly String UnitAtk = "o7Ynu1XP";
public static readonly String UnitDef = "6tyb58Kc";
public static readonly String UnitMag = "Y9H6TWnv";
public static readonly String UnitSpr = "sa8Ewx3H";
public static readonly String UnitLb = "EXf5G3Mk";
public static readonly String UnitLbLvl = "a71oxzCH";
public static readonly String UnitTmr = "f17L8wuX";
public static readonly String BonusUnit = "xojJ2w0S";
public static readonly String TotalExperience = "X9ABM7En";
public static readonly String Dictionary = "KJv6V7G9";
public static readonly String LibraDictionary = "z41pMJvC";
public static readonly String KnockdownCount = "4yk1JQBs";
public static readonly String PartyId = "r21y0YzS";
public static readonly String QuestId = "Z34jU7ue";
public static readonly String QuestStatus = "4kcAD9fW";
public static readonly String AcceptedDate = "VjJQ51uG";
public static readonly String CompletedDate = "m8ivD4NX";
public static readonly String EsperId = "Iwfx42Wo";
public static readonly String ColosseumId = "i5pd8xr3";
public static readonly String Description = "G4L0YIB2";
public static readonly String GachaId = "X1IuZnj2";
public static readonly String GachaSubId = "nqzG3b2v";
public static readonly String GachaUnitList = "UJz5QED2";
public static readonly String UnitList = "WbGYcN17";
public static readonly String LoginBonus = "ecK58yUC";
public static readonly String Equipment = "93Y6evuT";
public static readonly String Materia = "80NUYFMJ";
public static readonly String PartyUnits = "2A6fYiEC";
public static readonly String SubQuestId = "7Svg2kdT";
public static readonly String SubQuestItemCount = "0G7J2vfD";
public static readonly String TargetYear = "Gs6BT8n5";
public static readonly String NoticeInfo = "goAiX84L";
public static readonly String MedalId = "S21FT3L8";
public static readonly String MedalExchangeCount = "ngQX7a3N";
public static readonly String ServerTime_vhjEjKXZ = "vhjEjKXZ";
public static readonly String ServerTick = "cnopoBWZ";
public static readonly String UnitExperience = "S4U09svH";
public static readonly String ActualUnitExperience = "kcb0tsM6";
public static readonly String BonusGil = "Wdi3MAs2";
public static readonly String StolenGil = "Syar71nw";
public static readonly String ActualBonusGil = "16LQuC5r";
public static readonly String BaseGilTK = "TK6dB18Q";
public static readonly String AddGil = "L1uwe36k";
public static readonly String MissionResults = "09HRWXDf";
public static readonly String EquipId = "J1YX9kmM";
public static readonly String UnitLbGain = "1Rf2VDoI";
public static readonly String UnitXpGain = "u18nfD7p";
public static readonly String UnitGilSell = "N85uJT1d";
public static readonly String ItemsDropped = "xF9Sr1a6";
public static readonly String ItemsUniqueDropped = "JHMit30L";
public static readonly String ItemsStolen = "Sp7fF6I9";
public static readonly String ItemsUniqueStolen = "02aARqrv";
public static readonly String ItemsTreasure = "Z7G0yxXe";
public static readonly String ItemsFound = "EWmQy52k";
public static readonly String EquipmentDropped = "81fnjKLw";
public static readonly String EquipmentUniqueDropped = "3imo7rf4";
public static readonly String EquipmentStolen = "Iyx9Bos7";
public static readonly String EquipmentUniqueStolen = "VZ8DSco1";
public static readonly String EquipmentTreasure = "Mh1BA4uv";
public static readonly String EquipmentFound = "XMgu7qE0";
public static readonly String UnitsDropped = "2U05aV9Z";
public static readonly String ItemsTrusted = "REB5tAL9";
public static readonly String EquipmentTrusted = "Ym8F0ndw";
public static readonly String MateriaTrusted = "ERJa3SL5";
public static readonly String EncounterId = "V59rxm82";
public static readonly String EncounteredMonsters = "nar74pDu";
public static readonly String MonstersKilledCount = "f6M1cJgk";
public static readonly String MonsterParts = "uU21m4ry";
public static readonly String PartyStats = "Qic38SuC";
public static readonly String PossibleItems = "j94B63fP";
public static readonly String Rewards = "dX6cor8J";
public static readonly String Options = "5vFjunq1";
public static readonly String InternalDescription = "XFLm4Mx6";
public static readonly String GachaAnimation = "g38Pjk10";
public static readonly String Moogle = "JDFMe3A7";
public static readonly String InternalDesc = "4yT7FUqj";
public static readonly String Link = "1X65WPLU";
public static readonly String GiftId = "2HqjK1F7";
public static readonly String DateStartedYMD = "A3j7Wxtw";
public static readonly String FriendUnitId = "9WsTg26F";
public static readonly String FriendName = "AJGfV35v";
public static readonly String FriendRank = "QSf4NDq3";
public static readonly String FriendLevel = "wjX34YxG";
public static readonly String FriendIdFrom = "bUfq8BJ3";
public static readonly String MonsterHp = "fh31sk7B";
public static readonly String MonsterMp = "PC97pWQj";
public static readonly String MonsterAtk = "9NBV1XCS";
public static readonly String MonsterDef = "Pn5w9dfh";
public static readonly String MonsterMag = "84FJM3PD";
public static readonly String MonsterMnd = "T8xMDAZ4";
public static readonly String MonsterSpr = "41fbhtj2";
public static readonly String ElementResists = "hn42BL3Q";
public static readonly String StatusResists = "D9Nb7jgd";
public static readonly String PhysicalResist = "f67khsQZ";
public static readonly String MagicalResist = "Q1qLbx93";
public static readonly String MagicAffinity = "5VtY0SIU";
public static readonly String BattleUnitId = "PR2HIc71";
public static readonly String IsMoogle = "rUnq35N9";
public static readonly String UnitTmrId = "9mu4boy7";
public static readonly String BitNumber = "QLfe23bu";
public static readonly String AttackFrames = "a9DvZ70c";
public static readonly String EffectFrames = "5A8SmwyC";
public static readonly String EsperSp = "0A1BkNWb";
public static readonly String EsperBoardPieces = "E8WRi1bg";
public static readonly String Items_jsvoa0I2 = "jsvoa0I2";
public static readonly String NumSlots = "6ukvMSg9";
public static readonly String NumSlots2 = "1J7WnqxL";
public static readonly String ChallengeId = "V36ygRYs";
public static readonly String ChallengeRequirement = "Pzn5h0Ga";
public static readonly String ChallengeReward = "dX6cor8j";
public static readonly String ItemList = "HpL3FM4V";
public static readonly String AppRated = "YBRCsoxu";
public static readonly String MissionId = "qo3PECw6";
public static readonly String MapId = "9Pb24aSy";
public static readonly String RegionId = "Esxe71j3";
public static readonly String SubRegionId = "uv60hgDW";
public static readonly String DungeonId = "U9iHsau3";
public static readonly String MissionType = "Y4VoF8yu";
public static readonly String MissionIdChallenges = "qdhWF7z9";
public static readonly String RequiredSwitchId = "juA0Z4m7";
public static readonly String GrantedSwitchId = "dIPkNn61";
public static readonly String SwitchType = "5opcUT9t";
public static readonly String DungeonCompleteReward = "1x4bG2J8";
public static readonly String Raid = "CQN15Hgr";
public static readonly String GatheringStageId = "zF6QIY2r";
public static readonly String QuestSwitchIdQQ = "1C7GDEv4";
public static readonly String EventDungeonSwitchIdQQ = "q4f9IdMs";
public static readonly String DungeonSwitchIdQQ = "bs60p4LC";
public static readonly String BattleMusicQQ = "6w4xiIsS";
public static readonly String IconQQ = "DYTx1Is3";
public static readonly String StdEsperRaidGath = "gQR24kST";
public static readonly String UnitRestricted = "Kn03YQLk";
public static readonly String EscapeContinueQQ = "fV4Jn13q";
public static readonly String NotEggSeekerQQ = "TKBIV0U1";
public static readonly String PumpkinKingQQ = "T03qgLWA";
public static readonly String SnowmanQQ = "1Xfx5nPZ";
public static readonly String EventQQ = "k4imoR6p";
public static readonly String OptionName = "27RyqAGe";
public static readonly String OptionValue = "ayUH8g4q";
public static readonly String ArchiveName = "NYb0Cri6";
public static readonly String ArchiveValue = "6gAX1BpC";
public static readonly String TownId = "Gh92V3Tx";
public static readonly String StoreItemBuyId = "j9NS0H15";
public static readonly String StoreItemBuyPrice = "U1uaXph4";
public static readonly String StoreItemSellId = "8X7LwE3r";
public static readonly String StoreItemSellPrice = "97h4mIQo";
public static readonly String ArenaPlayerDmg = "GA1D6XIC";
public static readonly String ArenaEnemyDmg = "Pch7J9Ty";
public static readonly String ArenaPlayerTotalDmg = "3S8pMym0";
public static readonly String ArenaEnemyTotalDmg = "bB69ZWQY";
public static readonly String ArenaResult = "z8uj9TAU";
public static readonly String ArenaTurns = "g9t7dBCH";
public static readonly String ArenaVsFriend = "2q7sZreS";
public static readonly String DailyQuestId = "nYD7LvSG";
public static readonly String DailyQuestAmountRequired = "97CxqAgk";
public static readonly String DailyQuestAmountCompleted = "XCD3VwHk";
public static readonly String QuestCompleted = "3cEGYLhA";
public static readonly String DailyQuestName = "6uvHX2JG";
public static readonly String DailyQuestDescription = "56rsqHAp";
public static readonly String DailyQuestStatus = "ZLuw4DLa";
public static readonly String CountId = "Z0EN6jSh";
public static readonly String BattleWaves = "8xi6Xvyk";
public static readonly String BattleType = "0VkYZx1a";
public static readonly String FieldTreasureId = "4tNM5fGC";
public static readonly String FieldTreasureItem = "NiG2wL3A";
public static readonly String FieldTreasureAvailable = "uJh46wFS";
public static readonly String HarvestId = "N3hB0CwE";
public static readonly String HarvestOrder = "9GIvAQC2";
public static readonly String HarvestItem = "1Fa7rL5R";
public static readonly String GachaCost_0GgK6ytT = "0GgK6ytT";
public static readonly String GachaCost_zJ1A6HXm = "zJ1A6HXm";
public static readonly String GachaRepeat = "2RtVPS3b";
public static readonly String Milliseconds = "ytHoz4E2";
public static readonly String RequestID = "z5hB3P01";
public static readonly String ID = "6tSP4s8J";
public static readonly String ServerTime_dNrSy63V = "dNrSy63V";
public static readonly String ImageQuality = "3a162M47";
public static readonly String Language = "KmgMTuj5";
public static readonly String ReinforcementFriendId = "dUX7Pt5i";
public static readonly String ReinforcementUnitId = "qLke7K8f";
public static readonly String Items_4p6CrcGt = "4p6CrcGt";
public static readonly String Specials = "Pqi5r1TZ";
public static readonly String Magics = "i1yJ3hmT";
public static readonly String LimitBreaks = "s2rX7g0o";
public static readonly String Espers = "9JBtk2LE";
public static readonly String ElementalAttacks = "qr5PoZ1W";
public static readonly String KnockOuts = "73CfbLEx";
public static readonly String DeadCount = "Z1p0j9uF";
public static readonly String BattleClear = "69ieJGhD";
public static readonly String Count = "6q35TL07";
public static readonly String MonsterPartId = "xqartN26";
public static readonly String MonstPartsNum = "6Yc4RkdM";
public static readonly String MonsterId = "V9j8wJcC";
public static readonly String MonsterName = "VgrT60cL";
public static readonly String MonsterDrops = "9BetM2Ds";
public static readonly String MonsterSpecialDrops = "MZn8LC6H";
public static readonly String MonsterUnitDrops = "Vf5DGw07";
public static readonly String MonsterSteal = "3frn4ILX";
public static readonly String MonsterStealGil = "ATM35pjf";
public static readonly String TranslationJson = "15Y3fBmF";
public static readonly String RecipeType = "KosY4a18";
public static readonly String RecipeId = "MpNE6gB5";
public static readonly String RecipeBookId = "staFu8U1";
public static readonly String MateriaId = "H5jBL0Vf";
public static readonly String ItemType = "gak9Gb3N";
public static readonly String QuestSubquest = "9YPZuB2i";
public static readonly String RaidName = "xfirgH86";
public static readonly String RaidImage = "7DTnc2Lt";
public static readonly String RaidStart = "j93tApg0";
public static readonly String RaidEnd = "d7SKE3yo";
public static readonly String RaidLevel = "R01Wz7fe";
public static readonly String ArenaOpponents = "TI6deE8P";
public static readonly String ArenaRankingOpponents = "CLg9j1sh";
public static readonly String ArenaReward = "k9pWH78Z";
public static readonly String DateStart = "u3bysZ8S";
public static readonly String DateEnd = "2twsMyD6";
public static readonly String Expires = "kaR12y9r";
public static readonly String ScenarioId = "ja07xgLF";
public static readonly String Lapis = "cb3WmiD0";
public static readonly String ItemId = "tL6G9egd";
public static readonly String ItemCount = "Qy5EvcK1";
public static readonly String MissionWaveId = "2fY1IomW";
public static readonly String FriendIdUniqueUnitIdList = "0b6e9cwr";
public static readonly String FriendIdOnCooldown = "0j67QHm1";
public static readonly String RbEnemyId = "fP8Nv0KZ";
public static readonly String RbEnemyUnitList = "Jc4udh7x";
public static readonly String NoticeId = "td06MKEX";
public static readonly String NoticeType = "5GNraZM0";
public static readonly String NoticeRead = "oIra47LK";
public static readonly String EventSubId = "42B7MGIU";
public static readonly String EventId = "pvS5A4kE";
public static readonly String EventType = "89EvGKHx";
public static readonly String ObjectId = "6uIYE15X";
public static readonly String EventBonusUnitId = "86JmXL41";
public static readonly String EventBonutType = "1G6xjYvf";
public static readonly String BundleId = "EzXXHtTY";
public static readonly String BundleTitle = "3GtkuMJ1";
public static readonly String BundleDesc = "70oO1OaR";
public static readonly String BundleImage1 = "cSUSxGZA";
public static readonly String BundleImage2 = "MfynwFte";
public static readonly String BundleImage1Copy = "hJs2B3X5";
public static readonly String BundleCostType = "pRYHbNN5";
public static readonly String BundleCost = "AOHRcCC2";
public static readonly String BundleItemId = "4FF0gz8P";
public static readonly String BundleItemType = "YWF08vZS";
public static readonly String MailId = "ynP26rjD";
public static readonly String MailTitle = "fbcj5Aq9";
public static readonly String MailType = "9m5yIkCK";
public static readonly String MailItems = "7iJpH5zZ";
public static readonly String MailStatus = "14Y7jihw";
public static readonly String MailRecievedData = "f5LHNT4v";
public static readonly String BeastMix = "Simv74We";
public static readonly String Facebook = "Euv8cncS";
public static readonly String HomeMarqueeQuality = "H6o3079i";
public static readonly String HomeMarqueeLocale = "yJjS7dKX";
public static readonly String ItemBuy = "2aciVI9Y";
public static readonly String ItemSell = "2tHu3Chy";
public static readonly String MailReceipt = "rStH7od8";
public static readonly String Mission = "jQsE54Iz";
public static readonly String MissionEndChallenge = "2urzfX6d";
public static readonly String MissionEndContinue = "L4i4418y";
public static readonly String NoticeUpdate = "gM1w8m4y";
public static readonly String RmDungeon = "9Zok3IK2";
public static readonly String RoutineRaidMenuUpdate = "3uy7DzGB";
public static readonly String TownInfo = "JcxS6A8N";
public static readonly String Expedition = "67l03PW2";
public static readonly String ExpeditionId = "Ko86047K";
public static readonly String ExpeditionRewardId = "k60s8T42";
public static readonly String ExpeditionRelic = "p1H8307H";
public static readonly String ExpeditionRewardItem = "23tA3948";
public static readonly String ExpeditionRewardClaimed = "O7s2496M";
public static readonly String ExpeditionUnits = "7mA422N6";
public static readonly String ExpeditionBonus = "sO308L0M";
public static readonly String PartySelect = "CN92arJK";
public static readonly String CurrentParty = "Kgvo5JL2";
public static readonly String CompanionParty = "MBIYc89Q";
public static readonly String ColosseumParty = "Isc1ga3G";
public static readonly String ArenaParty = "igrz05CY";
public static readonly String EsperParty = "XZ4Kh7Ic";
public static readonly String EquipmentRarity = "52KBR9qV";
public static readonly String EquipmentSlotId = "znGsI4f8";
public static readonly String EquipmentTypeId = "8DZGF4Nn";
public static readonly String EquipmentRequirement = "t5Q4wZ7v";
public static readonly String EquipmentStatusInflict = "SxREt1M0";
public static readonly String EquipmentElementInflict = "Jn6BbR2P";
public static readonly String EquipmentPassiveAbility = "t42Xb3jV";
public static readonly String EquipmentActiveAbility = "GiBvPK84";
public static readonly String ItemStack = "9J6uRe8f";
public static readonly String ItemIdClone = "0HUPxDf1";
public static readonly String ItemBuyPrice = "E61qF5Lp";
public static readonly String ItemSellPrice = "bz6RS3pI";
public static readonly String SublimationId = "SJ56uhz2";
public static readonly String SublimationItems = "HS7V6Ww1";
public static readonly String SublimationUnitId = "25oxcKwN";
public static readonly String ClassUpItems = "KCk8u0am";
public static readonly String LBExperience = "A90DrNfp";
public static readonly Dictionary<String, String> Variables = new Dictionary<String, String>
{
{Encrypted, "Encrypted"},
{UserId, "UserId"},
{UserName, "UserName"},
{Password, "Password"},
{OperatingSystem, "OperatingSystem"},
{CountryCode, "CountryCode"},
{ContactId, "ContactId"},
{PurchaseSignature, "PurchaseSignature"},
{BuildVersion, "BuildVersion"},
{Time, "Time"},
{FriendId, "FriendId"},
{NotFriendId, "NotFriendId"},
{ModelChangeCnt, "ModelChangeCnt"},
{MacroToolRunningStatus, "MacroToolRunningStatus"},
{Ymd, "Ymd"},
{AppVersion, "AppVersion"},
{GumiId, "GumiId"},
{GumiToken, "GumiToken"},
{TransferCode, "TransferCode"},
{TransferPin, "TransferPin"},
{DateCreatedShort, "DateCreatedShort"},
{DateCreated, "DateCreated"},
{DateLinked, "DateLinked"},
{Time0, "Time0"},
{DeviceId, "DeviceId"},
{AdvertisingId, "AdvertisingId"},
{FacebookUserId, "FacebookUserId"},
{FacebookToken, "FacebookToken"},
{UsingFacebook, "UsingFacebook"},
{Data, "Data"},
{Level, "Level"},
{Experience, "Experience"},
{Energy, "Energy"},
{EnergyTimer, "EnergyTimer"},
{EnergyMax, "EnergyMax"},
{ColosseumOrb, "ColosseumOrb"},
{ColosseumOrbTimer, "ColosseumOrbTimer"},
{ColosseumOrbMax, "ColosseumOrbMax"},
{RaidOrb, "RaidOrb"},
{RaidOrbTimer, "RaidOrbTimer"},
{RaidOrbMax, "RaidOrbMax"},
{ExtraUnits, "ExtraUnits"},
{ExtraFriends, "ExtraFriends"},
{ExtraEquipment, "ExtraEquipment"},
{ExtraItems, "ExtraItems"},
{ExtraMaterials, "ExtraMaterials"},
{ExtraMateria, "ExtraMateria"},
{LastLoginYMD, "LastLoginYMD"},
{SerialLogin, "SerialLogin"},
{Gil, "Gil"},
{FriendPoints, "FriendPoints"},
{Gift, "Gift"},
{Message, "Message"},
{KeyName, "KeyName"},
{Value, "Value"},
{UniqueUnitId, "UniqueUnitId"},
{UnitId, "UnitId"},
{LastAccessBase, "LastAccessBase"},
{Rarity, "Rarity"},
{GenderId, "GenderId"},
{JobId, "JobId"},
{TribeId, "TribeId"},
{GameId, "GameId"},
{BaseUnitId, "BaseUnitId"},
{UnitMaxLevel, "UnitMaxLevel"},
{EquipIds, "EquipIds"},
{IsCombatUnit, "IsCombatUnit"},
{IsPotUnit, "IsPotUnit"},
{IsSummonable, "IsSummonable"},
{MateriaSlots, "MateriaSlots"},
{UnitSellPrice, "UnitSellPrice"},
{UnitSellIds, "UnitSellIds"},
{UnitLvl, "UnitLvl"},
{UnitHp, "UnitHp"},
{UnitMp, "UnitMp"},
{UnitAtk, "UnitAtk"},
{UnitDef, "UnitDef"},
{UnitMag, "UnitMag"},
{UnitSpr, "UnitSpr"},
{UnitLb, "UnitLb"},
{UnitLbLvl, "UnitLbLvl"},
{UnitTmr, "UnitTmr"},
{BonusUnit, "BonusUnit"},
{TotalExperience, "TotalExperience"},
{Dictionary, "Dictionary"},
{LibraDictionary, "LibraDictionary"},
{KnockdownCount, "KnockdownCount"},
{PartyId, "PartyId"},
{QuestId, "QuestId"},
{QuestStatus, "QuestStatus"},
{AcceptedDate, "AcceptedDate"},
{CompletedDate, "CompletedDate"},
{EsperId, "EsperId"},
{ColosseumId, "ColosseumId"},
{Description, "Description"},
{GachaId, "GachaId"},
{GachaSubId, "GachaSubId"},
{GachaUnitList, "GachaUnitList"},
{UnitList, "UnitList"},
{LoginBonus, "LoginBonus"},
{Equipment, "Equipment"},
{Materia, "Materia"},
{PartyUnits, "PartyUnits"},
{SubQuestId, "SubQuestId"},
{SubQuestItemCount, "SubQuestItemCount"},
{TargetYear, "TargetYear"},
{NoticeInfo, "NoticeInfo"},
{MedalId, "MedalId"},
{MedalExchangeCount, "MedalExchangeCount"},
{ServerTime_vhjEjKXZ, "ServerTime_vhjEjKXZ"},
{ServerTick, "ServerTick"},
{UnitExperience, "UnitExperience"},
{ActualUnitExperience, "ActualUnitExperience"},
{BonusGil, "BonusGil"},
{StolenGil, "StolenGil"},
{ActualBonusGil, "ActualBonusGil"},
{BaseGilTK, "BaseGilTK"},
{AddGil, "AddGil"},
{MissionResults, "MissionResults"},
{EquipId, "EquipId"},
{UnitLbGain, "UnitLbGain"},
{UnitXpGain, "UnitXpGain"},
{UnitGilSell, "UnitGilSell"},
{ItemsDropped, "ItemsDropped"},
{ItemsUniqueDropped, "ItemsUniqueDropped"},
{ItemsStolen, "ItemsStolen"},
{ItemsUniqueStolen, "ItemsUniqueStolen"},
{ItemsTreasure, "ItemsTreasure"},
{ItemsFound, "ItemsFound"},
{EquipmentDropped, "EquipmentDropped"},
{EquipmentUniqueDropped, "EquipmentUniqueDropped"},
{EquipmentStolen, "EquipmentStolen"},
{EquipmentUniqueStolen, "EquipmentUniqueStolen"},
{EquipmentTreasure, "EquipmentTreasure"},
{EquipmentFound, "EquipmentFound"},
{UnitsDropped, "UnitsDropped"},
{ItemsTrusted, "ItemsTrusted"},
{EquipmentTrusted, "EquipmentTrusted"},
{MateriaTrusted, "MateriaTrusted"},
{EncounterId, "EncounterId"},
{EncounteredMonsters, "EncounteredMonsters"},
{MonstersKilledCount, "MonstersKilledCount"},
{MonsterParts, "MonsterParts"},
{PartyStats, "PartyStats"},
{PossibleItems, "PossibleItems"},
{Rewards, "Rewards"},
{Options, "Options"},
{InternalDescription, "InternalDescription"},
{GachaAnimation, "GachaAnimation"},
{Moogle, "Moogle"},
{InternalDesc, "InternalDesc"},
{Link, "Link"},
{GiftId, "GiftId"},
{DateStartedYMD, "DateStartedYMD"},
{FriendUnitId, "FriendUnitId"},
{FriendName, "FriendName"},
{FriendRank, "FriendRank"},
{FriendLevel, "FriendLevel"},
{FriendIdFrom, "FriendIdFrom"},
{MonsterHp, "MonsterHp"},
{MonsterMp, "MonsterMp"},
{MonsterAtk, "MonsterAtk"},
{MonsterDef, "MonsterDef"},
{MonsterMag, "MonsterMag"},
{MonsterMnd, "MonsterMnd"},
{MonsterSpr, "MonsterSpr"},
{ElementResists, "ElementResists"},
{StatusResists, "StatusResists"},
{PhysicalResist, "PhysicalResist"},
{MagicalResist, "MagicalResist"},
{MagicAffinity, "MagicAffinity"},
{BattleUnitId, "BattleUnitId"},
{IsMoogle, "IsMoogle"},
{UnitTmrId, "UnitTmrId"},
{BitNumber, "BitNumber"},
{AttackFrames, "AttackFrames"},
{EffectFrames, "EffectFrames"},
{EsperSp, "EsperSp"},
{EsperBoardPieces, "EsperBoardPieces"},
{Items_jsvoa0I2, "Items_jsvoa0I2"},
{NumSlots, "NumSlots"},
{NumSlots2, "NumSlots2"},
{ChallengeId, "ChallengeId"},
{ChallengeRequirement, "ChallengeRequirement"},
{ChallengeReward, "ChallengeReward"},
{ItemList, "ItemList"},
{AppRated, "AppRated"},
{MissionId, "MissionId"},
{MapId, "MapId"},
{RegionId, "RegionId"},
{SubRegionId, "SubRegionId"},
{DungeonId, "DungeonId"},
{MissionType, "MissionType"},
{MissionIdChallenges, "MissionIdChallenges"},
{RequiredSwitchId, "RequiredSwitchId"},
{GrantedSwitchId, "GrantedSwitchId"},
{SwitchType, "SwitchType"},
{DungeonCompleteReward, "DungeonCompleteReward"},
{Raid, "Raid"},
{GatheringStageId, "GatheringStageId"},
{QuestSwitchIdQQ, "QuestSwitchIdQQ"},
{EventDungeonSwitchIdQQ, "EventDungeonSwitchIdQQ"},
{DungeonSwitchIdQQ, "DungeonSwitchIdQQ"},
{BattleMusicQQ, "BattleMusicQQ"},
{IconQQ, "IconQQ"},
{StdEsperRaidGath, "StdEsperRaidGath"},
{UnitRestricted, "UnitRestricted"},
{EscapeContinueQQ, "EscapeContinueQQ"},
{NotEggSeekerQQ, "NotEggSeekerQQ"},
{PumpkinKingQQ, "PumpkinKingQQ"},
{SnowmanQQ, "SnowmanQQ"},
{EventQQ, "EventQQ"},
{OptionName, "OptionName"},
{OptionValue, "OptionValue"},
{ArchiveName, "ArchiveName"},
{ArchiveValue, "ArchiveValue"},
{TownId, "TownId"},
{StoreItemBuyId, "StoreItemBuyId"},
{StoreItemBuyPrice, "StoreItemBuyPrice"},
{StoreItemSellId, "StoreItemSellId"},
{StoreItemSellPrice, "StoreItemSellPrice"},
{ArenaPlayerDmg, "ArenaPlayerDmg"},
{ArenaEnemyDmg, "ArenaEnemyDmg"},
{ArenaPlayerTotalDmg, "ArenaPlayerTotalDmg"},
{ArenaEnemyTotalDmg, "ArenaEnemyTotalDmg"},
{ArenaResult, "ArenaResult"},
{ArenaTurns, "ArenaTurns"},
{ArenaVsFriend, "ArenaVsFriend"},
{DailyQuestId, "DailyQuestId"},
{DailyQuestAmountRequired, "DailyQuestAmountRequired"},
{DailyQuestAmountCompleted, "DailyQuestAmountCompleted"},
{QuestCompleted, "QuestCompleted"},
{DailyQuestName, "DailyQuestName"},
{DailyQuestDescription, "DailyQuestDescription"},
{DailyQuestStatus, "DailyQuestStatus"},
{CountId, "CountId"},
{BattleWaves, "BattleWaves"},
{BattleType, "BattleType"},
{FieldTreasureId, "FieldTreasureId"},
{FieldTreasureItem, "FieldTreasureItem"},
{FieldTreasureAvailable, "FieldTreasureAvailable"},
{HarvestId, "HarvestId"},
{HarvestOrder, "HarvestOrder"},
{HarvestItem, "HarvestItem"},
{GachaCost_0GgK6ytT, "GachaCost_0GgK6ytT"},
{GachaCost_zJ1A6HXm, "GachaCost_zJ1A6HXm"},
{GachaRepeat, "GachaRepeat"},
{Milliseconds, "Milliseconds"},
{RequestID, "RequestID"},
{ID, "ID"},
{ServerTime_dNrSy63V, "ServerTime_dNrSy63V"},
{ImageQuality, "ImageQuality"},
{Language, "Language"},
{ReinforcementFriendId, "ReinforcementFriendId"},
{ReinforcementUnitId, "ReinforcementUnitId"},
{Items_4p6CrcGt, "Items_4p6CrcGt"},
{Specials, "Specials"},
{Magics, "Magics"},
{LimitBreaks, "LimitBreaks"},
{Espers, "Espers"},
{ElementalAttacks, "ElementalAttacks"},
{KnockOuts, "KnockOuts"},
{DeadCount, "DeadCount"},
{BattleClear, "BattleClear"},
{Count, "Count"},
{MonsterPartId, "MonsterPartId"},
{MonstPartsNum, "MonstPartsNum"},
{MonsterId, "MonsterId"},
{MonsterName, "MonsterName"},
{MonsterDrops, "MonsterDrops"},
{MonsterSpecialDrops, "MonsterSpecialDrops"},
{MonsterUnitDrops, "MonsterUnitDrops"},
{MonsterSteal, "MonsterSteal"},
{MonsterStealGil, "MonsterStealGil"},
{TranslationJson, "TranslationJson"},
{RecipeType, "RecipeType"},
{RecipeId, "RecipeId"},
{RecipeBookId, "RecipeBookId"},
{MateriaId, "MateriaId"},
{ItemType, "ItemType"},
{QuestSubquest, "QuestSubquest"},
{RaidName, "RaidName"},
{RaidImage, "RaidImage"},
{RaidStart, "RaidStart"},
{RaidEnd, "RaidEnd"},
{RaidLevel, "RaidLevel"},
{ArenaOpponents, "ArenaOpponents"},
{ArenaRankingOpponents, "ArenaRankingOpponents"},
{ArenaReward, "ArenaReward"},
{DateStart, "DateStart"},
{DateEnd, "DateEnd"},
{Expires, "Expires"},
{ScenarioId, "ScenarioId"},
{Lapis, "Lapis"},
{ItemId, "ItemId"},
{ItemCount, "ItemCount"},
{MissionWaveId, "MissionWaveId"},
{FriendIdUniqueUnitIdList, "FriendIdUniqueUnitIdList"},
{FriendIdOnCooldown, "FriendIdOnCooldown"},
{RbEnemyId, "RbEnemyId"},
{RbEnemyUnitList, "RbEnemyUnitList"},
{NoticeId, "NoticeId"},
{NoticeType, "NoticeType"},
{NoticeRead, "NoticeRead"},
{EventSubId, "EventSubId"},
{EventId, "EventId"},
{EventType, "EventType"},
{ObjectId, "ObjectId"},
{EventBonusUnitId, "EventBonusUnitId"},
{EventBonutType, "EventBonutType"},
{BundleId, "BundleId"},
{BundleTitle, "BundleTitle"},
{BundleDesc, "BundleDesc"},
{BundleImage1, "BundleImage1"},
{BundleImage2, "BundleImage2"},
{BundleImage1Copy, "BundleImage1Copy"},
{BundleCostType, "BundleCostType"},
{BundleCost, "BundleCost"},
{BundleItemId, "BundleItemId"},
{BundleItemType, "BundleItemType"},
{MailId, "MailId"},
{MailTitle, "MailTitle"},
{MailType, "MailType"},
{MailItems, "MailItems"},
{MailStatus, "MailStatus"},
{MailRecievedData, "MailRecievedData"},
{BeastMix, "BeastMix"},
{Facebook, "Facebook"},
{HomeMarqueeQuality, "HomeMarqueeQuality"},
{HomeMarqueeLocale, "HomeMarqueeLocale"},
{ItemBuy, "ItemBuy"},
{ItemSell, "ItemSell"},
{MailReceipt, "MailReceipt"},
{Mission, "Mission"},
{MissionEndChallenge, "MissionEndChallenge"},
{MissionEndContinue, "MissionEndContinue"},
{NoticeUpdate, "NoticeUpdate"},
{RmDungeon, "RmDungeon"},
{RoutineRaidMenuUpdate, "RoutineRaidMenuUpdate"},
{TownInfo, "TownInfo"},
{Expedition, "Expedition"},
{ExpeditionId, "ExpeditionId"},
{ExpeditionRewardId, "ExpeditionRewardId"},
{ExpeditionRelic, "ExpeditionRelic"},
{ExpeditionRewardItem, "ExpeditionRewardItem"},
{ExpeditionRewardClaimed, "ExpeditionRewardClaimed"},
{ExpeditionUnits, "ExpeditionUnits"},
{ExpeditionBonus, "ExpeditionBonus"},
{PartySelect, "PartySelect"},
{CurrentParty, "CurrentParty"},
{CompanionParty, "CompanionParty"},
{ColosseumParty, "ColosseumParty"},
{ArenaParty, "ArenaParty"},
{EsperParty, "EsperParty"},
{EquipmentRarity, "EquipmentRarity"},
{EquipmentSlotId, "EquipmentSlotId"},
{EquipmentTypeId, "EquipmentTypeId"},
{EquipmentRequirement, "EquipmentRequirement"},
{EquipmentStatusInflict, "EquipmentStatusInflict"},
{EquipmentElementInflict, "EquipmentElementInflict"},
{EquipmentPassiveAbility, "EquipmentPassiveAbility"},
{EquipmentActiveAbility, "EquipmentActiveAbility"},
{ItemStack, "ItemStack"},
{ItemIdClone, "ItemIdClone"},
{ItemBuyPrice, "ItemBuyPrice"},
{ItemSellPrice, "ItemSellPrice"},
{SublimationId, "SublimationId"},
{SublimationItems, "SublimationItems"},
{SublimationUnitId, "SublimationUnitId"},
{ClassUpItems, "ClassUpItems"},
{LBExperience, "LBExperience"},
};
}
}
| |
// Author: Robert Scheller, Melissa Lucash
using Landis.Core;
using Landis.SpatialModeling;
using Landis.Utilities;
using Landis.Library.LeafBiomassCohorts;
using System;
using System.Collections.Generic;
namespace Landis.Extension.Succession.NECN
{
/// <summary>
/// A helper class.
/// </summary>
public class FireReductions
{
private double coarseLitterReduction;
private double fineLitterReduction;
private double somReduction;
private double cohortWoodReduction;
private double cohortLeafReduction;
public double CoarseLitterReduction
{
get {
return coarseLitterReduction;
}
set {
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Coarse litter reduction due to fire must be between 0 and 1.0");
coarseLitterReduction = value;
}
}
public double FineLitterReduction
{
get {
return fineLitterReduction;
}
set {
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Fine litter reduction due to fire must be between 0 and 1.0");
fineLitterReduction = value;
}
}
public double CohortWoodReduction
{
get
{
return cohortWoodReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0");
cohortWoodReduction = value;
}
}
public double CohortLeafReduction
{
get
{
return cohortLeafReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Cohort wood reduction due to fire must be between 0 and 1.0");
cohortLeafReduction = value;
}
}
public double SOMReduction
{
get
{
return somReduction;
}
set
{
if (value < 0.0 || value > 1.0)
throw new InputValueException(value.ToString(), "Soil Organic Matter (SOM) reduction due to fire must be between 0 and 1.0");
somReduction = value;
}
}
//---------------------------------------------------------------------
public FireReductions()
{
this.CoarseLitterReduction = 0.0;
this.FineLitterReduction = 0.0;
this.CohortLeafReduction = 0.0;
this.CohortWoodReduction = 0.0;
this.SOMReduction = 0.0;
}
}
public class FireEffects
{
public static FireReductions[] ReductionsTable;
//public FireEffects(int numberOfSeverities)
//{
// ReductionsTable = new FireReductions[numberOfSeverities];
// for(int i=0; i <= numberOfSeverities; i++)
// {
// ReductionsTable[i] = new FireReductions();
// }
//}
//---------------------------------------------------------------------
public static void Initialize(IInputParameters parameters)
{
ReductionsTable = parameters.FireReductionsTable;
}
//---------------------------------------------------------------------
/// <summary>
/// Computes fire effects on litter, coarse woody debris, mineral soil, and charcoal.
/// No effects on soil organic matter (negligible according to Johnson et al. 2001).
/// </summary>
public static void ReduceLayers(byte severity, Site site)
{
// PlugIn.ModelCore.UI.WriteLine(" Calculating fire induced layer reductions. FineLitter={0}, Wood={1}, Duff={2}.", ReductionsTable[severity].FineLitterReduction, ReductionsTable[severity].CoarseLitterReduction, ReductionsTable[severity].SOMReduction);
// Structural litter first
double fineLitterReduction = 0.0;
try
{
fineLitterReduction = ReductionsTable[severity].FineLitterReduction;
}
catch
{
PlugIn.ModelCore.UI.WriteLine(" NOTE: The fire reductions table does not contain an entry for severity {0}. DEFAULT REDUCTION = 0.", severity);
return;
}
double carbonLoss = SiteVars.SurfaceStructural[site].Carbon * fineLitterReduction;
double nitrogenLoss = SiteVars.SurfaceStructural[site].Nitrogen * fineLitterReduction;
double summaryNLoss = nitrogenLoss;
SiteVars.SurfaceStructural[site].Carbon -= carbonLoss;
SiteVars.SourceSink[site].Carbon += carbonLoss;
SiteVars.FireCEfflux[site] += carbonLoss;
SiteVars.SurfaceStructural[site].Nitrogen -= nitrogenLoss;
SiteVars.SourceSink[site].Nitrogen += nitrogenLoss;
SiteVars.FireNEfflux[site] += nitrogenLoss;
SiteVars.FlamingConsumption[site] += carbonLoss * 2.0;
// Metabolic litter
carbonLoss = SiteVars.SurfaceMetabolic[site].Carbon * fineLitterReduction;
nitrogenLoss = SiteVars.SurfaceMetabolic[site].Nitrogen * fineLitterReduction;
summaryNLoss += nitrogenLoss;
SiteVars.SurfaceMetabolic[site].Carbon -= carbonLoss;
SiteVars.SourceSink[site].Carbon += carbonLoss;
SiteVars.FireCEfflux[site] += carbonLoss;
SiteVars.SurfaceMetabolic[site].Nitrogen -= nitrogenLoss;
SiteVars.SourceSink[site].Nitrogen += nitrogenLoss;
SiteVars.FireNEfflux[site] += nitrogenLoss;
SiteVars.FlamingConsumption[site] += carbonLoss * 2.0;
// Surface dead wood
double woodLossMultiplier = ReductionsTable[severity].CoarseLitterReduction;
carbonLoss = SiteVars.SurfaceDeadWood[site].Carbon * woodLossMultiplier;
nitrogenLoss = SiteVars.SurfaceDeadWood[site].Nitrogen * woodLossMultiplier;
summaryNLoss += nitrogenLoss;
SiteVars.SurfaceDeadWood[site].Carbon -= carbonLoss;
SiteVars.SourceSink[site].Carbon += carbonLoss;
SiteVars.FireCEfflux[site] += carbonLoss;
SiteVars.SurfaceDeadWood[site].Nitrogen -= nitrogenLoss;
SiteVars.SourceSink[site].Nitrogen += nitrogenLoss;
SiteVars.FireNEfflux[site] += nitrogenLoss;
SiteVars.FlamingConsumption[site] += carbonLoss * 2.0 * 0.35; // 0.35 = Small wood FRACTION FROM ALEC
SiteVars.SmolderConsumption[site] += carbonLoss * 2.0 * 0.65; // 0.65 = Large wood FRACTION FROM ALEC
// Surficial Soil Organic Matter (the 'Duff' layer)
double SOM_Multiplier = ReductionsTable[severity].SOMReduction;
carbonLoss = SiteVars.SOM1surface[site].Carbon * SOM_Multiplier;
nitrogenLoss = SiteVars.SOM1surface[site].Nitrogen * SOM_Multiplier;
summaryNLoss += nitrogenLoss;
SiteVars.SOM1surface[site].Carbon -= carbonLoss;
SiteVars.SourceSink[site].Carbon += carbonLoss;
SiteVars.FireCEfflux[site] += carbonLoss;
SiteVars.SOM1surface[site].Nitrogen -= nitrogenLoss;
SiteVars.SourceSink[site].Nitrogen += nitrogenLoss;
SiteVars.FireNEfflux[site] += nitrogenLoss;
SiteVars.SmolderConsumption[site] += carbonLoss * 2.0;
// Transfer 1% to mineral N.
SiteVars.MineralN[site] += summaryNLoss * 0.01;
}
//---------------------------------------------------------------------
// Crown scorching is when a cohort loses its foliage but is not killed.
public static double CrownScorching(ICohort cohort, byte siteSeverity)
{
int difference = (int) siteSeverity - cohort.Species.FireTolerance;
double ageFraction = 1.0 - ((double) cohort.Age / (double) cohort.Species.Longevity);
if(SpeciesData.Epicormic[cohort.Species])
{
if(difference < 0)
return 0.5 * ageFraction;
if(difference == 0)
return 0.75 * ageFraction;
if(difference > 0)
return 1.0 * ageFraction;
}
return 0.0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentNHibernate.Automapping.TestFixtures;
using FluentNHibernate.Conventions.Helpers.Builders;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Mapping;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Testing.FluentInterfaceTests;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface
{
[TestFixture]
public class HasManyCollectionConventionTests
{
private PersistenceModel model;
private IMappingProvider mapping;
private Type mappingType;
[SetUp]
public void CreatePersistenceModel()
{
model = new PersistenceModel();
}
[Test]
public void AccessShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Access.Field());
Convention(x => x.Access.Property());
VerifyModel(x => x.Access.ShouldEqual("field"));
}
[Test]
public void BatchSizeShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.BatchSize(10));
Convention(x => x.BatchSize(100));
VerifyModel(x => x.BatchSize.ShouldEqual(10));
}
[Test]
public void CacheShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Cache.ReadOnly());
Convention(x => x.Cache.ReadWrite());
VerifyModel(x => x.Cache.Usage.ShouldEqual("read-only"));
}
[Test]
public void CascadeShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Cascade.All());
Convention(x => x.Cascade.None());
VerifyModel(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void CheckConstraintShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Check("constraint = 1"));
Convention(x => x.Check("constraint = 0"));
VerifyModel(x => x.Check.ShouldEqual("constraint = 1"));
}
[Test]
public void CollectionTypeShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.CollectionType<int>());
Convention(x => x.CollectionType<string>());
VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(int)));
}
[Test]
public void FetchShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Fetch.Join());
Convention(x => x.Fetch.Select());
VerifyModel(x => x.Fetch.ShouldEqual("join"));
}
[Test]
public void GenericShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Generic());
Convention(x => x.Not.Generic());
VerifyModel(x => x.Generic.ShouldBeTrue());
}
[Test]
public void InverseShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Inverse());
Convention(x => x.Not.Inverse());
VerifyModel(x => x.Inverse.ShouldBeTrue());
}
[Test]
public void KeyColumnNameShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.KeyColumn("name"));
Convention(x => x.Key.Column("xxx"));
VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("name"));
}
[Test]
public void LazyShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.LazyLoad());
Convention(x => x.Not.LazyLoad());
VerifyModel(x => x.Lazy.ShouldEqual(true));
}
[Test]
public void OptimisticLockShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.OptimisticLock.All());
Convention(x => x.OptimisticLock.Dirty());
VerifyModel(x => x.OptimisticLock.ShouldEqual("all"));
}
[Test]
public void PersisterShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Persister<CustomPersister>());
Convention(x => x.Persister<SecondCustomPersister>());
VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister)));
}
[Test]
public void SchemaShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Schema("dbo"));
Convention(x => x.Schema("test"));
VerifyModel(x => x.Schema.ShouldEqual("dbo"));
}
[Test]
public void WhereShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Where("x = 1"));
Convention(x => x.Where("y = 2"));
VerifyModel(x => x.Where.ShouldEqual("x = 1"));
}
[Test]
public void ForeignKeyShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.ForeignKeyConstraintName("key"));
Convention(x => x.Key.ForeignKey("xxx"));
VerifyModel(x => x.Key.ForeignKey.ShouldEqual("key"));
}
[Test]
public void TableNameShouldntBeOverwritten()
{
Mapping(x => x.Children, x => x.Table("table"));
Convention(x => x.Table("xxx"));
VerifyModel(x => x.TableName.ShouldEqual("table"));
}
#region Helpers
private void Convention(Action<ICollectionInstance> convention)
{
model.Conventions.Add(new CollectionConventionBuilder().Always(convention));
}
private void Mapping<TChild>(Expression<Func<ExampleInheritedClass, IEnumerable<TChild>>> property, Action<OneToManyPart<TChild>> mappingDefinition)
{
var classMap = new ClassMap<ExampleInheritedClass>();
var map = classMap.HasMany(property);
mappingDefinition(map);
mapping = classMap;
mappingType = typeof(ExampleInheritedClass);
}
private void VerifyModel(Action<ICollectionMapping> modelVerification)
{
model.Add(mapping);
var generatedModels = model.BuildMappings();
var modelInstance = generatedModels
.First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null)
.Classes.First()
.Collections.First();
modelVerification(modelInstance);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CTYPES
using System;
using System.Diagnostics;
using System.Numerics;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
/// <summary>
/// Fields are created when a Structure is defined and provide
/// introspection of the structure.
/// </summary>
[PythonType, PythonHidden]
public sealed class Field : PythonTypeDataSlot, ICodeFormattable {
private readonly INativeType _fieldType;
private readonly int _offset, _index, _bits = -1, _bitsOffset;
private readonly string _fieldName;
internal Field(string fieldName, INativeType fieldType, int offset, int index) {
_offset = offset;
_fieldType = fieldType;
_index = index;
_fieldName = fieldName;
}
internal Field(string fieldName, INativeType fieldType, int offset, int index, int? bits, int? bitOffset) {
_offset = offset;
_fieldType = fieldType;
_index = index;
_fieldName = fieldName;
// if the number of bits is the full type width, we don't
// need to do any masking anywhere, we may want to revisit this
// if the __repr__ is an issue
if (bits != null && bits.Value != (_fieldType.Size * 8)) {
_bits = bits.Value;
_bitsOffset = bitOffset.Value;
}
}
public int offset {
get {
return _offset;
}
}
public int size {
get {
return _fieldType.Size;
}
}
#region Internal APIs
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
if (instance != null) {
CData inst = (CData)instance;
value = _fieldType.GetValue(inst._memHolder, inst, _offset, false);
if (_bits == -1) {
return true;
}
value = ExtractBits(value);
return true;
}
value = this;
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) {
if (instance != null) {
SetValue(((CData)instance)._memHolder, 0, value);
return true;
}
return base.TrySetValue(context, instance, owner, value);
}
internal void SetValue(MemoryHolder address, int baseOffset, object value) {
if (_bits == -1) {
object keepAlive = _fieldType.SetValue(address, baseOffset + _offset, value);
if (keepAlive != null) {
address.AddObject(_index.ToString(), keepAlive);
}
} else {
SetBitsValue(address, baseOffset, value);
}
}
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) {
throw PythonOps.TypeError("cannot delete fields in ctypes structures/unions");
}
internal INativeType NativeType {
get {
return _fieldType;
}
}
internal int? BitCount {
get {
if (_bits == -1) {
return null;
}
return _bits;
}
}
internal string FieldName {
get {
return _fieldName;
}
}
#endregion
#region ICodeFormattable Members
public string __repr__(CodeContext context) {
if (_bits == -1) {
return String.Format("<Field type={0}, ofs={1}, size={2}>", ((PythonType)_fieldType).Name, offset, size);
}
return String.Format("<Field type={0}, ofs={1}:{2}, bits={3}>", ((PythonType)_fieldType).Name, offset, _bitsOffset, _bits);
}
#endregion
#region Private implementation
/// <summary>
/// Called for fields which have been limited to a range of bits. Given the
/// value for the full type this extracts the individual bits.
/// </summary>
private object ExtractBits(object value) {
if (value is int) {
int validBits = ((1 << _bits) - 1);
int iVal = (int)value;
iVal = (iVal >> _bitsOffset) & validBits;
if (IsSignedType) {
// need to sign extend if high bit is set
if ((iVal & (1 << (_bits - 1))) != 0) {
iVal |= (-1) ^ validBits;
}
}
value = ScriptingRuntimeHelpers.Int32ToObject(iVal);
} else {
Debug.Assert(value is BigInteger); // we only return ints or big ints from GetValue
ulong validBits = (1UL << _bits) - 1;
BigInteger biVal = (BigInteger)value;
ulong bits;
if (IsSignedType) {
bits = (ulong)(long)biVal;
} else {
bits = (ulong)biVal;
}
bits = (bits >> _bitsOffset) & validBits;
if (IsSignedType) {
// need to sign extend if high bit is set
if ((bits & (1UL << (_bits - 1))) != 0) {
bits |= ulong.MaxValue ^ validBits;
}
value = (BigInteger)(long)bits;
} else {
value = (BigInteger)bits;
}
}
return value;
}
/// <summary>
/// Called for fields which have been limited to a range of bits. Sets the
/// specified value into the bits for the field.
/// </summary>
private void SetBitsValue(MemoryHolder address, int baseOffset, object value) {
// get the value in the form of a ulong which can contain the biggest bitfield
ulong newBits;
if (value is int) {
newBits = (ulong)(int)value;
} else if (value is BigInteger) {
newBits = (ulong)(long)(BigInteger)value;
} else {
throw PythonOps.TypeErrorForTypeMismatch("int or long", value);
}
// do the same for the existing value
int offset = checked(_offset + baseOffset);
object curValue = _fieldType.GetValue(address, null, offset, false);
ulong valueBits;
if (curValue is int) {
valueBits = (ulong)(int)curValue;
} else {
valueBits = (ulong)(long)(BigInteger)curValue;
}
// get a mask for the bits this field owns
ulong targetBits = ((1UL << _bits) - 1) << _bitsOffset;
// clear the existing bits
valueBits &= ~targetBits;
// or in the new bits provided by the user
valueBits |= (newBits << _bitsOffset) & targetBits;
// and set the value
if (IsSignedType) {
if (_fieldType.Size <= 4) {
_fieldType.SetValue(address, offset, (int)(long)valueBits);
} else {
_fieldType.SetValue(address, offset, (BigInteger)(long)valueBits);
}
} else {
if (_fieldType.Size < 4) {
_fieldType.SetValue(address, offset, (int)valueBits);
} else {
_fieldType.SetValue(address, offset, (BigInteger)valueBits);
}
}
}
private bool IsSignedType {
get {
switch (((SimpleType)_fieldType)._type) {
case SimpleTypeKind.SignedByte:
case SimpleTypeKind.SignedInt:
case SimpleTypeKind.SignedLong:
case SimpleTypeKind.SignedLongLong:
case SimpleTypeKind.SignedShort:
return true;
}
return false;
}
}
#endregion
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.