context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Models;
namespace Umbraco.Web.Mvc
{
/// <summary>
/// Redirects to an Umbraco page by Id or Entity
/// </summary>
public class RedirectToUmbracoPageResult : ActionResult
{
private IPublishedContent _publishedContent;
private readonly int _pageId;
private NameValueCollection _queryStringValues;
private readonly UmbracoContext _umbracoContext;
private string _url;
public string Url
{
get
{
if (!_url.IsNullOrWhiteSpace()) return _url;
if (PublishedContent == null)
{
throw new InvalidOperationException(string.Format("Cannot redirect, no entity was found for id {0}", _pageId));
}
var result = _umbracoContext.RoutingContext.UrlProvider.GetUrl(PublishedContent.Id);
if (result != "#")
{
_url = result;
return _url;
}
throw new InvalidOperationException(string.Format("Could not route to entity with id {0}, the NiceUrlProvider could not generate a URL", _pageId));
}
}
public IPublishedContent PublishedContent
{
get
{
if (_publishedContent != null) return _publishedContent;
//need to get the URL for the page
_publishedContent = UmbracoContext.Current.ContentCache.GetById(_pageId);
return _publishedContent;
}
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
public RedirectToUmbracoPageResult(int pageId)
: this(pageId, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryStringValues"></param>
public RedirectToUmbracoPageResult(int pageId, NameValueCollection queryStringValues)
: this(pageId, queryStringValues, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryString"></param>
public RedirectToUmbracoPageResult(int pageId, string queryString)
: this(pageId, queryString, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="publishedContent"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent)
: this(publishedContent, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="queryStringValues"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent, NameValueCollection queryStringValues)
: this(publishedContent, queryStringValues, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="queryString"></param>
/// <param name="queryStringValues"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent, string queryString)
: this(publishedContent, queryString, UmbracoContext.Current)
{
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(int pageId, UmbracoContext umbracoContext)
{
_pageId = pageId;
_umbracoContext = umbracoContext;
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryStringValues"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(int pageId, NameValueCollection queryStringValues, UmbracoContext umbracoContext)
{
_pageId = pageId;
_queryStringValues = queryStringValues;
_umbracoContext = umbracoContext;
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="pageId"></param>
/// <param name="queryString"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(int pageId, string queryString, UmbracoContext umbracoContext)
{
_pageId = pageId;
_queryStringValues = ParseQueryString(queryString);
_umbracoContext = umbracoContext;
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent, UmbracoContext umbracoContext)
{
_publishedContent = publishedContent;
_pageId = publishedContent.Id;
_umbracoContext = umbracoContext;
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="queryStringValues"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent, NameValueCollection queryStringValues, UmbracoContext umbracoContext)
{
_publishedContent = publishedContent;
_pageId = publishedContent.Id;
_queryStringValues = queryStringValues;
_umbracoContext = umbracoContext;
}
/// <summary>
/// Creates a new RedirectToUmbracoResult
/// </summary>
/// <param name="publishedContent"></param>
/// <param name="queryString"></param>
/// <param name="umbracoContext"></param>
public RedirectToUmbracoPageResult(IPublishedContent publishedContent, string queryString, UmbracoContext umbracoContext)
{
_publishedContent = publishedContent;
_pageId = publishedContent.Id;
_queryStringValues = ParseQueryString(queryString);
_umbracoContext = umbracoContext;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
if (context.IsChildAction)
{
throw new InvalidOperationException("Cannot redirect from a Child Action");
}
var destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);
if (_queryStringValues != null && _queryStringValues.Count > 0)
{
destinationUrl = destinationUrl += "?" + string.Join("&",
_queryStringValues.AllKeys.Select(x => x + "=" + HttpUtility.UrlEncode(_queryStringValues[x])));
}
context.Controller.TempData.Keep();
context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);
}
private NameValueCollection ParseQueryString(string queryString)
{
if (!string.IsNullOrEmpty(queryString))
{
return HttpUtility.ParseQueryString(queryString);
}
return null;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class ChangeExtensions : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region class vars
private const string defaultPath = @"de\\fault.path";
private const string exe = ".exe";
private const string cool = ".cool";
#endregion class vars
#region helper funtions
private bool TestChangeExtension(String path, String extension)
{
string expected = "";
int iIndex = path.LastIndexOf('.') ;
if(iIndex > -1)
{
switch(extension)
{
case null:
expected = path.Substring( 0, iIndex );
break;
case "":
expected = path.Substring( 0, iIndex + 1 );
break;
default:
expected = path.Substring( 0, iIndex ) + extension;
break;
}
}
else if(extension != null)
{
expected = path + extension;
}
else
{
expected = path;
}
Log.Comment("Original Path: " + path);
Log.Comment("Expected Path: " + expected);
string result = Path.ChangeExtension(path, extension);
if (result != expected)
{
Log.Exception("Got Path: " + result);
return false;
}
return true;
}
#endregion helper functions
#region Test Cases
[TestMethod]
public MFTestResults NullArgumentPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string strExtension = Path.ChangeExtension(null, exe);
Log.Comment("Expect: null");
if (strExtension != null)
{
Log.Exception("FAIL - Got: " + strExtension);
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults NullArgumentExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestChangeExtension(defaultPath, null))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ZeroLengthPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string strExtension = Path.ChangeExtension("", exe);
Log.Comment("Expect empty result");
if ( strExtension != "")
{
Log.Exception("Got: '" + strExtension + "'");
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ZeroLengthExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestChangeExtension(defaultPath, ""))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults StringEmptyPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string strExtension = Path.ChangeExtension("", exe);
if (strExtension != String.Empty)
{
Log.Exception("Got: '" + strExtension + "'");
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults StringEmptyExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestChangeExtension(defaultPath, string.Empty))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults WhiteSpace()
{
MFTestResults result = MFTestResults.Pass;
try
{
string strExtension = Path.ChangeExtension(" ", exe);
Log.Comment("BUG? - The Desktop has the same behavior, but this is their test case, so don't know right behavior");
Log.Comment("We will wait to hear back from CLR team to decide what the correct behavior is.");
Log.Exception("Expected ArgumentException, got " + strExtension);
result = MFTestResults.KnownFailure;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults InvalidChars()
{
MFTestResults result = MFTestResults.Pass;
foreach (char badChar in Path.InvalidPathChars)
{
try
{
string path = new string(new char[] { badChar, 'b', 'a', 'd', badChar, 'p', 'a', 't', 'h', badChar });
Log.FilteredComment("Testing path: " + path);
string strExtension = Path.ChangeExtension(path, exe);
}
catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); }
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
}
return result;
}
[TestMethod]
public MFTestResults NoExtensionPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = "jabba\\de\\hutt";
if (! TestChangeExtension(path, exe))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults MultiDotPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = "jabba..de..hutt...";
if (!TestChangeExtension(path, exe))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ValidExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = "jabba\\de\\hutt.solo";
if (!TestChangeExtension(path, exe))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults SpecialSymbolPath()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = "foo.bar.fkl;fkds92-509450-4359.213213213@*?2-3203-=210";
if (!TestChangeExtension(path, cool))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults SpecialSymbolExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
string extension = ".$#@$_)+_)!@@!!@##&_$)#_";
if (!TestChangeExtension(defaultPath, extension))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults LongExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
string path = new string('a', 256) + exe;
string extension = "." + new string('b', 256);
string strExtension = Path.ChangeExtension(path, extension);
if (!TestChangeExtension(path, extension))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults OneCharExtension()
{
MFTestResults result = MFTestResults.Pass;
try
{
string extension = ".z";
if (!TestChangeExtension(defaultPath, extension))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( NullArgumentPath, "NullArgumentPath" ),
new MFTestMethod( NullArgumentExtension, "NullArgumentExtension" ),
new MFTestMethod( ZeroLengthPath, "ZeroLengthPath" ),
new MFTestMethod( ZeroLengthExtension, "ZeroLengthExtension" ),
new MFTestMethod( StringEmptyPath, "StringEmptyPath" ),
new MFTestMethod( StringEmptyExtension, "StringEmptyExtension" ),
new MFTestMethod( WhiteSpace, "WhiteSpace" ),
new MFTestMethod( InvalidChars, "InvalidChars" ),
new MFTestMethod( NoExtensionPath, "NoExtensionPath" ),
new MFTestMethod( MultiDotPath, "MultiDotPath" ),
new MFTestMethod( ValidExtension, "ValidExtension" ),
new MFTestMethod( SpecialSymbolPath, "SpecialSymbolPath" ),
new MFTestMethod( SpecialSymbolExtension, "SpecialSymbolExtension" ),
new MFTestMethod( LongExtension, "LongExtension" ),
new MFTestMethod( OneCharExtension, "OneCharExtension" ),
};
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
public class ContainerTest
{
// Test 1: Variable scopes
// Test 1a: Private field
private IList<int> c1a = new List<int> { 1, 2 }; // BAD: private
// Test 1b: protected field
protected IList<int> c1b = new List<int> { 1, 2 }; // GOOD: protected
// Test 1c: public field
public IList<int> c1c = new List<int> { 1, 2 }; // GOOD: public
// Test 1d: internal field
internal IList<int> c1d = new List<int> { 1, 2 }; // BAD: internal
void TestScopes()
{
c1a.Add(1);
c1b.Add(2);
c1c.Add(3);
c1d.Add(4);
// Test 1e: Local variable
IList<int> c1e = new List<int> { 1, 2 }; // BAD: local
c1e.Add(5);
}
// Test 2: Method names
void TestMethodNames()
{
// Test 2a: Writeonly method names
IList<int> c2a = new List<int> { 1, 2 }; // BAD: writeonly methods
c2a.Add(1);
c2a.Clear();
c2a.Insert(1, 2);
c2a.Remove(1);
c2a.RemoveAt(3);
// Test 2b: Read/write method names
IList<int> c2b = new List<int> { 1, 2 }; // GOOD: read method
bool b = c2b.Contains(1);
// Test 2c: Other method names
var c2c = new Stack(); // BAD
c2c.Push(1);
var c2d = new BitArray(10); // BAD
c2d.Set(1, true);
c2d.SetAll(false);
var c2j = new LinkedList<int>(); // BAD
c2j.AddFirst(1);
c2j.AddLast(2);
c2j.RemoveFirst();
c2j.RemoveLast();
}
// Test 3: Variable uses
IList<int> f() { return new List<int>(); }
void f(IList<int> x) { }
IList<int> g()
{
// Returned from function
var c3c = new List<int> { 2, 3, 4 }; // GOOD: returned
c3c.Add(5);
return c3c;
}
IList<int> h
{
get
{
// Returned from property
var c3d = new List<int>(); // GOOD: returned
c3d.Add(1);
return c3d;
}
}
IList<int> this[int i]
{
get
{
// Returned from property
var c3e = new List<int>(); // GOOD: returned
c3e.Add(1);
return c3e;
}
}
void TestAccessTypes()
{
// 3a: Unused
IList<int> c3a = new List<int> { 4, 5 }; // BAD
// 3b: Pass to function
IList<int> c3b = new List<int> { }; // GOOD: used
c3b.Add(1);
f(c3b);
// 3f: Access a property
var c3f = new List<int>(); // GOOD: accessed
c3f.Add(1);
int zero = c3f.Count;
}
// Test 4: Initialization type
private IList<int> c4a; // BAD: even though uninitialized
void TestInitializationTypes()
{
// Test 4a: Uninitialized
c4a.Add(1);
// Test 4b: Constructed from new
var c4b = new List<int>(); // BAD
c4b.Add(1);
// Test 4c: List initialized
var c4c = new List<int> { 2, 3, 4 }; // BAD
c4c.Add(1);
// Test 4d: Constructed from other expression
var c4d = f(); // GOOD
c4d.Add(1);
// Test 4e: In a foreach loop
List<List<string>> c4e = new List<List<string>> { new List<string> { "x" } };
foreach (var c4f in c4e) // GOOD: constructed from elsewehere
c4f.Remove("x");
int x = c4e.Count;
}
// Test 5: Assignment
void TestAssignment()
{
// Assigned from new container
IList<int> c5a; // BAD
c5a = new List<int>();
c5a.Add(1);
// Assigned from something else
IList<int> c5b; // GOOD: from f()
c5b = f();
c5b.Add(1);
// Assigned to something
IList<int> c5c = new List<int>(), c5d; // GOOD: assigned elsewhere
c5c.Add(1);
c5d = c5c;
// Assigned in an expression somewhere
IList<int> c5e = new List<int>(); // BAD: assigned in expr
for (int i = 0; i < 10; c5e = new List<int>(), ++i)
c5e.Add(1);
IList<int> c5f = new List<int>(); // GOOD: assigned in expr
for (int i = 0; i < 10; c5f = null, ++i)
c5f.Add(1);
}
class NonCollection
{
public void Add(int i) { }
}
// Test 6: Collection type
void TestCollections()
{
var c6a = new NonCollection(); // GOOD: not a collection
c6a.Add(1);
var c6b = new ArrayList(); // BAD
c6b.Add(1);
var c6c = new BitArray(32); // BAD
c6c.SetAll(true);
var c6d = new Hashtable(); // BAD
c6d.Add(1, 2);
var c6e = new Queue(); // BAD
c6e.Enqueue(1);
var c6f = new SortedList(); // BAD
c6f.Add(1, 2);
var c6g = new Stack(); // BAD
c6g.Push(1);
var c6h = new Dictionary<int, int>(); // BAD
c6h.Add(1, 2);
var c6i = new HashSet<int>(); // BAD
c6i.Add(1);
var c6j = new LinkedList<int>(); // BAD
c6j.AddFirst(1);
var c6k = new List<int>(); // BAD
c6k.Add(1);
var c6l = new Queue<int>(); // BAD
c6l.Enqueue(1);
var c6m = new SortedDictionary<int, int>(); // BAD
c6m.Add(1, 2);
var c6n = new SortedList<int, int>(); // BAD
c6n.Add(1, 2);
var c6o = new SortedDictionary<int, int>(); // BAD
c6o.Add(1, 2);
var c6p = new SortedSet<int>(); // BAD
c6p.Add(1);
var c6q = new Stack<int>(); // BAD
c6q.Push(1);
ICollection<int> c6u = new List<int>(); // BAD
c6u.Add(1);
IDictionary<int, int> c6v = new Dictionary<int, int>(); // BAD
c6v.Add(1, 2);
IEnumerable<int> c6w = new List<int>(); // GOOD
c6w.GetEnumerator();
IList<int> c6x = new List<int>(); // BAD
c6x.Add(12);
ISet<int> c6y = new HashSet<int>(); // BAD
c6y.Add(1);
}
void TestDynamicAccess()
{
// GOOD: dynamic
dynamic c7a = new List<int>();
c7a.Add(1);
// GOOD: cast to dynamic
var c7b = new List<int>();
c7b.Add(1);
dynamic x = (dynamic)c7b;
// GOOD: passed as param to InvokeMember
var c7c = new List<int>();
var t = typeof(List<int>);
t.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, null, c7c, new Object[] { 1 });
}
IList<int> c8a = new List<int>(); // BAD: no attribute
[Obsolete()]
IList<int> c8b = new List<int>(); // GOOD: has attribute
void TestAttributes()
{
c8a.Add(1);
c8b.Add(2);
}
public static void Main(string[] args)
{
ContainerTest t = new ContainerTest();
}
IEnumerable<IList<string>> TestIndirectInitializations(IList<string>[] stringss)
{
foreach (var strings in stringss)
strings.Add(""); // GOOD
if (stringss[0] is List<String> l)
l.Add(""); // GOOD
switch (stringss[0])
{
case List<String> l2:
l2.Add(""); // GOOD
break;
}
return stringss;
}
void Out(out List<string> strings)
{
strings = new List<string> { "a", "b", "c" };
}
void OutTest()
{
Out(out var strings); // BAD: but allow for now (only C# 7 allows discards)
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 12.20Release
// Tag = $Name$
////////////////////////////////////////////////////////////////////////////////
#endregion
namespace FitFilePreviewer.Decode.Fit.Mesgs
{
/// <summary>
/// Implements the Goal profile message.
/// </summary>
public class GoalMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public GoalMesg() : base((Mesg) Profile.mesgs[Profile.GoalIndex])
{
}
public GoalMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sport field</summary>
/// <returns>Returns nullable Sport enum representing the Sport field</returns>
public Types.Sport? GetSport()
{
object obj = GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
Types.Sport? value = obj == null ? (Types.Sport?)null : (Types.Sport)obj;
return value;
}
/// <summary>
/// Set Sport field</summary>
/// <param name="sport_">Nullable field value to be set</param>
public void SetSport(Types.Sport? sport_)
{
SetFieldValue(0, 0, sport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SubSport field</summary>
/// <returns>Returns nullable SubSport enum representing the SubSport field</returns>
public Types.SubSport? GetSubSport()
{
object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
Types.SubSport? value = obj == null ? (Types.SubSport?)null : (Types.SubSport)obj;
return value;
}
/// <summary>
/// Set SubSport field</summary>
/// <param name="subSport_">Nullable field value to be set</param>
public void SetSubSport(Types.SubSport? subSport_)
{
SetFieldValue(1, 0, subSport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the StartDate field</summary>
/// <returns>Returns DateTime representing the StartDate field</returns>
public Types.DateTime GetStartDate()
{
return TimestampToDateTime((uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set StartDate field</summary>
/// <param name="startDate_">Nullable field value to be set</param>
public void SetStartDate(Types.DateTime startDate_)
{
SetFieldValue(2, 0, startDate_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EndDate field</summary>
/// <returns>Returns DateTime representing the EndDate field</returns>
public Types.DateTime GetEndDate()
{
return TimestampToDateTime((uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set EndDate field</summary>
/// <param name="endDate_">Nullable field value to be set</param>
public void SetEndDate(Types.DateTime endDate_)
{
SetFieldValue(3, 0, endDate_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Type field</summary>
/// <returns>Returns nullable Goal enum representing the Type field</returns>
new public Types.Goal? GetType()
{
object obj = GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
Types.Goal? value = obj == null ? (Types.Goal?)null : (Types.Goal)obj;
return value;
}
/// <summary>
/// Set Type field</summary>
/// <param name="type_">Nullable field value to be set</param>
public void SetType(Types.Goal? type_)
{
SetFieldValue(4, 0, type_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Value field</summary>
/// <returns>Returns nullable uint representing the Value field</returns>
public uint? GetValue()
{
return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Value field</summary>
/// <param name="value_">Nullable field value to be set</param>
public void SetValue(uint? value_)
{
SetFieldValue(5, 0, value_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Repeat field</summary>
/// <returns>Returns nullable Bool enum representing the Repeat field</returns>
public Types.Bool? GetRepeat()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
Types.Bool? value = obj == null ? (Types.Bool?)null : (Types.Bool)obj;
return value;
}
/// <summary>
/// Set Repeat field</summary>
/// <param name="repeat_">Nullable field value to be set</param>
public void SetRepeat(Types.Bool? repeat_)
{
SetFieldValue(6, 0, repeat_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TargetValue field</summary>
/// <returns>Returns nullable uint representing the TargetValue field</returns>
public uint? GetTargetValue()
{
return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TargetValue field</summary>
/// <param name="targetValue_">Nullable field value to be set</param>
public void SetTargetValue(uint? targetValue_)
{
SetFieldValue(7, 0, targetValue_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Recurrence field</summary>
/// <returns>Returns nullable GoalRecurrence enum representing the Recurrence field</returns>
public Types.GoalRecurrence? GetRecurrence()
{
object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
Types.GoalRecurrence? value = obj == null ? (Types.GoalRecurrence?)null : (Types.GoalRecurrence)obj;
return value;
}
/// <summary>
/// Set Recurrence field</summary>
/// <param name="recurrence_">Nullable field value to be set</param>
public void SetRecurrence(Types.GoalRecurrence? recurrence_)
{
SetFieldValue(8, 0, recurrence_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RecurrenceValue field</summary>
/// <returns>Returns nullable ushort representing the RecurrenceValue field</returns>
public ushort? GetRecurrenceValue()
{
return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RecurrenceValue field</summary>
/// <param name="recurrenceValue_">Nullable field value to be set</param>
public void SetRecurrenceValue(ushort? recurrenceValue_)
{
SetFieldValue(9, 0, recurrenceValue_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Enabled field</summary>
/// <returns>Returns nullable Bool enum representing the Enabled field</returns>
public Types.Bool? GetEnabled()
{
object obj = GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
Types.Bool? value = obj == null ? (Types.Bool?)null : (Types.Bool)obj;
return value;
}
/// <summary>
/// Set Enabled field</summary>
/// <param name="enabled_">Nullable field value to be set</param>
public void SetEnabled(Types.Bool? enabled_)
{
SetFieldValue(10, 0, enabled_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Gui;
using FlatRedBall.Input;
using Side = FlatRedBall.Math.Collision.CollisionEnumerations.Side3D;
using FlatRedBall.Graphics;
#if FRB_MDX
using Microsoft.DirectX;
using System.Drawing;
#else //if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#endif
namespace FlatRedBall.Math.Geometry
{
public class AxisAlignedCube : PositionedObject, IScalable3D, IScalable, IEquatable<AxisAlignedCube>
#if FRB_XNA
, IMouseOver
#endif
{
#region Fields
internal float mScaleX = 1;
internal float mScaleY = 1;
internal float mScaleZ = 1;
float mScaleXVelocity;
float mScaleYVelocity;
float mScaleZVelocity;
bool mVisible;
float mBoundingRadius;
internal Vector3 mLastMoveCollisionReposition;
public Color mColor = Color.White;
internal Layer mLayerBelongingTo;
#endregion
#region Properties
public float ScaleX
{
get { return mScaleX; }
set
{
#if DEBUG
if (value < 0)
{
throw new ArgumentException("Cannot set a negative scale value. This will cause collision to behave weird.");
}
#endif
mScaleX = value;
mBoundingRadius = (float)(System.Math.Sqrt((mScaleX * mScaleX) + (mScaleY * mScaleY) + (mScaleZ * mScaleZ)));
}
}
public float ScaleY
{
get { return mScaleY; }
set
{
#if DEBUG
if (value < 0)
{
throw new ArgumentException("Cannot set a negative scale value. This will cause collision to behave weird.");
}
#endif
mScaleY = value;
mBoundingRadius = (float)(System.Math.Sqrt((mScaleX * mScaleX) + (mScaleY * mScaleY) + (mScaleZ * mScaleZ)));
}
}
public float ScaleZ
{
get { return mScaleZ; }
set
{
#if DEBUG
if (value < 0)
{
throw new ArgumentException("Cannot set a negative scale value. This will cause collision to behave weird.");
}
#endif
mScaleZ = value;
mBoundingRadius = (float)(System.Math.Sqrt((mScaleX * mScaleX) + (mScaleY * mScaleY) + (mScaleZ * mScaleZ)));
}
}
public float ScaleXVelocity
{
get { return mScaleXVelocity; }
set { mScaleXVelocity = value; }
}
public float ScaleYVelocity
{
get { return mScaleYVelocity; }
set { mScaleYVelocity = value; }
}
public float ScaleZVelocity
{
get { return mScaleZVelocity; }
set { mScaleZVelocity = value; }
}
public bool Visible
{
get { return mVisible; }
set
{
if (value != mVisible)
{
mVisible = value;
ShapeManager.NotifyOfVisibilityChange(this);
}
}
}
public float BoundingRadius
{
get { return mBoundingRadius; }
}
public Color Color
{
set
{
mColor = value;
}
get
{
return mColor;
}
}
public Vector3 LastMoveCollisionReposition
{
get { return mLastMoveCollisionReposition; }
}
#endregion
#region Methods
#region Constructor
public AxisAlignedCube()
{ }
#endregion
#region Public Methods
public AxisAlignedCube Clone()
{
AxisAlignedCube clonedCube = this.Clone<AxisAlignedCube>();
clonedCube.mVisible = false;
clonedCube.mLayerBelongingTo = null;
return clonedCube;
}
public override void TimedActivity(float secondDifference,
double secondDifferenceSquaredDividedByTwo, float secondsPassedLastFrame)
{
base.TimedActivity(secondDifference, secondDifferenceSquaredDividedByTwo, secondsPassedLastFrame);
mScaleX += (float)(mScaleXVelocity * secondDifference);
mScaleY += (float)(mScaleYVelocity * secondDifference);
ScaleZ += (float)(mScaleZVelocity * secondDifference); // to force recalculation of radius
}
#if FRB_XNA
public BoundingBox AsBoundingBox()
{
BoundingBox boundingBox = new BoundingBox(
new Vector3(Position.X - mScaleX, Position.Y - mScaleY, Position.Z - mScaleZ),
new Vector3(Position.X + mScaleX, Position.Y + mScaleY, Position.Z + mScaleZ));
return boundingBox;
}
#endif
#region CollideAgainst
public bool CollideAgainst(AxisAlignedCube cube)
{
UpdateDependencies(TimeManager.CurrentTime);
cube.UpdateDependencies(TimeManager.CurrentTime);
return (X - mScaleX < cube.X + cube.mScaleX &&
X + mScaleX > cube.X - cube.mScaleX &&
Y - mScaleY < cube.Y + cube.mScaleY &&
Y + mScaleY > cube.Y - cube.mScaleY &&
Z - mScaleZ < cube.Z + cube.mScaleZ &&
Z + mScaleZ > cube.Z - cube.mScaleZ);
}
public bool CollideAgainstMove(AxisAlignedCube other, float thisMass, float otherMass)
{
if (CollideAgainst(other))
{
Side side = Side.Left; // set it to left first
float smallest = System.Math.Abs(X + mScaleX - (other.X - other.mScaleX));
float currentDistance = System.Math.Abs(X - mScaleX - (other.X + other.mScaleX));
if (currentDistance < smallest) { smallest = currentDistance; side = Side.Right; }
currentDistance = Y - mScaleY - (other.Y + other.mScaleY);
if (currentDistance < 0) currentDistance *= -1;
if (currentDistance < smallest) { smallest = currentDistance; side = Side.Top; }
currentDistance = Y + mScaleY - (other.Y - other.mScaleY);
if (currentDistance < 0) currentDistance *= -1;
if (currentDistance < smallest) { smallest = currentDistance; side = Side.Bottom; }
currentDistance = Z - mScaleZ - (other.Z + other.mScaleZ);
if (currentDistance < 0) currentDistance *= -1;
if (currentDistance < smallest) { smallest = currentDistance; side = Side.Front; }
currentDistance = Z + mScaleZ - (other.Z - other.mScaleZ);
if (currentDistance < 0) currentDistance *= -1;
if (currentDistance < smallest) { smallest = currentDistance; side = Side.Back; }
float amountToMoveThis = otherMass / (thisMass + otherMass);
Vector3 movementVector = new Vector3();
switch (side)
{
case Side.Left: movementVector.X = other.X - other.mScaleX - mScaleX - X; break;
case Side.Right: movementVector.X = other.X + other.mScaleX + mScaleX - X; break;
case Side.Top: movementVector.Y = other.Y + other.mScaleY + mScaleY - Y; break;
case Side.Bottom: movementVector.Y = other.Y - other.mScaleY - mScaleY - Y; break;
case Side.Front: movementVector.Z = other.Z + other.mScaleZ + mScaleZ - Z; break;
case Side.Back: movementVector.Z = other.Z - other.mScaleZ - mScaleZ - Z; break;
}
//Should this be a Vector3 instead?
mLastMoveCollisionReposition.X = movementVector.X * amountToMoveThis;
mLastMoveCollisionReposition.Y = movementVector.Y * amountToMoveThis;
mLastMoveCollisionReposition.Z = movementVector.Z * amountToMoveThis;
TopParent.X += mLastMoveCollisionReposition.X;
TopParent.Y += mLastMoveCollisionReposition.Y;
TopParent.Z += mLastMoveCollisionReposition.Z;
other.mLastMoveCollisionReposition.X = -movementVector.X * (1 - amountToMoveThis);
other.mLastMoveCollisionReposition.Y = -movementVector.Y * (1 - amountToMoveThis);
other.mLastMoveCollisionReposition.Z = -movementVector.Z * (1 - amountToMoveThis);
other.TopParent.X += other.mLastMoveCollisionReposition.X;
other.TopParent.Y += other.mLastMoveCollisionReposition.Y;
other.TopParent.Z += other.mLastMoveCollisionReposition.Z;
ForceUpdateDependencies();
other.ForceUpdateDependencies();
return true;
}
return false;
}
public bool CollideAgainst(Sphere sphere)
{
return sphere.CollideAgainst(this);
}
public bool CollideAgainstMove(Sphere sphere, float thisMass, float otherMass)
{
return sphere.CollideAgainstMove(this, otherMass, thisMass);
}
public bool CollideAgainstBounce(AxisAlignedCube other, float thisMass, float otherMass, float elasticity)
{
if (this.CollideAgainstMove(other, thisMass, otherMass))
{
// Get the relative velocity of this circle to the argument circle:
Vector3 relativeVelocity = new Vector3(
this.TopParent.XVelocity - other.TopParent.XVelocity,
this.TopParent.YVelocity - other.TopParent.YVelocity,
this.TopParent.ZVelocity - other.TopParent.ZVelocity);
Vector3 reposition = mLastMoveCollisionReposition;
if (otherMass == 0)
{
reposition = -other.mLastMoveCollisionReposition;
}
#if FRB_MDX
float velocityNormalDotResult = Vector3.Dot( relativeVelocity, reposition);
#else
float velocityNormalDotResult;
Vector3.Dot(ref relativeVelocity, ref reposition, out velocityNormalDotResult);
#endif
if (velocityNormalDotResult >= 0)
{
return true;
}
#if FRB_MDX
//Vector2 tangentVector = new Vector2((float)mLastCollisionTangent.X, (float)mLastCollisionTangent.Y);
// Perform the bounce if the relative velocity and the tangent are the opposite direction.
Vector3 reverseNormal = -Vector3.Normalize(LastMoveCollisionReposition);
float length = Vector3.Dot(relativeVelocity, reverseNormal);
Vector3 velocityOnNormal = Vector3.Multiply(reverseNormal, length);
#else
Vector3 reverseNormal = -reposition;
reverseNormal.Normalize();
float length = Vector3.Dot(relativeVelocity, reverseNormal);
Vector3 velocityOnNormal;
Vector3.Multiply(ref reverseNormal, length, out velocityOnNormal);
#endif
other.TopParent.Velocity.X += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.X;
other.TopParent.Velocity.Y += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.Y;
other.TopParent.Velocity.Z += (1 + elasticity) * thisMass / (thisMass + otherMass) * velocityOnNormal.Z;
this.TopParent.Velocity.X -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.X;
this.TopParent.Velocity.Y -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.Y;
this.TopParent.Velocity.Z -= (1 + elasticity) * otherMass / (thisMass + otherMass) * velocityOnNormal.Z;
return true;
}
return false;
}
public bool CollideAgainstBounce(Sphere sphere, float thisMass, float otherMass, float elasticity)
{
return sphere.CollideAgainstBounce(this, otherMass, thisMass, elasticity);
}
#endregion
public bool IsPointInside(Vector3 absolutePosition)
{
return absolutePosition.X > this.Position.X - this.mScaleX &&
absolutePosition.X < this.Position.X + this.mScaleX &&
absolutePosition.Y > this.Position.Y - this.mScaleY &&
absolutePosition.Y < this.Position.Y + this.mScaleY &&
absolutePosition.Z > this.Position.Z - this.mScaleZ &&
absolutePosition.Z < this.Position.Z + this.mScaleZ;
}
#endregion
#endregion
#region IEquatable<AxisAlignedCube> Members
public bool Equals(AxisAlignedCube other)
{
return this == other;
}
#endregion
#region IMouseOver Implementation
#if FRB_XNA
public bool IsMouseOver(Cursor cursor)
{
return cursor.IsOn3D(this);
}
public bool IsMouseOver(Cursor cursor, Layer layer)
{
return cursor.IsOn3D(this, layer);
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using ParatureSDK.Fields;
using ParatureSDK.ParaObjects.EntityReferences;
using System.Text;
namespace ParatureSDK.ParaObjects
{
/// <summary>
/// Holds all the properties of the Download module.
/// </summary>
public class Download : ParaEntity, IMutableEntity
{
// Specific properties for this module
/// <summary>
/// An attachment object holds the information about any attachment.
/// </summary>
public Attachment Attachment
{
get
{
return GetFieldValue<Attachment>("Attachment");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Attachment");
if (field == null)
{
field = new StaticField()
{
Name = "Attachment",
IgnoreSerializeXml = true,
DataType = "entity"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public DateTime Date_Created
{
get
{
return GetFieldValue<DateTime>("Date_Created");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Date_Created");
if (field == null)
{
field = new StaticField()
{
Name = "Date_Created",
FieldType = "usdate",
DataType = "date"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public DateTime Date_Updated
{
get
{
return GetFieldValue<DateTime>("Date_Updated");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Date_Updated");
if (field == null)
{
field = new StaticField()
{
Name = "Date_Updated",
FieldType = "usdate",
DataType = "date"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// The description of the download.
/// </summary>
public string Description
{
get
{
return GetFieldValue<string>("Description");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Description");
if (field == null)
{
field = new StaticField()
{
Name = "Description",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// In case this download consists of an external link, instead of a file, this property will be populated.
/// Please make sure, when you use this property (in case of a create/update of a download)
/// that the Guid property is set to empty, as only one of these two properties must be filled.
/// </summary>
public string External_Link
{
get
{
return GetFieldValue<string>("External_Link");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "External_Link");
if (field == null)
{
field = new StaticField()
{
Name = "External_Link",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public bool MultipleFolders
{
get
{
return GetFieldValue<bool>("MultipleFolders");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "MultipleFolders");
if (field == null)
{
field = new StaticField()
{
Name = "MultipleFolders",
IgnoreSerializeXml = true,
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// The list of folders under which the download is listed.
/// In certain configurations, there may only be 1 folder allowed.
/// Check the "MultipleFolders" property to see whether more than one folder is allowed.
/// If extra folders are added when only one is allowed, the first in the list will sent
/// </summary>
public List<DownloadFolder> Folders
{
get
{
return GetFieldValue<List<DownloadFolder>>("Folders");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Folders");
if (field == null)
{
field = new StaticField()
{
Name = "Folders",
FieldType = "entitymultiple",
DataType = "entity"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// If the download consists of a file that has been uploaded, this would be the GUID of the file.
/// Please make sure, when you use this property (in case of a create/update of a download)
/// that the ExternalLink property is set to empty, as only one of these two properties must be filled.
/// </summary>
public string Guid
{
get
{
return GetFieldValue<string>("Guid");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Guid");
if (field == null)
{
field = new StaticField()
{
Name = "Guid",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// List of Sla type objects. These SLAs are the ones allowed to see this download.
/// </summary>
public List<Sla> Permissions
{
get
{
return GetFieldValue<List<Sla>>("Permissions");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Permissions");
if (field == null)
{
field = new StaticField()
{
Name = "Permissions",
FieldType = "entitymultiple",
DataType = "entity"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// The name of the download.
/// </summary>
public string Name
{
get
{
return GetFieldValue<string>("Name");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Name");
if (field == null)
{
field = new StaticField()
{
Name = "Name",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// List of products that are linked to this download. In case your config uses this feature.
/// </summary>
public List<Product> Products
{
get
{
return GetFieldValue<List<Product>>("Products");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Products");
if (field == null)
{
field = new StaticField()
{
Name = "Products",
FieldType = "entitymultiple",
DataType = "entity"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// Whether the download is published or not.
/// </summary>
public bool? Published
{
get
{
return GetFieldValue<bool?>("Published");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Published");
if (field == null)
{
field = new StaticField()
{
Name = "Published",
FieldType = "checkbox",
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public string Title
{
get
{
return GetFieldValue<string>("Title");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Title");
if (field == null)
{
field = new StaticField()
{
Name = "Title",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public bool? Visible
{
get
{
return GetFieldValue<bool?>("Visible");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Visible");
if (field == null)
{
field = new StaticField()
{
Name = "Visible",
FieldType = "checkbox",
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// File extension
/// </summary>
[XmlElement("Ext")]
public string Extension
{
get
{
return GetFieldValue<string>("Ext");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Ext");
if (field == null)
{
field = new StaticField()
{
Name = "Ext",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public Int32? Portal_Search_Weight
{
get
{
return GetFieldValue<Int32>("Portal_Search_Weight");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Portal_Search_Weight");
if (field == null)
{
field = new StaticField()
{
Name = "Portal_Search_Weight",
FieldType = "int",
DataType = "int"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public Int32? Desk_Search_Weight
{
get
{
return GetFieldValue<Int32>("Desk_Search_Weight");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Desk_Search_Weight");
if (field == null)
{
field = new StaticField()
{
Name = "Desk_Search_Weight",
FieldType = "int",
DataType = "int"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public bool? Hide_On_Portal
{
get
{
return GetFieldValue<bool>("Hide_On_Portal");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Hide_On_Portal");
if (field == null)
{
field = new StaticField()
{
Name = "Hide_On_Portal",
FieldType = "checkbox",
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public bool? Is_Portal_Search_Pinned
{
get
{
return GetFieldValue<bool>("Is_Portal_Search_Pinned");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Is_Portal_Search_Pinned");
if (field == null)
{
field = new StaticField()
{
Name = "Is_Portal_Search_Pinned",
FieldType = "checkbox",
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public bool? Is_Desk_Search_Pinned
{
get
{
return GetFieldValue<bool>("Is_Desk_Search_Pinned");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Is_Desk_Search_Pinned");
if (field == null)
{
field = new StaticField()
{
Name = "Is_Desk_Search_Pinned",
FieldType = "checkbox",
DataType = "boolean"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
public string Language
{
get
{
return GetFieldValue<string>("Language");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Language");
if (field == null)
{
field = new StaticField()
{
Name = "Language",
FieldType = "text",
DataType = "string"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// Certain configuration use the End User License Agreement (EULA). this controls what Eula would
/// be associated with this download.
/// </summary>
public EulaReference Eula
{
get
{
return GetFieldValue<EulaReference>("Eula");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "Eula");
if (field == null)
{
field = new StaticField()
{
Name = "Eula",
FieldType = "entity",
DataType = "entity"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// Number of times the files where updated.
/// </summary>
public Int64 File_Hits
{
get
{
return GetFieldValue<Int64>("File_Hits");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "File_Hits");
if (field == null)
{
field = new StaticField()
{
Name = "File_Hits",
FieldType = "int",
DataType = "int"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// Size of the file.
/// </summary>
public Int64 File_Size
{
get
{
return GetFieldValue<Int64>("File_Size");
}
set
{
var field = StaticFields.FirstOrDefault(f => f.Name == "File_Size");
if (field == null)
{
field = new StaticField()
{
Name = "File_Size",
FieldType = "int",
DataType = "int"
};
StaticFields.Add(field);
}
field.Value = value;
}
}
/// <summary>
/// Uploads a file to the Parature system, from a standard System.Net.Mail.Attachment object, in case you use this from an email.
/// </summary>
/// <param name="EmailAttachment">
/// The email attachment to upload.
/// </param>
[Obsolete("To be removed in favor of Download.AddAttachment(ParaService, System.Net.Mail.Attachment) in the next major revision.", false)]
public void AttachmentsAdd(ParaCredentials paracredentials, System.Net.Mail.Attachment EmailAttachment)
{
Attachment = ApiHandler.Download.DownloadUploadFile(paracredentials, EmailAttachment);
Guid = Attachment.Guid;
}
/// <summary>
/// Uploads a file to the Parature system, from a standard System.Net.Mail.Attachment object, in case you use this from an email.
/// </summary>
/// <param name="EmailAttachment">
/// The email attachment to upload.
/// </param>
public void AddAttachment(ParaService service, System.Net.Mail.Attachment EmailAttachment)
{
Attachment = service.UploadFile<Download>(EmailAttachment);
Guid = Attachment.Guid;
}
/// <summary>
/// Uploads the file to the current Download.
/// The file will also be added to the current Downloads's Guid.
/// </summary>
/// <param name="Attachment">
/// The binary Byte array of the file you would like to upload.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
///
///</param>
[Obsolete("To be removed in favor of Download.AddAttachment(ParaService, byte[], string, string) in the next major revision.", false)]
public void AttachmentsAdd(ParaCredentials paracredentials, Byte[] Attachment, string contentType, string FileName)
{
this.Attachment = ApiHandler.Download.DownloadUploadFile(paracredentials, Attachment, contentType, FileName);
Guid = this.Attachment.Guid;
}
/// <summary>
/// Uploads the file to the current Download.
/// The file will also be added to the current Downloads's Guid.
/// </summary>
/// <param name="Attachment">
/// The binary Byte array of the file you would like to upload.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
///
///</param>
public void AddAttachment(ParaService service, Byte[] attachment, string contentType, string fileName)
{
this.Attachment = service.UploadFile<Download>(attachment, contentType, fileName);
Guid = this.Attachment.Guid;
}
/// <summary>
/// Uploads a text based file to the current Download. You need to pass a string, and the mime type of a text based file (html, text, etc...).
/// </summary>
/// <param name="text">
/// The content of the text based file.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
/// The name you woule like the attachment to have.
///</param>
[Obsolete("To be removed in favor of Download.AddAttachment(ParaService, string, string, string) in the next major revision.", false)]
public void AttachmentsAdd(ParaCredentials paracredentials, string text, string contentType, string FileName)
{
Attachment = ApiHandler.Download.DownloadUploadFile(paracredentials, text, contentType, FileName);
Guid = Attachment.Guid;
}
/// <summary>
/// Uploads a text based file to the current Download. You need to pass a string, and the mime type of a text based file (html, text, etc...).
/// </summary>
/// <param name="text">
/// The content of the text based file.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
/// The name you woule like the attachment to have.
///</param>
public void AddAttachment(ParaService service, string text, string contentType, string fileName)
{
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(text);
Attachment = service.UploadFile<Download>(bytes, contentType, fileName);
Guid = Attachment.Guid;
}
/// <summary>
/// Updates the current download attachment with a text based file. You need to pass a string, and the mime type of a text based file (html, text, etc...).
/// </summary>
/// <param name="text">
/// The content of the text based file.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
/// The name you woule like the attachment to have.
///</param>
[Obsolete("To be removed in favor of Download.UpdateAttachment(ParaService, string, string, string) in the next major revision.", false)]
public void AttachmentsUpdate(ParaCredentials paracredentials, string text, string contentType, string FileName)
{
Attachment = ApiHandler.Download.DownloadUploadFile(paracredentials, text, contentType, FileName);
Guid = Attachment.Guid;
Name = FileName;
}
/// <summary>
/// Updates the current download attachment with a text based file. You need to pass a string, and the mime type of a text based file (html, text, etc...).
/// </summary>
/// <param name="text">
/// The content of the text based file.
///</param>
/// <param name="paracredentials">
/// The parature credentials class for the APIs.
/// </param>
/// <param name="contentType">
/// The type of content being uploaded, you have to make sure this is the right text.
/// </param>
/// <param name="FileName">
/// The name you woule like the attachment to have.
///</param>
public void UpdateAttachment(ParaService service, string text, string contentType, string fileName)
{
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(text);
Attachment = service.UploadFile<Download>(bytes, contentType, fileName);
Guid = Attachment.Guid;
Name = fileName;
}
/// <summary>
/// If you have a download file and would like to replace the file, use this method. It will actually delete
/// the existing attachment, and then add a new one to replace it.
/// </summary>
[Obsolete("To be removed in favor of Download.UpdateAttachment(ParaService, byte[], string, string) in the next major revision.", false)]
public void AttachmentsUpdate(ParaCredentials paracredentials, Byte[] Attachment, string contentType, string FileName)
{
this.Attachment = ApiHandler.Download.DownloadUploadFile(paracredentials, Attachment, contentType, FileName);
Guid = this.Attachment.Guid;
Name = FileName;
}
/// <summary>
/// If you have a download file and would like to replace the file, use this method. It will actually delete
/// the existing attachment, and then add a new one to replace it.
/// </summary>
public void UpdateAttachment(ParaService service, byte[] attachment, string contentType, string fileName)
{
this.Attachment = service.UploadFile<Download>(attachment, contentType, fileName);
Guid = this.Attachment.Guid;
Name = fileName;
}
public Download()
{
}
/// <summary>
///
/// </summary>
/// <param name="allowMultipleFolders">True if Multiple Folders is configured</param>
public Download(bool allowMultipleFolders)
{
MultipleFolders = allowMultipleFolders;
}
public Download(Download download)
: base(download)
{
Id = download.Id;
Date_Created = download.Date_Created;
Date_Updated = download.Date_Updated;
Description = download.Description;
External_Link = download.External_Link;
MultipleFolders = download.MultipleFolders;
Folders = download.Folders;
Guid = download.Guid;
Permissions = new List<Sla>(download.Permissions);
Name = download.Name;
Products = new List<Product>(download.Products);
Published = download.Published;
Title = download.Title;
Visible = download.Visible;
Eula = new EulaReference();
Eula.Eula = download.Eula.Eula;
File_Hits = download.File_Hits;
File_Size = download.File_Size;
}
public override string GetReadableName()
{
return Title;
}
}
}
| |
// 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.ComponentModel.DataAnnotations
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class AssociationAttribute : System.Attribute
{
public AssociationAttribute(string name, string thisKey, string otherKey) { }
public bool IsForeignKey { get { return default(bool); } set { } }
public string Name { get { return default(string); } }
public string OtherKey { get { return default(string); } }
public System.Collections.Generic.IEnumerable<string> OtherKeyMembers { get { return default(System.Collections.Generic.IEnumerable<string>); } }
public string ThisKey { get { return default(string); } }
public System.Collections.Generic.IEnumerable<string> ThisKeyMembers { get { return default(System.Collections.Generic.IEnumerable<string>); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple = false)]
public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CompareAttribute(string otherProperty) { }
public string OtherProperty { get { return default(string); } }
public string OtherPropertyDisplayName { get { return default(string); } }
public override bool RequiresValidationContext { get { return default(bool); } }
public override string FormatErrorMessage(string name) { return default(string); }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class ConcurrencyCheckAttribute : System.Attribute
{
public ConcurrencyCheckAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public CreditCardAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2500), AllowMultiple = true)]
public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CustomValidationAttribute(System.Type validatorType, string method) { }
public string Method { get { return default(string); } }
public System.Type ValidatorType { get { return default(System.Type); } }
public override string FormatErrorMessage(string name) { return default(string); }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
}
public enum DataType
{
CreditCard = 14,
Currency = 6,
Custom = 0,
Date = 2,
DateTime = 1,
Duration = 4,
EmailAddress = 10,
Html = 8,
ImageUrl = 13,
MultilineText = 9,
Password = 11,
PhoneNumber = 5,
PostalCode = 15,
Text = 7,
Time = 3,
Upload = 16,
Url = 12,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { }
public DataTypeAttribute(string customDataType) { }
public string CustomDataType { get { return default(string); } }
public System.ComponentModel.DataAnnotations.DataType DataType { get { return default(System.ComponentModel.DataAnnotations.DataType); } }
public System.ComponentModel.DataAnnotations.DisplayFormatAttribute DisplayFormat { get { return default(System.ComponentModel.DataAnnotations.DisplayFormatAttribute); } protected set { } }
public virtual string GetDataTypeName() { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class DisplayAttribute : System.Attribute
{
public DisplayAttribute() { }
public bool AutoGenerateField { get { return default(bool); } set { } }
public bool AutoGenerateFilter { get { return default(bool); } set { } }
public string Description { get { return default(string); } set { } }
public string GroupName { get { return default(string); } set { } }
public string Name { get { return default(string); } set { } }
public int Order { get { return default(int); } set { } }
public string Prompt { get { return default(string); } set { } }
public System.Type ResourceType { get { return default(System.Type); } set { } }
public string ShortName { get { return default(string); } set { } }
public System.Nullable<bool> GetAutoGenerateField() { return default(System.Nullable<bool>); }
public System.Nullable<bool> GetAutoGenerateFilter() { return default(System.Nullable<bool>); }
public string GetDescription() { return default(string); }
public string GetGroupName() { return default(string); }
public string GetName() { return default(string); }
public System.Nullable<int> GetOrder() { return default(System.Nullable<int>); }
public string GetPrompt() { return default(string); }
public string GetShortName() { return default(string); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = true, AllowMultiple = false)]
public partial class DisplayColumnAttribute : System.Attribute
{
public DisplayColumnAttribute(string displayColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) { }
public string DisplayColumn { get { return default(string); } }
public string SortColumn { get { return default(string); } }
public bool SortDescending { get { return default(bool); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DisplayFormatAttribute : System.Attribute
{
public DisplayFormatAttribute() { }
public bool ApplyFormatInEditMode { get { return default(bool); } set { } }
public bool ConvertEmptyStringToNull { get { return default(bool); } set { } }
public string DataFormatString { get { return default(string); } set { } }
public bool HtmlEncode { get { return default(bool); } set { } }
public string NullDisplayText { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class EditableAttribute : System.Attribute
{
public EditableAttribute(bool allowEdit) { }
public bool AllowEdit { get { return default(bool); } }
public bool AllowInitialValue { get { return default(bool); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EmailAddressAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EnumDataTypeAttribute(System.Type enumType) : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public System.Type EnumType { get { return default(System.Type); } }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public FileExtensionsAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public string Extensions { get { return default(string); } set { } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class FilterUIHintAttribute : System.Attribute
{
public FilterUIHintAttribute(string filterUIHint) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { return default(System.Collections.Generic.IDictionary<string, object>); } }
public string FilterUIHint { get { return default(string); } }
public string PresentationLayer { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
public partial interface IValidatableObject
{
System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class KeyAttribute : System.Attribute
{
public KeyAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MaxLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MaxLengthAttribute() { }
public MaxLengthAttribute(int length) { }
public int Length { get { return default(int); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MinLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MinLengthAttribute(int length) { }
public int Length { get { return default(int); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class PhoneAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public PhoneAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RangeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RangeAttribute(double minimum, double maximum) { }
public RangeAttribute(int minimum, int maximum) { }
public RangeAttribute(System.Type type, string minimum, string maximum) { }
public object Maximum { get { return default(object); } }
public object Minimum { get { return default(object); } }
public System.Type OperandType { get { return default(System.Type); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RegularExpressionAttribute(string pattern) { }
public int MatchTimeoutInMilliseconds { get { return default(int); } set { } }
public string Pattern { get { return default(string); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RequiredAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RequiredAttribute() { }
public bool AllowEmptyStrings { get { return default(bool); } set { } }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ScaffoldColumnAttribute : System.Attribute
{
public ScaffoldColumnAttribute(bool scaffold) { }
public bool Scaffold { get { return default(bool); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class StringLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public StringLengthAttribute(int maximumLength) { }
public int MaximumLength { get { return default(int); } }
public int MinimumLength { get { return default(int); } set { } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class TimestampAttribute : System.Attribute
{
public TimestampAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = true)]
public partial class UIHintAttribute : System.Attribute
{
public UIHintAttribute(string uiHint) { }
public UIHintAttribute(string uiHint, string presentationLayer) { }
public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { return default(System.Collections.Generic.IDictionary<string, object>); } }
public string PresentationLayer { get { return default(string); } }
public string UIHint { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class UrlAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public UrlAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
public abstract partial class ValidationAttribute : System.Attribute
{
protected ValidationAttribute() { }
protected ValidationAttribute(System.Func<string> errorMessageAccessor) { }
protected ValidationAttribute(string errorMessage) { }
public string ErrorMessage { get { return default(string); } set { } }
public string ErrorMessageResourceName { get { return default(string); } set { } }
public System.Type ErrorMessageResourceType { get { return default(System.Type); } set { } }
protected string ErrorMessageString { get { return default(string); } }
public virtual bool RequiresValidationContext { get { return default(bool); } }
public virtual string FormatErrorMessage(string name) { return default(string); }
public System.ComponentModel.DataAnnotations.ValidationResult GetValidationResult(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
public virtual bool IsValid(object value) { return default(bool); }
protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
public void Validate(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public void Validate(object value, string name) { }
}
public sealed partial class ValidationContext : System.IServiceProvider
{
public ValidationContext(object instance) { }
public ValidationContext(object instance, System.Collections.Generic.IDictionary<object, object> items) { }
public ValidationContext(object instance, System.IServiceProvider serviceProvider, System.Collections.Generic.IDictionary<object, object> items) { }
public string DisplayName { get { return default(string); } set { } }
public System.Collections.Generic.IDictionary<object, object> Items { get { return default(System.Collections.Generic.IDictionary<object, object>); } }
public string MemberName { get { return default(string); } set { } }
public object ObjectInstance { get { return default(object); } }
public System.Type ObjectType { get { return default(System.Type); } }
public object GetService(System.Type serviceType) { return default(object); }
public void InitializeServiceProvider(System.Func<System.Type, object> serviceProvider) { }
}
public partial class ValidationException : System.Exception
{
public ValidationException() { }
public ValidationException(System.ComponentModel.DataAnnotations.ValidationResult validationResult, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message) { }
public ValidationException(string errorMessage, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message, System.Exception innerException) { }
public System.ComponentModel.DataAnnotations.ValidationAttribute ValidationAttribute { get { return default(System.ComponentModel.DataAnnotations.ValidationAttribute); } }
public System.ComponentModel.DataAnnotations.ValidationResult ValidationResult { get { return default(System.ComponentModel.DataAnnotations.ValidationResult); } }
public object Value { get { return default(object); } }
}
public partial class ValidationResult
{
public static readonly System.ComponentModel.DataAnnotations.ValidationResult Success;
protected ValidationResult(System.ComponentModel.DataAnnotations.ValidationResult validationResult) { }
public ValidationResult(string errorMessage) { }
public ValidationResult(string errorMessage, System.Collections.Generic.IEnumerable<string> memberNames) { }
public string ErrorMessage { get { return default(string); } set { } }
public System.Collections.Generic.IEnumerable<string> MemberNames { get { return default(System.Collections.Generic.IEnumerable<string>); } }
public override string ToString() { return default(string); }
}
public static partial class Validator
{
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { return default(bool); }
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, bool validateAllProperties) { return default(bool); }
public static bool TryValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { return default(bool); }
public static bool TryValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { return default(bool); }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, bool validateAllProperties) { }
public static void ValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { }
}
}
namespace System.ComponentModel.DataAnnotations.Schema
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ColumnAttribute : System.Attribute
{
public ColumnAttribute() { }
public ColumnAttribute(string name) { }
public string Name { get { return default(string); } }
public int Order { get { return default(int); } set { } }
public string TypeName { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class ComplexTypeAttribute : System.Attribute
{
public ComplexTypeAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DatabaseGeneratedAttribute : System.Attribute
{
public DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption databaseGeneratedOption) { }
public System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption DatabaseGeneratedOption { get { return default(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption); } }
}
public enum DatabaseGeneratedOption
{
Computed = 2,
Identity = 1,
None = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ForeignKeyAttribute : System.Attribute
{
public ForeignKeyAttribute(string name) { }
public string Name { get { return default(string); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class InversePropertyAttribute : System.Attribute
{
public InversePropertyAttribute(string property) { }
public string Property { get { return default(string); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(388), AllowMultiple = false)]
public partial class NotMappedAttribute : System.Attribute
{
public NotMappedAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class TableAttribute : System.Attribute
{
public TableAttribute(string name) { }
public string Name { get { return default(string); } }
public string Schema { get { return default(string); } set { } }
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// C_DigestEncryptUpdate and C_DecryptDigestUpdate tests.
/// </summary>
[TestClass]
public class _23_DigestEncryptAndDecryptDigestTest
{
/// <summary>
/// Basic C_DigestEncryptUpdate and C_DecryptDigestUpdate test.
/// </summary>
[TestMethod]
public void _01_BasicDigestEncryptAndDecryptDigestTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
uint keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt32(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM digestingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = null;
byte[] digest1 = null;
byte[] decryptedData = null;
byte[] digest2 = null;
// Multipart digesting and encryption function C_DigestEncryptUpdate can be used i.e. for digesting and encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
uint encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
rv = pkcs11.C_DigestEncryptUpdate(session, part, Convert.ToUInt32(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
}
// Get length of digest value in first call
uint digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest1 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest1, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
uint lastEncryptedPartLen = 0;
rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with encrypted data and digest
// Multipart decryption and digesting function C_DecryptDigestUpdate can be used i.e. for digesting and decryption of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
uint partLen = Convert.ToUInt32(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Process each individual encrypted data part
partLen = Convert.ToUInt32(part.Length);
rv = pkcs11.C_DecryptDigestUpdate(session, encryptedPart, Convert.ToUInt32(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, Convert.ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
uint lastPartLen = 0;
rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
// Get length of digest value in first call
uint digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest2 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest2, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with decrypted data and digest
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
Assert.IsTrue(Convert.ToBase64String(digest1) == Convert.ToBase64String(digest2));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
encryptionMechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
/*
* 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 LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
public interface ILSL_Api
{
void state(string newState);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
void llAddToLandBanList(string avatar, double hours);
void llAddToLandPassList(string avatar, double hours);
void llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnSitTarget();
LSL_Key llAvatarOnLinkSitTarget(int linknum);
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options);
LSL_Integer llCeil(double f);
void llClearCameraParams();
LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face);
LSL_Integer llClearPrimMedia(LSL_Integer face);
void llCloseRemoteDataChannel(string channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
void llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Vector llDetectedVel(int number);
void llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
void llEjectFromLand(string pest);
void llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Key llGenerateKey();
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_List llGetAgentList(LSL_Integer scope, LSL_List options);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_String llGetCreator();
LSL_String llGetDate();
LSL_Float llGetEnergy();
LSL_String llGetEnv(LSL_String name);
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_Integer llGetLinkNumberOfSides(int link);
LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
LSL_Float llGetMassMKS();
LSL_Integer llGetMemoryLimit();
void llGetNextEmail(string address, string subject);
LSL_String llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_String llGetParcelMusicURL();
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_List llGetPrimMediaParams(int face, LSL_List rules);
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetSPMaxMemory();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Integer llGetUsedMemory();
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
void llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
void llGiveMoney(string destination, int amount);
LSL_String llTransferLindenDollars(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
LSL_String llGetUsername(string id);
LSL_String llRequestUsername(string id);
LSL_String llGetDisplayName(string id);
LSL_String llRequestDisplayName(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
void llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
LSL_Integer llManageEstateAccess(int action, string avatar);
void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset);
void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
LSL_String llSHA1String(string src);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
void llOffsetTexture(double u, double v, int face);
void llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
void llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
void llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
void llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llRegionSayTo(string target, int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
void llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
void llRemoteLoadScript(string target, string name, int running, int start_param);
void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
void llRemoveFromLandBanList(string avatar);
void llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_Key llRequestAgentData(string id, int data);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_String llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
void llResetLandBanList();
void llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
void llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, string text);
void llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
void llScriptProfiler(LSL_Integer flag);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetContentType(LSL_Key id, LSL_Integer type);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetVelocity(LSL_Vector velocity, int local);
void llSetAngularVelocity(LSL_Vector angularVelocity, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
void llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetLocalRot(LSL_Rotation rot);
LSL_Integer llSetMemoryLimit(LSL_Integer limit);
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
void llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
void llSetPos(LSL_Vector pos);
LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List rules);
void llSetPrimitiveParams(LSL_List rules);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
void llSetPrimURL(string url);
LSL_Integer llSetRegionPos(LSL_Vector pos);
void llSetRemoteScriptAccessPin(int pin);
void llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, double alpha);
void llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
void llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, double range);
void llTargetOmega(LSL_Vector axis, double spinrate, double gain);
void llTargetRemove(int number);
void llTeleportAgentHome(string agent);
void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt);
void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt);
void llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
void print(string str);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules, string originFunc);
void llSetKeyframedMotion(LSL_List frames, LSL_List options);
LSL_List GetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using ATABBI.TexE.Customization;
namespace ATABBI.TexE
{
public partial class MainForm2 : Form
{
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private DocumentExplorer m_solutionExplorer = new DocumentExplorer();
private PropertyWindow m_propertyWindow = new PropertyWindow();
private Toolbox m_toolbox = new Toolbox();
private OutputWindow m_outputWindow = new OutputWindow();
private BibliographyList m_BibliographyList = new BibliographyList();
public MainForm2()
{
InitializeComponent();
showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
RightToLeftLayout = showRightToLeft.Checked;
m_solutionExplorer = new DocumentExplorer();
m_solutionExplorer.RightToLeftLayout = RightToLeftLayout;
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
}
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
{
m_solutionExplorer.Show(dockPanel);
}
private void menuItemPropertyWindow_Click(object sender, System.EventArgs e)
{
m_propertyWindow.Show(dockPanel);
}
private void menuItemToolbox_Click(object sender, System.EventArgs e)
{
m_toolbox.Show(dockPanel);
}
private void menuItemOutputWindow_Click(object sender, System.EventArgs e)
{
m_outputWindow.Show(dockPanel);
}
private void menuItemBibliographyList_Click(object sender, System.EventArgs e)
{
m_BibliographyList.Show(dockPanel);
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog(this);
}
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private void menuItemNew_Click(object sender, System.EventArgs e)
{
TextDocument dummyDoc = CreateNewDocument();
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
}
private TextDocument CreateNewDocument()
{
TextDocument dummyDoc = new TextDocument();
int count = 1;
//string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
string text = "Document" + count.ToString();
while (FindDocument(text) != null)
{
count ++;
//text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
text = "Document" + count.ToString();
}
dummyDoc.Text = text;
return dummyDoc;
}
private TextDocument CreateNewDocument(string text)
{
TextDocument dummyDoc = new TextDocument();
dummyDoc.Text = text;
return dummyDoc;
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Application.ExecutablePath;
openFile.Filter = "text files (*.txt)|*.txt|tex files (*.tex)|*.tex|All files (*.*)|*.*";
openFile.FilterIndex = 1;
openFile.RestoreDirectory = true ;
if(openFile.ShowDialog() == DialogResult.OK)
{
string fullName = openFile.FileName;
string fileName = Path.GetFileName(fullName);
if (FindDocument(fileName) != null)
{
MessageBox.Show("The document: " + fileName + " has already opened!");
return;
}
TextDocument dummyDoc = new TextDocument();
dummyDoc.Text = fileName;
dummyDoc.Show(dockPanel);
try
{
dummyDoc.FileName = fullName;
}
catch (Exception exception)
{
dummyDoc.Close();
MessageBox.Show(exception.Message);
}
}
}
private void menuItemFile_Popup(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
menuItemClose.Enabled = menuItemCloseAll.Enabled = (ActiveMdiChild != null);
}
else
{
menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
menuItemCloseAll.Enabled = (dockPanel.DocumentsCount > 0);
}
}
private void menuItemClose_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
ActiveMdiChild.Close();
else if (dockPanel.ActiveDocument != null)
dockPanel.ActiveDocument.DockHandler.Close();
}
private void menuItemCloseAll_Click(object sender, System.EventArgs e)
{
CloseAllDocuments();
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
IDockContent[] documents = dockPanel.DocumentsToArray();
foreach (IDockContent content in documents)
content.DockHandler.Close();
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(DocumentExplorer).ToString())
return m_solutionExplorer;
else if (persistString == typeof(PropertyWindow).ToString())
return m_propertyWindow;
else if (persistString == typeof(Toolbox).ToString())
return m_toolbox;
else if (persistString == typeof(OutputWindow).ToString())
return m_outputWindow;
else if (persistString == typeof(BibliographyList).ToString())
return m_BibliographyList;
else
{
string[] parsedStrings = persistString.Split(new char[] { ',' });
if (parsedStrings.Length != 3)
return null;
if (parsedStrings[0] != typeof(TextDocument).ToString())
return null;
TextDocument dummyDoc = new TextDocument();
if (parsedStrings[1] != string.Empty)
dummyDoc.FileName = parsedStrings[1];
if (parsedStrings[2] != string.Empty)
dummyDoc.Text = parsedStrings[2];
return dummyDoc;
}
}
private void MainForm_Load(object sender, System.EventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
}
private void menuItemToolBar_Click(object sender, System.EventArgs e)
{
toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
}
private void menuItemStatusBar_Click(object sender, System.EventArgs e)
{
statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == toolBarButtonNew)
menuItemNew_Click(null, null);
else if (e.ClickedItem == toolBarButtonOpen)
menuItemOpen_Click(null, null);
else if (e.ClickedItem == toolBarButtonSolutionExplorer)
menuItemSolutionExplorer_Click(null, null);
else if (e.ClickedItem == toolBarButtonPropertyWindow)
menuItemPropertyWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonToolbox)
menuItemToolbox_Click(null, null);
else if (e.ClickedItem == toolBarButtonOutputWindow)
menuItemOutputWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonBibliographyList)
menuItemBibliographyList_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByCode)
menuItemLayoutByCode_Click(null, null);
//else if (e.ClickedItem == toolBarButtonLayoutByXml)
menuItemLayoutByXml_Click(null, null);
}
private void menuItemNewWindow_Click(object sender, System.EventArgs e)
{
MainForm newWindow = new MainForm();
newWindow.Text = newWindow.Text + " - New";
newWindow.Show();
}
private void menuItemTools_Popup(object sender, System.EventArgs e)
{
menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking;
}
private void menuItemLockLayout_Click(object sender, System.EventArgs e)
{
dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
}
private void menuItemLayoutByCode_Click(object sender, System.EventArgs e)
{
return;
dockPanel.SuspendLayout(true);
m_solutionExplorer.Show(dockPanel, DockState.DockRight);
m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer);
m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35);
m_BibliographyList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);
CloseAllDocuments();
TextDocument doc1 = CreateNewDocument("Document1");
TextDocument doc2 = CreateNewDocument("Document2");
TextDocument doc3 = CreateNewDocument("Document3");
TextDocument doc4 = CreateNewDocument("Document4");
doc1.Show(dockPanel, DockState.Document);
doc2.Show(doc1.Pane, null);
doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);
dockPanel.ResumeLayout(true, true);
}
private void menuItemLayoutByXml_Click(object sender, System.EventArgs e)
{
return;
dockPanel.SuspendLayout(true);
// In order to load layout from XML, we need to close all the DockContents
CloseAllContents();
Assembly assembly = Assembly.GetAssembly(typeof(MainForm));
Stream xmlStream = assembly.GetManifestResourceStream("ATABBI.TexE.Resources.DockPanel.xml");
dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
xmlStream.Close();
dockPanel.ResumeLayout(true, true);
}
private void CloseAllContents()
{
// we don't want to create another instance of tool window, set DockPanel to null
m_solutionExplorer.DockPanel = null;
m_propertyWindow.DockPanel = null;
m_toolbox.DockPanel = null;
m_outputWindow.DockPanel = null;
m_BibliographyList.DockPanel = null;
// Close all other document windows
CloseAllDocuments();
}
private void SetSchema(object sender, System.EventArgs e)
{
CloseAllContents();
if (sender == menuItemSchemaVS2005)
Extender.SetSchema(dockPanel, Extender.Schema.VS2005);
else if (sender == menuItemSchemaVS2003)
Extender.SetSchema(dockPanel, Extender.Schema.VS2003);
menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
}
private void SetDocumentStyle(object sender, System.EventArgs e)
{
DocumentStyle oldStyle = dockPanel.DocumentStyle;
DocumentStyle newStyle;
if (sender == menuItemDockingMdi)
newStyle = DocumentStyle.DockingMdi;
else if (sender == menuItemDockingWindow)
newStyle = DocumentStyle.DockingWindow;
else if (sender == menuItemDockingSdi)
newStyle = DocumentStyle.DockingSdi;
else
newStyle = DocumentStyle.SystemMdi;
if (oldStyle == newStyle)
return;
if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
CloseAllDocuments();
dockPanel.DocumentStyle = newStyle;
menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
}
private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
Form activeMdi = ActiveMdiChild;
foreach (Form form in MdiChildren)
{
if (form != activeMdi)
form.Close();
}
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
if (!document.DockHandler.IsActivated)
document.DockHandler.Close();
}
}
}
private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e)
{
dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked= !menuItemShowDocumentIcon.Checked;
}
private void showRightToLeft_Click(object sender, EventArgs e)
{
CloseAllContents();
if (showRightToLeft.Checked)
{
this.RightToLeft = RightToLeft.No;
this.RightToLeftLayout = false;
}
else
{
this.RightToLeft = RightToLeft.Yes;
this.RightToLeftLayout = true;
}
m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout;
showRightToLeft.Checked = !showRightToLeft.Checked;
}
private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
{
m_bSaveLayout = false;
Close();
m_bSaveLayout = true;
}
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Threading;
namespace OpenSim.Region.OptionalModules.Scripting
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class ExtendedPhysics : INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[EXTENDED PHYSICS]";
// =============================================================
// Since BulletSim is a plugin, this these values aren't defined easily in one place.
// This table must correspond to an identical table in BSScene.
// Per scene functions. See BSScene.
// Per avatar functions. See BSCharacter.
// Per prim functions. See BSPrim.
public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType";
public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType";
public const string PhysFunctChangeLinkFixed = "BulletSim.ChangeLinkFixed";
public const string PhysFunctChangeLinkType = "BulletSim.ChangeLinkType";
public const string PhysFunctGetLinkType = "BulletSim.GetLinkType";
public const string PhysFunctChangeLinkParams = "BulletSim.ChangeLinkParams";
// =============================================================
private IConfig Configuration { get; set; }
private bool Enabled { get; set; }
private Scene BaseScene { get; set; }
private IScriptModuleComms Comms { get; set; }
#region INonSharedRegionModule
public string Name { get { return this.GetType().Name; } }
public void Initialise(IConfigSource config)
{
BaseScene = null;
Enabled = false;
Configuration = null;
Comms = null;
try
{
if ((Configuration = config.Configs["ExtendedPhysics"]) != null)
{
Enabled = Configuration.GetBoolean("Enabled", Enabled);
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Initialization error: {0}", LogHeader, e);
}
m_log.InfoFormat("{0} module {1} enabled", LogHeader, (Enabled ? "is" : "is not"));
}
public void Close()
{
if (BaseScene != null)
{
BaseScene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
BaseScene.EventManager.OnSceneObjectPartUpdated -= EventManager_OnSceneObjectPartUpdated;
BaseScene = null;
}
}
public void AddRegion(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (BaseScene != null && BaseScene == scene)
{
Close();
}
}
public void RegionLoaded(Scene scene)
{
if (!Enabled) return;
BaseScene = scene;
Comms = BaseScene.RequestModuleInterface<IScriptModuleComms>();
if (Comms == null)
{
m_log.WarnFormat("{0} ScriptModuleComms interface not defined", LogHeader);
Enabled = false;
return;
}
// Register as LSL functions all the [ScriptInvocation] marked methods.
Comms.RegisterScriptInvocations(this);
Comms.RegisterConstants(this);
// When an object is modified, we might need to update its extended physics parameters
BaseScene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
BaseScene.EventManager.OnSceneObjectPartUpdated += EventManager_OnSceneObjectPartUpdated;
}
public Type ReplaceableInterface { get { return null; } }
#endregion // INonSharedRegionModule
private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
{
}
// Event generated when some property of a prim changes.
private void EventManager_OnSceneObjectPartUpdated(SceneObjectPart sop, bool isFullUpdate)
{
}
[ScriptConstant]
public const int PHYS_CENTER_OF_MASS = 1 << 0;
[ScriptInvocation]
public string physGetEngineType(UUID hostID, UUID scriptID)
{
string ret = string.Empty;
if (BaseScene.PhysicsScene != null)
{
ret = BaseScene.PhysicsScene.EngineType;
}
return ret;
}
[ScriptConstant]
public const int PHYS_LINKSET_TYPE_CONSTRAINT = 0;
[ScriptConstant]
public const int PHYS_LINKSET_TYPE_COMPOUND = 1;
[ScriptConstant]
public const int PHYS_LINKSET_TYPE_MANUAL = 2;
[ScriptInvocation]
public int physSetLinksetType(UUID hostID, UUID scriptID, int linksetType)
{
int ret = -1;
if (!Enabled) return ret;
// The part that is requesting the change.
SceneObjectPart requestingPart = BaseScene.GetSceneObjectPart(hostID);
if (requestingPart != null)
{
// The change is always made to the root of a linkset.
SceneObjectGroup containingGroup = requestingPart.ParentGroup;
SceneObjectPart rootPart = containingGroup.RootPart;
if (rootPart != null)
{
PhysicsActor rootPhysActor = rootPart.PhysActor;
if (rootPhysActor != null)
{
if (rootPhysActor.IsPhysical)
{
// Change a physical linkset by making non-physical, waiting for one heartbeat so all
// the prim and linkset state is updated, changing the type and making the
// linkset physical again.
containingGroup.ScriptSetPhysicsStatus(false);
Thread.Sleep(150); // longer than one heartbeat tick
// A kludge for the moment.
// Since compound linksets move the children but don't generate position updates to the
// simulator, it is possible for compound linkset children to have out-of-sync simulator
// and physical positions. The following causes the simulator to push the real child positions
// down into the physics engine to get everything synced.
containingGroup.UpdateGroupPosition(containingGroup.AbsolutePosition);
containingGroup.UpdateGroupRotationR(containingGroup.GroupRotation);
object[] parms2 = { rootPhysActor, null, linksetType };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2));
Thread.Sleep(150); // longer than one heartbeat tick
containingGroup.ScriptSetPhysicsStatus(true);
}
else
{
// Non-physical linksets don't have a physical instantiation so there is no state to
// worry about being updated.
object[] parms2 = { rootPhysActor, null, linksetType };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2));
}
}
else
{
m_log.WarnFormat("{0} physSetLinksetType: root part does not have a physics actor. rootName={1}, hostID={2}",
LogHeader, rootPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} physSetLinksetType: root part does not exist. RequestingPartName={1}, hostID={2}",
LogHeader, requestingPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} physSetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID);
}
return ret;
}
[ScriptInvocation]
public int physGetLinksetType(UUID hostID, UUID scriptID)
{
int ret = -1;
if (!Enabled) return ret;
// The part that is requesting the change.
SceneObjectPart requestingPart = BaseScene.GetSceneObjectPart(hostID);
if (requestingPart != null)
{
// The type is is always on the root of a linkset.
SceneObjectGroup containingGroup = requestingPart.ParentGroup;
SceneObjectPart rootPart = containingGroup.RootPart;
if (rootPart != null)
{
PhysicsActor rootPhysActor = rootPart.PhysActor;
if (rootPhysActor != null)
{
object[] parms2 = { rootPhysActor, null };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinksetType, parms2));
}
else
{
m_log.WarnFormat("{0} physGetLinksetType: root part does not have a physics actor. rootName={1}, hostID={2}",
LogHeader, rootPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} physGetLinksetType: root part does not exist. RequestingPartName={1}, hostID={2}",
LogHeader, requestingPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} physGetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID);
}
return ret;
}
[ScriptConstant]
public const int PHYS_LINK_TYPE_FIXED = 1234;
[ScriptConstant]
public const int PHYS_LINK_TYPE_HINGE = 4;
[ScriptConstant]
public const int PHYS_LINK_TYPE_SPRING = 9;
[ScriptConstant]
public const int PHYS_LINK_TYPE_6DOF = 6;
[ScriptConstant]
public const int PHYS_LINK_TYPE_SLIDER = 7;
// physChangeLinkType(integer linkNum, integer typeCode)
[ScriptInvocation]
public int physChangeLinkType(UUID hostID, UUID scriptID, int linkNum, int typeCode)
{
int ret = -1;
if (!Enabled) return ret;
PhysicsActor rootPhysActor;
PhysicsActor childPhysActor;
if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor))
{
object[] parms2 = { rootPhysActor, childPhysActor, typeCode };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2));
}
return ret;
}
// physGetLinkType(integer linkNum)
[ScriptInvocation]
public int physGetLinkType(UUID hostID, UUID scriptID, int linkNum)
{
int ret = -1;
if (!Enabled) return ret;
PhysicsActor rootPhysActor;
PhysicsActor childPhysActor;
if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor))
{
object[] parms2 = { rootPhysActor, childPhysActor };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinkType, parms2));
}
return ret;
}
// physChangeLinkFixed(integer linkNum)
// Change the link between the root and the linkNum into a fixed, static physical connection.
[ScriptInvocation]
public int physChangeLinkFixed(UUID hostID, UUID scriptID, int linkNum)
{
int ret = -1;
if (!Enabled) return ret;
PhysicsActor rootPhysActor;
PhysicsActor childPhysActor;
if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor))
{
object[] parms2 = { rootPhysActor, childPhysActor , PHYS_LINK_TYPE_FIXED };
ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2));
}
return ret;
}
// Code for specifying params.
// The choice if 14400 is arbitrary and only serves to catch parameter code misuse.
public const int PHYS_PARAM_MIN = 14401;
[ScriptConstant]
public const int PHYS_PARAM_FRAMEINA_LOC = 14401;
[ScriptConstant]
public const int PHYS_PARAM_FRAMEINA_ROT = 14402;
[ScriptConstant]
public const int PHYS_PARAM_FRAMEINB_LOC = 14403;
[ScriptConstant]
public const int PHYS_PARAM_FRAMEINB_ROT = 14404;
[ScriptConstant]
public const int PHYS_PARAM_LINEAR_LIMIT_LOW = 14405;
[ScriptConstant]
public const int PHYS_PARAM_LINEAR_LIMIT_HIGH = 14406;
[ScriptConstant]
public const int PHYS_PARAM_ANGULAR_LIMIT_LOW = 14407;
[ScriptConstant]
public const int PHYS_PARAM_ANGULAR_LIMIT_HIGH = 14408;
[ScriptConstant]
public const int PHYS_PARAM_USE_FRAME_OFFSET = 14409;
[ScriptConstant]
public const int PHYS_PARAM_ENABLE_TRANSMOTOR = 14410;
[ScriptConstant]
public const int PHYS_PARAM_TRANSMOTOR_MAXVEL = 14411;
[ScriptConstant]
public const int PHYS_PARAM_TRANSMOTOR_MAXFORCE = 14412;
[ScriptConstant]
public const int PHYS_PARAM_CFM = 14413;
[ScriptConstant]
public const int PHYS_PARAM_ERP = 14414;
[ScriptConstant]
public const int PHYS_PARAM_SOLVER_ITERATIONS = 14415;
[ScriptConstant]
public const int PHYS_PARAM_SPRING_AXIS_ENABLE = 14416;
[ScriptConstant]
public const int PHYS_PARAM_SPRING_DAMPING = 14417;
[ScriptConstant]
public const int PHYS_PARAM_SPRING_STIFFNESS = 14418;
[ScriptConstant]
public const int PHYS_PARAM_LINK_TYPE = 14419;
[ScriptConstant]
public const int PHYS_PARAM_USE_LINEAR_FRAMEA = 14420;
[ScriptConstant]
public const int PHYS_PARAM_SPRING_EQUILIBRIUM_POINT = 14421;
public const int PHYS_PARAM_MAX = 14421;
// Used when specifying a parameter that has settings for the three linear and three angular axis
[ScriptConstant]
public const int PHYS_AXIS_ALL = -1;
[ScriptConstant]
public const int PHYS_AXIS_LINEAR_ALL = -2;
[ScriptConstant]
public const int PHYS_AXIS_ANGULAR_ALL = -3;
[ScriptConstant]
public const int PHYS_AXIS_LINEAR_X = 0;
[ScriptConstant]
public const int PHYS_AXIS_LINEAR_Y = 1;
[ScriptConstant]
public const int PHYS_AXIS_LINEAR_Z = 2;
[ScriptConstant]
public const int PHYS_AXIS_ANGULAR_X = 3;
[ScriptConstant]
public const int PHYS_AXIS_ANGULAR_Y = 4;
[ScriptConstant]
public const int PHYS_AXIS_ANGULAR_Z = 5;
// physChangeLinkParams(integer linkNum, [ PHYS_PARAM_*, value, PHYS_PARAM_*, value, ...])
[ScriptInvocation]
public int physChangeLinkParams(UUID hostID, UUID scriptID, int linkNum, object[] parms)
{
int ret = -1;
if (!Enabled) return ret;
PhysicsActor rootPhysActor;
PhysicsActor childPhysActor;
if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor))
{
object[] parms2 = AddToBeginningOfArray(rootPhysActor, childPhysActor, parms);
ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkParams, parms2));
}
return ret;
}
private bool GetRootPhysActor(UUID hostID, out PhysicsActor rootPhysActor)
{
SceneObjectGroup containingGroup;
SceneObjectPart rootPart;
return GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor);
}
private bool GetRootPhysActor(UUID hostID, out SceneObjectGroup containingGroup, out SceneObjectPart rootPart, out PhysicsActor rootPhysActor)
{
bool ret = false;
rootPhysActor = null;
containingGroup = null;
rootPart = null;
SceneObjectPart requestingPart;
requestingPart = BaseScene.GetSceneObjectPart(hostID);
if (requestingPart != null)
{
// The type is is always on the root of a linkset.
containingGroup = requestingPart.ParentGroup;
if (containingGroup != null && !containingGroup.IsDeleted)
{
rootPart = containingGroup.RootPart;
if (rootPart != null)
{
rootPhysActor = rootPart.PhysActor;
if (rootPhysActor != null)
{
ret = true;
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}",
LogHeader, rootPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not exist. RequestingPartName={1}, hostID={2}",
LogHeader, requestingPart.Name, hostID);
}
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Containing group missing or deleted. hostID={1}", LogHeader, hostID);
}
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: cannot find script object in scene. hostID={1}", LogHeader, hostID);
}
return ret;
}
// Find the root and child PhysActors based on the linkNum.
// Return 'true' if both are found and returned.
private bool GetRootAndChildPhysActors(UUID hostID, int linkNum, out PhysicsActor rootPhysActor, out PhysicsActor childPhysActor)
{
bool ret = false;
rootPhysActor = null;
childPhysActor = null;
SceneObjectGroup containingGroup;
SceneObjectPart rootPart;
if (GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor))
{
SceneObjectPart linkPart = containingGroup.GetLinkNumPart(linkNum);
if (linkPart != null)
{
childPhysActor = linkPart.PhysActor;
if (childPhysActor != null)
{
ret = true;
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Link part has no physical actor. rootName={1}, hostID={2}, linknum={3}",
LogHeader, rootPart.Name, hostID, linkNum);
}
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Could not find linknum part. rootName={1}, hostID={2}, linknum={3}",
LogHeader, rootPart.Name, hostID, linkNum);
}
}
else
{
m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}",
LogHeader, rootPart.Name, hostID);
}
return ret;
}
// Return an array of objects with the passed object as the first object of a new array
private object[] AddToBeginningOfArray(object firstOne, object secondOne, object[] prevArray)
{
object[] newArray = new object[2 + prevArray.Length];
newArray[0] = firstOne;
newArray[1] = secondOne;
prevArray.CopyTo(newArray, 2);
return newArray;
}
// Extension() returns an object. Convert that object into the integer error we expect to return.
private int MakeIntError(object extensionRet)
{
int ret = -1;
if (extensionRet != null)
{
try
{
ret = (int)extensionRet;
}
catch
{
ret = -1;
}
}
return ret;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E02_Continent (editable root object).<br/>
/// This is a generated base class of <see cref="E02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="E03_SubContinentObjects"/> of type <see cref="E03_SubContinentColl"/> (1:M relation to <see cref="E04_SubContinent"/>)
/// </remarks>
[Serializable]
public partial class E02_Continent : BusinessBase<E02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E03_Continent_Child> E03_Continent_SingleObjectProperty = RegisterProperty<E03_Continent_Child>(p => p.E03_Continent_SingleObject, "E03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E03 Continent Single Object ("parent load" child property).
/// </summary>
/// <value>The E03 Continent Single Object.</value>
public E03_Continent_Child E03_Continent_SingleObject
{
get { return GetProperty(E03_Continent_SingleObjectProperty); }
private set { LoadProperty(E03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<E03_Continent_ReChild> E03_Continent_ASingleObjectProperty = RegisterProperty<E03_Continent_ReChild>(p => p.E03_Continent_ASingleObject, "E03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the E03 Continent ASingle Object ("parent load" child property).
/// </summary>
/// <value>The E03 Continent ASingle Object.</value>
public E03_Continent_ReChild E03_Continent_ASingleObject
{
get { return GetProperty(E03_Continent_ASingleObjectProperty); }
private set { LoadProperty(E03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="E03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<E03_SubContinentColl> E03_SubContinentObjectsProperty = RegisterProperty<E03_SubContinentColl>(p => p.E03_SubContinentObjects, "E03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the E03 Sub Continent Objects ("parent load" child property).
/// </summary>
/// <value>The E03 Sub Continent Objects.</value>
public E03_SubContinentColl E03_SubContinentObjects
{
get { return GetProperty(E03_SubContinentObjectsProperty); }
private set { LoadProperty(E03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E02_Continent"/> object.</returns>
public static E02_Continent NewE02_Continent()
{
return DataPortal.Create<E02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="E02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID parameter of the E02_Continent to fetch.</param>
/// <returns>A reference to the fetched <see cref="E02_Continent"/> object.</returns>
public static E02_Continent GetE02_Continent(int continent_ID)
{
return DataPortal.Fetch<E02_Continent>(continent_ID);
}
/// <summary>
/// Factory method. Deletes a <see cref="E02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the E02_Continent to delete.</param>
public static void DeleteE02_Continent(int continent_ID)
{
DataPortal.Delete<E02_Continent>(continent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E02_Continent()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(E03_Continent_SingleObjectProperty, DataPortal.CreateChild<E03_Continent_Child>());
LoadProperty(E03_Continent_ASingleObjectProperty, DataPortal.CreateChild<E03_Continent_ReChild>());
LoadProperty(E03_SubContinentObjectsProperty, DataPortal.CreateChild<E03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="E02_Continent"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID">The Continent ID.</param>
protected void DataPortal_Fetch(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, continent_ID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
FetchChildren(dr);
}
}
}
/// <summary>
/// Loads a <see cref="E02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID"));
LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
if (dr.Read())
LoadProperty(E03_Continent_SingleObjectProperty, E03_Continent_Child.GetE03_Continent_Child(dr));
dr.NextResult();
if (dr.Read())
LoadProperty(E03_Continent_ASingleObjectProperty, E03_Continent_ReChild.GetE03_Continent_ReChild(dr));
dr.NextResult();
LoadProperty(E03_SubContinentObjectsProperty, E03_SubContinentColl.GetE03_SubContinentColl(dr));
dr.NextResult();
while (dr.Read())
{
var child = E05_SubContinent_Child.GetE05_SubContinent_Child(dr);
var obj = E03_SubContinentObjects.FindE04_SubContinentByParentProperties(child.subContinent_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = E05_SubContinent_ReChild.GetE05_SubContinent_ReChild(dr);
var obj = E03_SubContinentObjects.FindE04_SubContinentByParentProperties(child.subContinent_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var e05_CountryColl = E05_CountryColl.GetE05_CountryColl(dr);
e05_CountryColl.LoadItems(E03_SubContinentObjects);
dr.NextResult();
while (dr.Read())
{
var child = E07_Country_Child.GetE07_Country_Child(dr);
var obj = e05_CountryColl.FindE06_CountryByParentProperties(child.country_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = E07_Country_ReChild.GetE07_Country_ReChild(dr);
var obj = e05_CountryColl.FindE06_CountryByParentProperties(child.country_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var e07_RegionColl = E07_RegionColl.GetE07_RegionColl(dr);
e07_RegionColl.LoadItems(e05_CountryColl);
dr.NextResult();
while (dr.Read())
{
var child = E09_Region_Child.GetE09_Region_Child(dr);
var obj = e07_RegionColl.FindE08_RegionByParentProperties(child.region_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = E09_Region_ReChild.GetE09_Region_ReChild(dr);
var obj = e07_RegionColl.FindE08_RegionByParentProperties(child.region_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var e09_CityColl = E09_CityColl.GetE09_CityColl(dr);
e09_CityColl.LoadItems(e07_RegionColl);
dr.NextResult();
while (dr.Read())
{
var child = E11_City_Child.GetE11_City_Child(dr);
var obj = e09_CityColl.FindE10_CityByParentProperties(child.city_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = E11_City_ReChild.GetE11_City_ReChild(dr);
var obj = e09_CityColl.FindE10_CityByParentProperties(child.city_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var e11_CityRoadColl = E11_CityRoadColl.GetE11_CityRoadColl(dr);
e11_CityRoadColl.LoadItems(e09_CityColl);
}
/// <summary>
/// Inserts a new <see cref="E02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="E02_Continent"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(Continent_ID);
}
/// <summary>
/// Deletes the <see cref="E02_Continent"/> object from database.
/// </summary>
/// <param name="continent_ID">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
protected void DataPortal_Delete(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteE02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, continent_ID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(E03_Continent_SingleObjectProperty, DataPortal.CreateChild<E03_Continent_Child>());
LoadProperty(E03_Continent_ASingleObjectProperty, DataPortal.CreateChild<E03_Continent_ReChild>());
LoadProperty(E03_SubContinentObjectsProperty, DataPortal.CreateChild<E03_SubContinentColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Capture execution context for a thread
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using Thread = Internal.Runtime.Augments.RuntimeThread;
namespace System.Threading
{
public delegate void ContextCallback(Object state);
public sealed class ExecutionContext : IDisposable, ISerializable
{
internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true);
internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty<IAsyncLocal>(), isFlowSuppressed: true);
private readonly IAsyncLocalValueMap m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
private readonly bool m_isFlowSuppressed;
private readonly bool m_isDefault;
private ExecutionContext(bool isDefault)
{
m_isDefault = isDefault;
}
private ExecutionContext(
IAsyncLocalValueMap localValues,
IAsyncLocal[] localChangeNotifications,
bool isFlowSuppressed)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
m_isFlowSuppressed = isFlowSuppressed;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public static ExecutionContext Capture()
{
ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
return
executionContext == null ? Default :
executionContext.m_isFlowSuppressed ? null :
executionContext;
}
private ExecutionContext ShallowClone(bool isFlowSuppressed)
{
Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (m_localValues == null ||
m_localValues.GetType() == typeof(AsyncLocalValueMap.EmptyAsyncLocalValueMap))
{
return isFlowSuppressed ?
DefaultFlowSuppressed :
null; // implies the default context
}
return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
}
public static AsyncFlowControl SuppressFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread.ExecutionContext ?? Default;
if (executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes);
}
executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
var asyncFlowControl = new AsyncFlowControl();
currentThread.ExecutionContext = executionContext;
asyncFlowControl.Initialize(currentThread);
return asyncFlowControl;
}
public static void RestoreFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread.ExecutionContext;
if (executionContext == null || !executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow);
}
currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
}
public static bool IsFlowSuppressed()
{
ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
return executionContext != null && executionContext.m_isFlowSuppressed;
}
internal bool HasChangeNotifications => m_localChangeNotifications != null;
internal bool IsDefault => m_isDefault;
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
// Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc.
if (executionContext == null)
{
ThrowNullContext();
}
RunInternal(executionContext, callback, state);
}
internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
{
// Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
// Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
// https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
// Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
// Capture references to Thread Contexts
Thread currentThread0 = Thread.CurrentThread;
Thread currentThread = currentThread0;
ExecutionContext previousExecutionCtx0 = currentThread0.ExecutionContext;
// Store current ExecutionContext and SynchronizationContext as "previousXxx".
// This allows us to restore them and undo any Context changes made in callback.Invoke
// so that they won't "leak" back into caller.
// These variables will cross EH so be forced to stack
ExecutionContext previousExecutionCtx = previousExecutionCtx0;
SynchronizationContext previousSyncCtx = currentThread0.SynchronizationContext;
if (executionContext != null && executionContext.m_isDefault)
{
// Default is a null ExecutionContext internally
executionContext = null;
}
if (previousExecutionCtx0 != executionContext)
{
// Restore changed ExecutionContext
currentThread0.ExecutionContext = executionContext;
if ((executionContext != null && executionContext.HasChangeNotifications) ||
(previousExecutionCtx0 != null && previousExecutionCtx0.HasChangeNotifications))
{
// There are change notifications; trigger any affected
OnValuesChanged(previousExecutionCtx0, executionContext);
}
}
ExceptionDispatchInfo edi = null;
try
{
callback.Invoke(state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
SynchronizationContext previousSyncCtx1 = previousSyncCtx;
Thread currentThread1 = currentThread;
// The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
if (currentThread1.SynchronizationContext != previousSyncCtx1)
{
// Restore changed SynchronizationContext back to previous
currentThread1.SynchronizationContext = previousSyncCtx1;
}
ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
ExecutionContext currentExecutionCtx1 = currentThread1.ExecutionContext;
if (currentExecutionCtx1 != previousExecutionCtx1)
{
// Restore changed ExecutionContext back to previous
currentThread1.ExecutionContext = previousExecutionCtx1;
if ((currentExecutionCtx1 != null && currentExecutionCtx1.HasChangeNotifications) ||
(previousExecutionCtx1 != null && previousExecutionCtx1.HasChangeNotifications))
{
// There are change notifications; trigger any affected
OnValuesChanged(currentExecutionCtx1, previousExecutionCtx1);
}
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
internal static void OnValuesChanged(ExecutionContext previousExecutionCtx, ExecutionContext nextExecutionCtx)
{
Debug.Assert(previousExecutionCtx != nextExecutionCtx);
// Collect Change Notifications
IAsyncLocal[] previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications;
IAsyncLocal[] nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications;
// At least one side must have notifications
Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null);
// Fire Change Notifications
try
{
if (previousChangeNotifications != null && nextChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx.m_localValues != null);
Debug.Assert(nextExecutionCtx.m_localValues != null);
// Both contexts have change notifications, check previousExecutionCtx first
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
if (nextChangeNotifications != previousChangeNotifications)
{
// Check for additional notifications in nextExecutionCtx
foreach (IAsyncLocal local in nextChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event
// for that local in the code above.
if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue))
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
}
}
}
else if (previousChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx.m_localValues != null);
// No current values, so just check previous against null
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
if (previousValue != null)
{
local.OnValueChanged(previousValue, null, contextChanged: true);
}
}
}
else // Implied: nextChangeNotifications != null
{
// Notifications can't exist without values
Debug.Assert(nextExecutionCtx.m_localValues != null);
// No previous values, so just check current against null
foreach (IAsyncLocal local in nextChangeNotifications)
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
if (currentValue != null)
{
local.OnValueChanged(null, currentValue, contextChanged: true);
}
}
}
}
catch (Exception ex)
{
Environment.FailFast(
SR.ExecutionContext_ExceptionInAsyncLocalNotification,
ex);
}
}
[StackTraceHidden]
private static void ThrowNullContext()
{
throw new InvalidOperationException(SR.InvalidOperation_NullContext);
}
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
if (current == null)
{
return null;
}
current.m_localValues.TryGetValue(local, out object value);
return value;
}
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
object previousValue = null;
bool hadPreviousValue = false;
if (current != null)
{
hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
}
if (previousValue == newValue)
{
return;
}
IAsyncLocal[] newChangeNotifications = null;
IAsyncLocalValueMap newValues;
bool isFlowSuppressed = false;
if (current != null)
{
isFlowSuppressed = current.m_isFlowSuppressed;
newValues = current.m_localValues.Set(local, newValue);
newChangeNotifications = current.m_localChangeNotifications;
}
else
{
// First AsyncLocal
newValues = new AsyncLocalValueMap.OneElementAsyncLocalValueMap(local, newValue);
}
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Debug.Assert(newChangeNotifications != null);
Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else if (newChangeNotifications == null)
{
newChangeNotifications = new IAsyncLocal[1] { local };
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
Thread.CurrentThread.ExecutionContext =
(!isFlowSuppressed && newValues.GetType() == typeof(AsyncLocalValueMap.EmptyAsyncLocalValueMap)) ?
null : // No values, return to Default context
new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, contextChanged: false);
}
}
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
}
public struct AsyncFlowControl : IDisposable
{
private Thread _thread;
internal void Initialize(Thread currentThread)
{
Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
}
if (Thread.CurrentThread != _thread)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
}
// An async flow control cannot be undone when a different execution context is applied. The desktop framework
// mutates the execution context when its state changes, and only changes the instance when an execution context
// is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
// context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
// context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
// local's value, the desktop framework verifies that a different execution context has not been applied by
// checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
// since the execution context instance will change after changing the async local's value, it verifies that a
// different execution context has not been applied, by instead ensuring that the current execution context's
// flow is suppressed.
if (!ExecutionContext.IsFlowSuppressed())
{
throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
}
_thread = null;
ExecutionContext.RestoreFlow();
}
public void Dispose()
{
Undo();
}
public override bool Equals(object obj)
{
return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
}
public bool Equals(AsyncFlowControl obj)
{
return _thread == obj._thread;
}
public override int GetHashCode()
{
return _thread?.GetHashCode() ?? 0;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals(b);
}
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
return !(a == b);
}
}
}
| |
/*
* Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v..
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using log4net;
using Microsoft.SharePoint.Client;
using File = Microsoft.SharePoint.Client.File;
#endregion
namespace PPWCode.Util.SharePoint.I
{
/// <summary>
/// Actual implementation of <see cref="ISharePointClient"/>.
/// </summary>
public class SharePointClient
: ISharePointClient
{
#region fields
private static readonly ILog s_Logger = LogManager.GetLogger(typeof(SharePointClient));
#endregion
#region Private helpers
/// <summary>
/// Gets a client context on which the rootweb is already loaded.
/// User is responsible for disposing the context.
/// </summary>
private ClientContext GetSharePointClientContext()
{
ClientContext ctx = new ClientContext(SharePointSiteUrl);
if (Credentials != null)
{
ctx.Credentials = Credentials;
}
ctx.Load(ctx.Site.RootWeb);
ctx.ExecuteQuery();
s_Logger.Debug(string.Format("Connect to SharePoint using user {0}", ctx.Web.CurrentUser));
return ctx;
}
private static void CreateFolder(ClientContext spClientContext, string relativeUrl)
{
var workUrl = (relativeUrl.StartsWith("/")) ? relativeUrl.Substring(1) : relativeUrl;
string[] foldernames = workUrl.Split('/');
spClientContext.Load(spClientContext.Site.RootWeb.RootFolder);
spClientContext.ExecuteQuery();
Folder parentfolder = spClientContext.Site.RootWeb.RootFolder;
string workname = String.Empty;
string parentfoldername = String.Empty;
foreach (string folderName in foldernames)
{
try
{
workname = String.Format("{0}/{1}", workname, folderName);
Folder workfolder = spClientContext.Site.RootWeb.GetFolderByServerRelativeUrl(workname);
spClientContext.Load(workfolder);
spClientContext.ExecuteQuery();
parentfolder = workfolder;
}
catch (ServerException se)
{
if (se.ServerErrorTypeName == typeof(FileNotFoundException).FullName)
{
if (parentfolder == null)
{
parentfolder = spClientContext.Site.RootWeb.GetFolderByServerRelativeUrl(parentfoldername);
spClientContext.Load(parentfolder);
}
parentfolder.Folders.Add(folderName);
spClientContext.ExecuteQuery();
parentfolder = null;
}
}
parentfoldername = workname;
}
}
#endregion
#region ISharePointClient interface
public string SharePointSiteUrl { get; set; }
public ICredentials Credentials { get; set; }
/// <inheritdoc cref="ISharePointClient.EnsureFolder" />
public void EnsureFolder(string relativeUrl)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web rootWeb = spClientContext.Site.RootWeb;
//Check if the url exists
try
{
rootWeb.GetFolderByServerRelativeUrl(relativeUrl);
spClientContext.ExecuteQuery();
}
catch (ServerException se)
{
// If not, create it.
if (se.ServerErrorTypeName == typeof(FileNotFoundException).FullName)
{
CreateFolder(spClientContext, relativeUrl);
}
}
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("EnsureFolder({0}) failed using ClientContext {1}.", relativeUrl, SharePointSiteUrl), e);
throw;
}
}
public void UploadDocument(string relativeUrl, SharePointDocument doc)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web rootWeb = spClientContext.Site.RootWeb;
//Check if the url exists
int index = relativeUrl.LastIndexOf("/");
string parentFolder = relativeUrl.Substring(0, index);
string filename = relativeUrl.Substring(index + 1);
//Create intermediate folders if not exist
EnsureFolder(parentFolder);
Folder fldr = rootWeb.GetFolderByServerRelativeUrl(parentFolder);
spClientContext.ExecuteQuery();
//Create File information
var fciNewFileFromComputer = new FileCreationInformation
{
Content = doc.Content,
Url = filename,
Overwrite = true
};
//Upload the file
File uploadedFile = fldr.Files.Add(fciNewFileFromComputer);
spClientContext.Load(uploadedFile);
spClientContext.ExecuteQuery();
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("UploadDocument({0}) failed using ClientContext {1}.", relativeUrl, SharePointSiteUrl), e);
throw;
}
}
public bool ValidateUri(Uri sharePointUri)
{
if (sharePointUri != null)
{
string baseUrl = sharePointUri.GetLeftPart(UriPartial.Authority);
if (!string.IsNullOrEmpty(baseUrl))
{
using (ClientContext clientContext = new ClientContext(baseUrl))
{
//get the site collection
Web site = clientContext.Web;
string localPath = sharePointUri.LocalPath;
if (!string.IsNullOrEmpty(localPath))
{
//get the document library folder
site.GetFolderByServerRelativeUrl(localPath);
try
{
clientContext.ExecuteQuery();
return true;
}
catch (ServerException)
{
return false;
}
catch (Exception)
{
return false;
}
}
}
}
}
return false;
}
public void OpenUri(Uri uri)
{
string url = uri.OriginalString;
if (!string.IsNullOrEmpty(url))
{
Process.Start(new ProcessStartInfo
{
UseShellExecute = true,
FileName = url,
Verb = "Open",
LoadUserProfile = true
});
}
}
public List<SharePointSearchResult> SearchFiles(string url)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web rootWeb = spClientContext.Site.RootWeb;
Folder spFolder = rootWeb.GetFolderByServerRelativeUrl(url); // "/Shared%20Documents/MEERTENS%20MATHIEU%20-%2051062002701/Construo/Actua/");
spClientContext.Load(spFolder.Files);
spClientContext.ExecuteQuery();
List<SharePointSearchResult> result = new List<SharePointSearchResult>();
foreach (File spFile in spFolder.Files)
{
var fileInformation = new SharePointSearchResult();
fileInformation.Properties.Add("FileName", spFile.Name);
fileInformation.Properties.Add("Description", spFile.CheckInComment);
fileInformation.Properties.Add("MajorVersion", spFile.MajorVersion);
fileInformation.Properties.Add("MinorVersion", spFile.MinorVersion);
fileInformation.Properties.Add("ModifiedBy", spFile.ModifiedBy);
fileInformation.Properties.Add("DateModified", spFile.TimeLastModified);
fileInformation.Properties.Add("CreatedBy", spFile.Author);
fileInformation.Properties.Add("DateCreated", spFile.TimeCreated);
fileInformation.Properties.Add("ServerRelativeUrl", spFile.ServerRelativeUrl);
result.Add(fileInformation);
}
return result;
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("SearchFiles({0}) failed using ClientContext {1}.", url, SharePointSiteUrl), e);
throw;
}
}
#endregion
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using gov.va.medora.utils;
namespace gov.va.medora.mdo
{
/// <summary>
///
/// </summary>
/// <remarks>
/// Contributions by Matt Schmidt (vhaindschmim0) and Robert Ruff (vhawpbruffr)
/// </remarks>
public class SocSecNum
{
protected string myAreaNumber;
protected string myGroupNumber;
protected string mySerialNumber;
const string IssuedByWoolworth = "078051120";
const string SSAPamphlet = "219099999";
protected const string INVALID_SSN = "Invalid SSN";
bool _sensitive;
const string SENSITIVE = "*SENSITIVE*";
public SocSecNum() {}
public SocSecNum(string value)
{
setSSN(value);
}
/// <summary>
/// Use this constructor to create a SocSecNum object without an SSN string. Pass true as the argument
/// and use the SocSecNum.SensitivityString accessor to obtain the sensitivity string
/// </summary>
/// <param name="sensitive">Pass true for sensitive SSNs</param>
public SocSecNum(bool sensitive)
{
_sensitive = sensitive;
}
void setSSN(string value)
{
if (String.IsNullOrEmpty(value))
{
return;
//throw new ArgumentException(INVALID_SSN);
}
if (value.ToUpper().Contains("SENSITIVE"))
{
_sensitive = true;
return;
}
string myValue = StringUtils.removeNonNumericChars(value);
if (myValue.Length != 9 || !StringUtils.isNumeric(myValue))
{
throw new ArgumentException(INVALID_SSN);
}
myAreaNumber = stripField(myValue, 1);
myGroupNumber = stripField(myValue, 2);
mySerialNumber = stripField(myValue, 3);
}
/// <summary>
/// Returns the constant sensitivity string (*SENSITIVE*)
/// </summary>
public string SensitivityString
{
get { return SENSITIVE; }
}
/// <summary>
/// Sensitive setting accessor
/// </summary>
public bool Sensitive
{
get { return _sensitive; }
set { _sensitive = value; }
}
public string AreaNumber
{
get { return myAreaNumber; }
set
{
myAreaNumber = value;
if (!IsValidAreaNumber)
{
throw new ArgumentException("Invalid area number");
}
}
}
public string GroupNumber
{
get { return myGroupNumber; }
set
{
myGroupNumber = value;
if (!IsValidGroupNumber)
{
throw new ArgumentException("Invalid group number");
}
}
}
public string SerialNumber
{
get { return mySerialNumber; }
set
{
mySerialNumber = value;
if (!IsValidSerialNumber)
{
throw new ArgumentException("Invalid serial number");
}
}
}
internal string setIfNumeric(string s)
{
if (!StringUtils.isNumeric(s))
{
throw new ArgumentException(INVALID_SSN);
}
return s;
}
public bool IsWellFormedAreaNumber
{
get { return isWellFormedAreaNumber(myAreaNumber); }
}
public static bool isWellFormedAreaNumber(string value)
{
if (value.Length != 3 || !StringUtils.isNumeric(value))
{
return false;
}
return true;
}
public virtual bool IsValidAreaNumber
{
get { return isValidAreaNumber(myAreaNumber); }
}
public static bool isValidAreaNumber(string value)
{
if (!isWellFormedAreaNumber(value))
{
return false;
}
int iAreaNumber = Convert.ToInt16(value);
if (iAreaNumber == 0 ||
(iAreaNumber > 649 && iAreaNumber < 700) ||
(iAreaNumber > 772))
{
return false;
}
return true;
}
public bool IsWellFormedGroupNumber
{
get { return isWellFormedGroupNumber(myGroupNumber); }
}
public static bool isWellFormedGroupNumber(string value)
{
if (value.Length != 2 || !StringUtils.isNumeric(value))
{
return false;
}
return true;
}
public bool IsValidGroupNumber
{
get { return isValidGroupNumber(myGroupNumber); }
}
public static bool isValidGroupNumber(string value)
{
if (!isWellFormedGroupNumber(value))
{
return false;
}
return (value != "00");
}
public bool IsWellFormedSerialNumber
{
get { return isWellFormedSerialNumber(mySerialNumber); }
}
public static bool isWellFormedSerialNumber(string value)
{
if (value.Length != 4 || !StringUtils.isNumeric(value))
{
return false;
}
return true;
}
public bool IsValidSerialNumber
{
get { return isValidSerialNumber(mySerialNumber); }
}
public static bool isValidSerialNumber(string value)
{
if (!isWellFormedSerialNumber(value))
{
return false;
}
return (value != "0000");
}
public bool IsWellFormed
{
get { return isWellFormed(toString()); }
}
public static bool isWellFormed(string value)
{
string myValue = StringUtils.removeNonNumericChars(value);
if (myValue.Length != 9 || !StringUtils.isNumeric(myValue))
{
return false;
}
return isWellFormedAreaNumber(stripField(myValue, 1)) &&
isWellFormedGroupNumber(stripField(myValue, 2)) &&
isWellFormedSerialNumber(stripField(myValue, 3));
}
public bool IsValid
{
get { return isValid(toString()); }
}
public static bool isValid(string value)
{
if (!isWellFormed(value))
{
return false;
}
if (value == IssuedByWoolworth || value == SSAPamphlet)
{
return false;
}
return isValidAreaNumber(stripField(value, 1)) &&
isValidGroupNumber(stripField(value, 2)) &&
isValidSerialNumber(stripField(value, 3));
}
public static string stripField(string value, int fldnum)
{
string myValue = StringUtils.removeNonNumericChars(value);
switch (fldnum)
{
case 1:
if (myValue.Length < 3)
{
return "";
}
return myValue.Substring(0, 3);
case 2:
if (myValue.Length < 5)
{
return "";
}
return myValue.Substring(3, 2);
case 3:
if (myValue.Length < 9)
{
return "";
}
return myValue.Substring(5,4);
default:
return "";
}
}
public override string ToString()
{
return this.toString();
}
public virtual string toString()
{
if (_sensitive)
{
return SENSITIVE;
}
return myAreaNumber + myGroupNumber + mySerialNumber;
}
public virtual string toHyphenatedString()
{
if (_sensitive)
{
return SENSITIVE;
}
return myAreaNumber + '-' + myGroupNumber + '-' + mySerialNumber;
}
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Xamarin.Auth
{
/// <summary>
/// An Account that represents an authenticated user of a social network.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class Account
#else
public class Account
#endif
{
/// <summary>
/// The username used as a key when storing this account.
/// </summary>
public virtual string Username { get; set; }
/// <summary>
/// A key-value store associated with this account. These get encrypted when the account is stored.
/// </summary>
public virtual Dictionary<string, string> Properties { get; private set; }
/// <summary>
/// Cookies that are stored with the account for web services that control access using cookies.
/// </summary>
public virtual CookieContainer Cookies { get; private set; }
/// <summary>
/// Initializes a new blank <see cref="Xamarin.Auth.Account"/>.
/// </summary>
public Account ()
: this ("", null, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
public Account (string username)
: this (username, null, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='cookies'>
/// The cookies to be stored with the account.
/// </param>
public Account (string username, CookieContainer cookies)
: this (username, null, cookies)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='properties'>
/// Properties for the account.
/// </param>
public Account (string username, IDictionary<string, string> properties)
: this (username, properties, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='properties'>
/// Properties for the account.
/// </param>
/// <param name='cookies'>
/// The cookies to be stored with the account.
/// </param>
public Account (string username, IDictionary<string, string> properties, CookieContainer cookies)
{
Username = username;
Properties = (properties == null) ?
new Dictionary<string, string> () :
new Dictionary<string, string> (properties);
Cookies = (cookies == null) ?
new CookieContainer () :
cookies;
}
/// <summary>
/// Serialize this account into a string that can be deserialized.
/// </summary>
public string Serialize ()
{
var sb = new StringBuilder ();
sb.Append ("__username__=");
sb.Append (Uri.EscapeDataString (Username));
foreach (var p in Properties) {
sb.Append ("&");
sb.Append (Uri.EscapeDataString (p.Key));
sb.Append ("=");
sb.Append (Uri.EscapeDataString (p.Value));
}
if (Cookies.Count > 0) {
sb.Append ("&__cookies__=");
sb.Append (Uri.EscapeDataString (SerializeCookies ()));
}
return sb.ToString ();
}
/// <summary>
/// Restores an account from its serialized string representation.
/// </summary>
/// <param name='serializedString'>
/// The serialized account generated by <see cref="Serialize"/>
/// </param>
public static Account Deserialize (string serializedString)
{
var acct = new Account ();
foreach (var p in serializedString.Split ('&')) {
var kv = p.Split ('=');
var key = Uri.UnescapeDataString (kv [0]);
var val = kv.Length > 1 ? Uri.UnescapeDataString (kv [1]) : "";
if (key == "__cookies__") {
acct.Cookies = DeserializeCookies (val);
} else if (key == "__username__") {
acct.Username = val;
} else {
acct.Properties [key] = val;
}
}
return acct;
}
string SerializeCookies ()
{
var f = new BinaryFormatter ();
using (var s = new MemoryStream ()) {
f.Serialize (s, Cookies);
return Convert.ToBase64String (s.GetBuffer (), 0, (int)s.Length);
}
}
static CookieContainer DeserializeCookies (string cookiesString)
{
var f = new BinaryFormatter ();
using (var s = new MemoryStream (Convert.FromBase64String (cookiesString))) {
return (CookieContainer)f.Deserialize (s);
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Xamarin.Auth.Account"/>.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the current <see cref="Xamarin.Auth.Account"/>.
/// </returns>
public override string ToString ()
{
return Serialize ();
}
}
}
| |
using CodeHub.Helpers;
using CodeHub.Models;
using HtmlAgilityPack;
using JetBrains.Annotations;
using Octokit;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
using static CodeHub.ViewModels.TrendingViewmodel;
namespace CodeHub.Services
{
class RepositoryUtility
{
/// <summary>
/// Returns trending repos. First call (second parameter = true) returns first 7 repositories,
/// Second call (second parameter = false) returns the rest
///</summary>
/// <param name="range">Today, weekly or monthly</param>
/// <param name="firstCall">Indicates if this is the first call in incremental calls or not</param>
/// <returns>Trending Repositories in a Time range</returns>
public static async Task<ObservableCollection<Repository>> GetTrendingRepos(TimeRange range, bool firstCall)
{
try
{
var repos = new ObservableCollection<Repository>();
var repoNames = new List<(string, string)>();
if (firstCall)
{
repoNames = await HtmlParseService.ExtractTrendingRepos(range);
}
else
{
switch (range)
{
case TimeRange.TODAY:
repoNames = GlobalHelper.TrendingTodayRepoNames;
break;
case TimeRange.WEEKLY:
repoNames = GlobalHelper.TrendingWeekRepoNames;
break;
case TimeRange.MONTHLY:
repoNames = GlobalHelper.TrendingMonthRepoNames;
break;
}
}
if (firstCall)
{
for (int i = 0; i < 7; i++)
{
repos.Add(await GlobalHelper.GithubClient.Repository.Get(repoNames[i].Item1, repoNames[i].Item2));
}
}
else
{
for (int i = 7; i < repoNames.Count; i++)
{
repos.Add(await GlobalHelper.GithubClient.Repository.Get(repoNames[i].Item1, repoNames[i].Item2));
}
}
return repos;
}
catch
{
return null;
}
}
/// <summary>
/// Gets names of all branches of a given repository
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<ObservableCollection<string>> GetAllBranches(Repository repo)
{
try
{
var branches = await GlobalHelper.GithubClient.Repository.Branch.GetAll(repo.Owner.Login, repo.Name);
var branchList = new ObservableCollection<string>();
foreach (Branch i in branches)
{
branchList.Add(i.Name);
}
return branchList;
}
catch
{
return null;
}
}
/// <summary>
/// Gets a specified Repository
/// </summary>
/// <param name="ownerName"></param>
/// <param name="repoName"></param>
/// <returns></returns>
public static async Task<Repository> GetRepository(string ownerName, string repoName)
{
try
{
return await GlobalHelper.GithubClient.Repository.Get(ownerName, repoName);
}
catch
{
return null;
}
}
/// <summary>
/// Gets a specified Repository
/// </summary>
/// <param name="repoId"></param>
/// <returns></returns>
public static async Task<Repository> GetRepository(long repoId)
{
try
{
return await GlobalHelper.GithubClient.Repository.Get(repoId);
}
catch
{
return null;
}
}
#region Files info parsing
/// <summary>
/// Returns a wrapped repository content with all the additional info that can be retrieved from the associated HTML page
/// </summary>
/// <param name="contentTask">The task with the contents to load</param>
/// <param name="htmlUrl">The URL to the repository page</param>
/// <param name="client">The GitHubClient to manually retrieve the commits</param>
/// <param name="repoId">The id of the current repository</param>
/// <param name="branch">The name of the current branch to load</param>
/// <param name="token">The cancellation token for the operation</param>
[ItemCanBeNull]
public static async Task<IEnumerable<RepositoryContentWithCommitInfo>> TryLoadLinkedCommitDataAsync(
[NotNull] Task<IReadOnlyList<RepositoryContent>> contentTask, [NotNull] string htmlUrl,
[NotNull] GitHubClient client, long repoId, [NotNull] string branch, CancellationToken token)
{
// Try to download the file info
IReadOnlyList<RepositoryContent> contents = null;
try
{
// Load the full HTML body
var view = new WebView();
var tcs = new TaskCompletionSource<string>();
view.NavigationCompleted += (s, e) =>
{
view.InvokeScriptAsync("eval", new[] { "document.documentElement.outerHTML;" }).AsTask().ContinueWith(t =>
{
tcs.SetResult(t.Status == TaskStatus.RanToCompletion ? t.Result : null);
});
};
// Manually set the user agent to get the full desktop site
var userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/7.0; Touch; rv:11.0; WPDesktop) like Gecko";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(htmlUrl));
httpRequestMessage.Headers.Append("User-Agent", userAgent);
view.NavigateWithHttpRequestMessage(httpRequestMessage);
// Run the web calls in parallel
await Task.WhenAll(contentTask, tcs.Task);
contents = contentTask.Result;
var html = tcs.Task.Result;
if (token.IsCancellationRequested)
{
return contents?.OrderByDescending(entry => entry.Type.Value).Select(content => new RepositoryContentWithCommitInfo(content));
}
// Load the HTML document
var document = new HtmlDocument();
document.LoadHtml(html);
/* =================
* HTML error tags
* =================
* ...
* <include-fragment class="commit-tease commit-loader">
* ...
* <div class="loader-error"/>
* </include-fragment>
* ... */
// Check if the HTML loading was successful
if (document.DocumentNode
?.Descendants("include-fragment") // Get the <include-fragment/> nodes
?.FirstOrDefault(node => node.Attributes?.AttributesWithName("class") // Get the nodes with a class attribute
?.FirstOrDefault(att => att.Value?.Equals("commit-tease commit-loader") == true) // That attribute must have this name
!= null) // There must be a node with these specs if the HTML loading failed
?.Descendants("div") // Get the inner <div/> nodes
?.FirstOrDefault(node => node.Attributes?.AttributesWithName("class")?.FirstOrDefault() // Check the class name
?.Value?.Equals("loader-error") == true) != null || // Make sure there was in fact a loading error
html.Contains("class=\"warning include - fragment - error\"") ||
html.Contains("Failed to load latest commit information"))
{
System.Diagnostics.Debug.WriteLine("[DEBUG] Fallback");
// Use the Oktokit APIs to get the info
var tasks = contents.Select(r => client.Repository.Commit.GetAll(repoId,
new CommitRequest { Path = r.Path, Sha = branch }, // Only get the commits that edited the current file
new ApiOptions { PageCount = 1, PageSize = 1 })); // Just get the latest commit for this file
var commits = await Task.WhenAll(tasks);
// Query the results
return contents.AsParallel().OrderByDescending(file => file.Type.Value).Select((file, i) =>
{
GitHubCommit commit = commits[i].FirstOrDefault();
return commit != null
? new RepositoryContentWithCommitInfo(file, commit, null, commit.Commit.Committer.Date.DateTime)
: new RepositoryContentWithCommitInfo(file);
});
}
System.Diagnostics.Debug.WriteLine("[DEBUG] HTML parsing");
/* ================
* HTML STRUCTURE
* ================
* ...
* <tr class="js-navigation-item">
* ...
* <td class="content">
* <span ...>
* <a href="CONTENT_URL">...</a>
* </span>
* </td>
* <td class="message">
* <span ...>
* [...]?
* <a title="COMMIT_MESSAGE">...</a>
* </span>
* </td>
* <td class="age">
* <span ...>
* <time-ago datetime="EDIT_TIME">...</a>
* </span>
* </td>
* ... */
// Try to extract the commit info, in parallel
var cores = Environment.ProcessorCount;
var partials =
(from i in Enumerable.Range(1, cores)
let list = new List<RepositoryContentWithCommitInfo>()
select list).ToArray();
var result = Parallel.For(0, cores, new ParallelOptions { MaxDegreeOfParallelism = cores }, workerId =>
{
int max = contents.Count * (workerId + 1) / cores;
for (int i = contents.Count * workerId / cores; i < max; i++)
{
// Find the right node
var element = contents[i];
HtmlNode target = document.DocumentNode?.Descendants("a")?
.FirstOrDefault(child => child.Attributes?.AttributesWithName("id")?
.FirstOrDefault()?.Value?.EndsWith(element.Sha) == true);
// Parse the node contents
if (target != null)
{
// Get the commit and time nodes
HtmlNode
messageRoot = target.Ancestors("td")?.FirstOrDefault()?.Siblings()?.FirstOrDefault(node => node.Name.Equals("td")),
timeRoot = messageRoot?.Siblings()?.FirstOrDefault(node => node.Name.Equals("td"));
HtmlAttribute
messageTitle = messageRoot?
.Descendants("a")?
.Select(node => node.Attributes?.AttributesWithName("title")?.FirstOrDefault())?
.FirstOrDefault(node => node != null),
timestamp = timeRoot?
.Descendants("time-ago")?
.FirstOrDefault()?
.Attributes?
.AttributesWithName("datetime")?
.FirstOrDefault();
// Fix the message, if present
var message = messageTitle?.Value;
if (message != null)
{
message = WebUtility.HtmlDecode(message); // Remove HTML-encoded characters
message = Regex.Replace(message, @":[^:]+: ?| ?:[^:]+:", string.Empty); // Remove GitHub emojis
}
// Add the parsed contents
if (timestamp?.Value != null)
{
if (DateTime.TryParse(timestamp.Value, out DateTime time))
{
partials[workerId].Add(new RepositoryContentWithCommitInfo(element, null, message, time));
continue;
}
}
partials[workerId].Add(new RepositoryContentWithCommitInfo(element, null, message));
continue;
}
partials[workerId].Add(new RepositoryContentWithCommitInfo(element));
}
});
if (!result.IsCompleted)
{
throw new InvalidOperationException();
}
return partials.SelectMany(list => list).OrderByDescending(entry => entry.Content.Type.Value);
}
catch
{
// Just return the original content without additional info
return contents?.OrderByDescending(entry => entry.Type.Value).Select(content => new RepositoryContentWithCommitInfo(content));
}
}
#endregion
/// <summary>
/// Gets contents of a given repository, branch and path (Text)
/// </summary>
/// <param name="repo"></param>
/// <param name="path"></param>
/// <param name="branch"></param>
/// <returns></returns>
public static async Task<RepositoryContent> GetRepositoryContentTextByPath(Repository repo, string path, string branch)
{
try
{
var results = await GlobalHelper.GithubClient.Repository.Content.GetAllContentsByRef(repo.Id, path, branch);
return results.First();
}
catch
{
return null;
}
}
/// <summary>
/// Gets contents of a given repository and branch
/// </summary>
/// <param name="repo"></param>
/// <param name="branch"></param>
/// <returns></returns>
public static async Task<ObservableCollection<RepositoryContentWithCommitInfo>> GetRepositoryContent(Repository repo, string branch)
{
try
{
IEnumerable<RepositoryContentWithCommitInfo> results;
if (SettingsService.Get<bool>(SettingsKeys.LoadCommitsInfo))
{
results = await TryLoadLinkedCommitDataAsync(
GlobalHelper.GithubClient.Repository.Content.GetAllContentsByRef(repo.Owner.Login, repo.Name, branch), repo.HtmlUrl,
GlobalHelper.GithubClient, repo.Id, branch, CancellationToken.None);
return new ObservableCollection<RepositoryContentWithCommitInfo>(results.OrderByDescending(entry => entry.Content.Type.Value)
.ThenBy(entry => entry.Content.Name));
}
else
{
results = from item in await GlobalHelper.GithubClient.Repository.Content.GetAllContentsByRef(repo.Owner.Login, repo.Name, branch)
select new RepositoryContentWithCommitInfo(item);
return new ObservableCollection<RepositoryContentWithCommitInfo>(results.OrderByDescending(entry => entry.Content.Type.Value));
}
}
catch
{
return null;
}
}
/// <summary>
/// Gets contents of a given repository, branch and path (HTML)
/// </summary>
/// <param name="repo"></param>
/// <param name="path"></param>
/// <param name="branch"></param>
/// <returns></returns>
public static async Task<ObservableCollection<RepositoryContentWithCommitInfo>> GetRepositoryContentByPath(Repository repo, string path, string branch)
{
try
{
var url = $"{repo.HtmlUrl}/tree/{branch}/{path}";
IEnumerable<RepositoryContentWithCommitInfo> results;
if (SettingsService.Get<bool>(SettingsKeys.LoadCommitsInfo))
{
results = await TryLoadLinkedCommitDataAsync(
GlobalHelper.GithubClient.Repository.Content.GetAllContentsByRef(repo.Id, path, branch), url,
GlobalHelper.GithubClient, repo.Id, branch, CancellationToken.None);
return new ObservableCollection<RepositoryContentWithCommitInfo>(results);
}
else
{
results = from item in await GlobalHelper.GithubClient.Repository.Content.GetAllContentsByRef(repo.Id, path, branch)
select new RepositoryContentWithCommitInfo(item);
return new ObservableCollection<RepositoryContentWithCommitInfo>(results.OrderByDescending(entry => entry.Content.Type.Value));
}
}
catch
{
return null;
}
}
#region Issue
/// <summary>
/// Gets all issues for a given repository
/// </summary>
/// <param name="repoId"></param>
/// <param name="filter"></param>
/// <returns></returns>
public static async Task<ObservableCollection<Issue>> GetAllIssuesForRepo(long repoId, RepositoryIssueRequest filter, int pageIndex)
{
try
{
var options = new ApiOptions
{
PageCount = 1,
PageSize = 10,
StartPage = pageIndex
};
var issues = await GlobalHelper.GithubClient.Issue.GetAllForRepository(repoId, filter, options);
return new ObservableCollection<Issue>(issues);
}
catch
{
return null;
}
}
#endregion
#region PR
/// <summary>
/// Gets all PRs for a given repository
/// </summary>
/// <param name="repoId"></param>
/// <param name="filter"></param>
/// <returns></returns>
public static async Task<ObservableCollection<PullRequest>> GetAllPullRequestsForRepo(long repoId, PullRequestRequest filter, int pageIndex)
{
try
{
var options = new ApiOptions
{
PageCount = 1,
PageSize = 10,
StartPage = pageIndex
};
var prList = await GlobalHelper.GithubClient.PullRequest.GetAllForRepository(repoId, filter, options);
return new ObservableCollection<PullRequest>(prList);
}
catch
{
return null;
}
}
#endregion
/// <summary>
/// Gets all repositories owned by a given user
/// </summary>
/// <param name="login"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public static async Task<ObservableCollection<Repository>> GetRepositoriesForUser(string login, int pageIndex)
{
try
{
var options = new ApiOptions
{
PageSize = 5,
PageCount = 1,
StartPage = pageIndex
};
var result = await GlobalHelper.GithubClient.Repository.GetAllForUser(login, options);
return new ObservableCollection<Repository>(result);
}
catch
{
return null;
}
}
/// <summary>
/// Gets all repositories starred by a given user
/// </summary>
/// <param name="login"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public static async Task<ObservableCollection<Repository>> GetStarredRepositoriesForUser(string login, int pageIndex)
{
try
{
var options = new ApiOptions
{
PageSize = 5,
PageCount = 1,
StartPage = pageIndex
};
var result = await GlobalHelper.GithubClient.Activity.Starring.GetAllForUser(login, options);
return new ObservableCollection<Repository>(result);
}
catch
{
return null;
}
}
/// <summary>
/// Gets the preferred README's HTML for a repository
/// </summary>
/// <param name="repoId">Repsitory Id</param>
/// <returns></returns>
public static async Task<string> GetReadmeHTMLForRepository(long repoId)
{
try
{
return await GlobalHelper.GithubClient.Repository.Content.GetReadmeHtml(repoId);
}
catch
{
return null;
}
}
/// <summary>
/// Gets the preferred README for a repository
/// </summary>
/// <param name="repoId">Repsitory Id</param>
/// <returns></returns>
public static async Task<Readme> GetReadmeForRepository(long repoId)
{
try
{
return await GlobalHelper.GithubClient.Repository.Content.GetReadme(repoId);
}
catch
{
return null;
}
}
/// <summary>
/// Gets default branch for a given repository
/// </summary>
/// <param name="repoId"></param>
/// <returns></returns>
public static async Task<string> GetDefaultBranch(long repoId)
{
try
{
var repo = await GlobalHelper.GithubClient.Repository.Get(repoId);
return repo.DefaultBranch;
}
catch
{
return null;
}
}
/// <summary>
/// Stars a given reposiory
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> StarRepository(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Activity.Starring.StarRepo(repo.Owner.Login, repo.Name);
}
catch
{
return false;
}
}
/// <summary>
/// Unstars a given repository
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> UnstarRepository(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Activity.Starring.RemoveStarFromRepo(repo.Owner.Login, repo.Name);
}
catch
{
return false;
}
}
/// <summary>
/// Watches a repository
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> WatchRepository(Repository repo)
{
try
{
return (await GlobalHelper.GithubClient.Activity.Watching.WatchRepo(repo.Id, new NewSubscription { Subscribed = true })).Subscribed;
}
catch
{
return false;
}
}
/// <summary>
/// Unwatches a repository
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> UnwatchRepository(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Activity.Watching.UnwatchRepo(repo.Id);
}
catch
{
return false;
}
}
/// <summary>
/// Forks a repository
/// </summary>
/// <param name="repo"></param>
/// <returns>Forked repository</returns>
public static async Task<Repository> ForkRepository(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Repository.Forks.Create(repo.Id, new NewRepositoryFork());
}
catch
{
return null;
}
}
/// <summary>
/// Checks if a repository is watched by the authorized user
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> CheckWatched(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Activity.Watching.CheckWatched(repo.Id);
}
catch
{
return false;
}
}
/// <summary>
/// Checks if a repository is starred by the authorized user
/// </summary>
/// <param name="repo"></param>
/// <returns></returns>
public static async Task<bool> CheckStarred(Repository repo)
{
try
{
return await GlobalHelper.GithubClient.Activity.Starring.CheckStarred(repo.Owner.Login, repo.Name);
}
catch
{
return false;
}
}
/// <summary>
/// Gets all commits for a given file path
/// </summary>
/// <param name="repoId">Repository Id</param>
/// <param name="path">file path</param>
/// <returns></returns>
public static async Task<ObservableCollection<GitHubCommit>> GetAllCommitsForFile(long repoId, string path)
{
try
{
var request = new CommitRequest { Path = path };
var list = await GlobalHelper.GithubClient.Repository.Commit.GetAll(repoId, request);
return new ObservableCollection<GitHubCommit>(list);
}
catch
{
return null;
}
}
/// <summary>
/// Gets all contributors for a repository
/// </summary>
/// <param name="repoId"></param>
/// <returns></returns>
public static async Task<ObservableCollection<RepositoryContributor>> GetContributorsForRepository(long repoId)
{
try
{
var options = new ApiOptions
{
PageCount = 1,
PageSize = 100
};
var users = await GlobalHelper.GithubClient.Repository.GetAllContributors(repoId, options);
return new ObservableCollection<RepositoryContributor>(users);
}
catch
{
return null;
}
}
/// <summary>
/// Gets all releases for a repository
/// </summary>
/// <param name="repoId"></param>
/// <returns></returns>
public static async Task<ObservableCollection<Release>> GetReleasesForRepository(long repoId)
{
try
{
var releases = await GlobalHelper.GithubClient.Repository.Release.GetAll(repoId);
return new ObservableCollection<Release>(releases);
}
catch
{
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using BEPUphysics.Entities;
using BEPUutilities.DataStructures;
using BEPUphysics.UpdateableSystems;
namespace BEPUphysics.Vehicle
{
/// <summary>
/// Simulates wheeled vehicles using a variety of constraints and shape casts.
/// </summary>
public class Vehicle : CombinedUpdateable, IDuringForcesUpdateable, IBeforeNarrowPhaseUpdateable, IEndOfTimeStepUpdateable, IEndOfFrameUpdateable
{
//TODO: The vehicle uses wheel 'fake constraints' that were made prior to the changes to the constraint system that allow for customizable solver settings.
//It would be convenient to use a SolverGroup to handle the wheel constraints, since the functionality is nearly the same.
private readonly List<Wheel> wheels = new List<Wheel>();
private Entity body;
internal List<Entity> previousSupports = new List<Entity>();
/// <summary>
/// Constructs a vehicle.
/// </summary>
/// <param name="shape">Body of the vehicle.</param>
public Vehicle(Entity shape)
{
IsUpdatedSequentially = false;
Body = shape;
Body.activityInformation.IsAlwaysActive = true;
//The body is always active, so don't bother with stabilization either.
//Stabilization can introduce artifacts as well.
body.activityInformation.AllowStabilization = false;
}
/// <summary>
/// Constructs a vehicle.
/// </summary>
/// <param name="shape">Body of the vehicle.</param>
/// <param name="wheelList">List of wheels of the vehicle.</param>
public Vehicle(Entity shape, IEnumerable<Wheel> wheelList)
{
IsUpdatedSequentially = false;
Body = shape;
Body.activityInformation.IsAlwaysActive = true;
//The body is always active, so don't bother with stabilization either.
//Stabilization can introduce artifacts as well.
body.activityInformation.AllowStabilization = false;
foreach (Wheel wheel in wheelList)
{
AddWheel(wheel);
}
}
/// <summary>
/// Gets or sets the entity representing the shape of the car.
/// </summary>
public Entity Body
{
get { return body; }
set
{
body = value;
OnInvolvedEntitiesChanged();
}
}
/// <summary>
/// Number of wheels with supports.
/// </summary>
public int SupportedWheelCount
{
get
{
int toReturn = 0;
foreach (Wheel wheel in Wheels)
{
if (wheel.HasSupport)
toReturn++;
}
return toReturn;
}
}
/// <summary>
/// Gets the list of wheels supporting the vehicle.
/// </summary>
public ReadOnlyList<Wheel> Wheels
{
get { return new ReadOnlyList<Wheel>(wheels); }
}
/// <summary>
/// Sets up the vehicle's information when being added to the space.
/// Called automatically when the space adds the vehicle.
/// </summary>
/// <param name="newSpace">New owning space.</param>
public override void OnAdditionToSpace(Space newSpace)
{
newSpace.Add(body);
foreach (Wheel wheel in Wheels)
{
wheel.OnAdditionToSpace(newSpace);
}
}
/// <summary>
/// Sets up the vehicle's information when being added to the space.
/// Called automatically when the space adds the vehicle.
/// </summary>
public override void OnRemovalFromSpace(Space oldSpace)
{
foreach (Wheel wheel in Wheels)
{
wheel.OnRemovalFromSpace(oldSpace);
}
oldSpace.Remove(Body);
}
/// <summary>
/// Performs the end-of-frame update component.
/// </summary>
/// <param name="dt">Time since last frame in simulation seconds.</param>
void IEndOfFrameUpdateable.Update(float dt)
{
//Graphics should be updated at the end of each frame.
foreach (Wheel wheel in Wheels)
{
wheel.UpdateAtEndOfFrame(dt);
}
}
/// <summary>
/// Performs the end-of-update update component.
/// </summary>
/// <param name="dt">Time since last frame in simulation seconds.</param>
void IEndOfTimeStepUpdateable.Update(float dt)
{
//Graphics should be updated at the end of each frame.
foreach (Wheel wheel in Wheels)
{
wheel.UpdateAtEndOfUpdate(dt);
}
}
void IBeforeNarrowPhaseUpdateable.Update(float dt)
{
//After broadphase, test for supports.
foreach (Wheel wheel in wheels)
{
wheel.FindSupport();
}
OnInvolvedEntitiesChanged();
}
void IDuringForcesUpdateable.Update(float dt)
{
foreach (Wheel wheel in wheels)
{
wheel.UpdateDuringForces(dt);
}
}
/// <summary>
/// Adds a wheel to the vehicle.
/// </summary>
/// <param name="wheel">WheelTest to add.</param>
public void AddWheel(Wheel wheel)
{
if (wheel.vehicle == null)
{
wheels.Add(wheel);
wheel.OnAddedToVehicle(this);
}
else
throw new InvalidOperationException("Can't add a wheel to a vehicle if it already belongs to a vehicle.");
}
/// <summary>
/// Removes a wheel from the vehicle.
/// </summary>
/// <param name="wheel">WheelTest to remove.</param>
public void RemoveWheel(Wheel wheel)
{
if (wheel.vehicle == this)
{
wheel.OnRemovedFromVehicle();
wheels.Remove(wheel);
}
else
throw new InvalidOperationException("Can't remove a wheel from a vehicle that does not own it.");
}
/// <summary>
/// Updates the vehicle.
/// Called automatically when needed by the owning Space.
/// </summary>
public override float SolveIteration()
{
int numActive = 0;
foreach (Wheel wheel in Wheels)
{
if (wheel.isActiveInSolver)
if (!wheel.ApplyImpulse())
wheel.isActiveInSolver = false;
else
numActive++;
}
if (numActive == 0)
isActiveInSolver = false;
return solverSettings.minimumImpulse + 1; //We take care of ourselves.
}
/// <summary>
/// Adds entities associated with the solver item to the involved entities list.
/// Ensure that sortInvolvedEntities() is called at the end of the function.
/// This allows the non-batched multithreading system to lock properly.
/// </summary>
protected internal override void CollectInvolvedEntities(RawList<Entity> outputInvolvedEntities)
{
outputInvolvedEntities.Add(Body);
foreach (Wheel wheel in Wheels)
{
if (wheel.supportingEntity != null && !outputInvolvedEntities.Contains(wheel.supportingEntity))
outputInvolvedEntities.Add(wheel.supportingEntity);
}
}
/// <summary>
/// Computes information required during the later update.
/// Called once before the iteration loop.
/// </summary>
/// <param name="dt">Time since previous frame in simulation seconds.</param>
public override void Update(float dt)
{
//TODO: to help balance multithreading, what if each wheel were its own SolverUpdateable
//(no more CombinedUpdateable, basically)
//This might be okay, but chances are if each was totally isolated, the 'enter exit'
//of the monitor would be more expensive than just going in all at once and leaving at once.
//Maybe a SolverGroup instead of CombinedUpdateable, though.
//Update the wheel 'constraints.'
foreach (Wheel wheel in Wheels)
{
if (wheel.isActiveInSolver)
wheel.PreStep(dt);
}
}
/// <summary>
/// Performs any pre-solve iteration work that needs exclusive
/// access to the members of the solver updateable.
/// Usually, this is used for applying warmstarting impulses.
/// </summary>
public override void ExclusiveUpdate()
{
foreach (Wheel wheel in Wheels)
{
if (wheel.isActiveInSolver)
wheel.ExclusiveUpdate();
}
}
/// <summary>
/// Updates the activity state of the wheel constraints.
/// </summary>
public override void UpdateSolverActivity()
{
if (isActive)
{
isActiveInSolver = false;
if (body.activityInformation.IsActive)
{
foreach (Wheel wheel in Wheels)
{
wheel.UpdateSolverActivity();
isActiveInSolver = isActiveInSolver || wheel.isActiveInSolver;
}
}
}
else
isActiveInSolver = false;
}
}
}
| |
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace
{
public enum Phase { Setup, Processing, Complete };
public class AssetUsageDetectorWindow : EditorWindow, IHasCustomMenu
{
private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew };
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties";
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks";
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );
private readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f );
private GUIStyle lockButtonStyle;
private readonly AssetUsageDetector core = new AssetUsageDetector();
private SearchResult searchResult; // Overall search results
// This isn't readonly so that it can be serialized
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
#pragma warning disable 0649
[SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked
private bool m_isLocked;
private bool IsLocked
{
get { return m_isLocked; }
set
{
if( m_isLocked != value )
{
m_isLocked = value;
titleContent = value ? new GUIContent( "[L] " + windowTitle.text, EditorGUIUtility.IconContent( "InspectorLock" ).image ) : windowTitle;
}
}
}
#pragma warning restore 0649
private Phase currentPhase = Phase.Setup;
private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view
private bool searchInScenesInBuild = true; // Scenes in build
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
private bool searchInAssetsFolder = true; // Assets in Project window
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
private List<Object> searchInAssetsSubset = new List<Object>() { null }; // If not empty, only these assets are searched for references
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool lazySceneSearch = true;
private bool searchNonSerializableVariables = true;
private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false;
private bool hideDuplicateRows = true;
private bool hideReduntantPrefabVariantLinks = true;
private bool noAssetDatabaseChanges = false;
private bool showDetailedProgressBar = true;
private BindingFlags fieldModifiers, propertyModifiers;
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );
private bool drawObjectsToSearchSection = true;
private Vector2 scrollPosition = Vector2.zero;
private bool shouldRepositionSelf;
private Rect windowTargetPosition;
void IHasCustomMenu.AddItemsToMenu( GenericMenu contextMenu )
{
contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked );
contextMenu.AddSeparator( "" );
#if UNITY_2018_3_OR_NEWER
contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) );
#else
contextMenu.AddItem( new GUIContent( "Settings" ), false, () =>
{
System.Type preferencesWindowType = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.PreferencesWindow" );
preferencesWindowType.GetMethod( "ShowPreferencesWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).Invoke( null, null );
EditorWindow preferencesWindow = GetWindow( preferencesWindowType );
if( (bool) preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow ) )
{
preferencesWindowType.GetMethod( "AddCustomSections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( preferencesWindow, null );
preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, false );
}
int targetSectionIndex = -1;
System.Collections.IList sections = (System.Collections.IList) preferencesWindowType.GetField( "m_Sections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow );
for( int i = 0; i < sections.Count; i++ )
{
if( ( (GUIContent) sections[i].GetType().GetField( "content", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( sections[i] ) ).text == "Asset Usage Detector" )
{
targetSectionIndex = i;
break;
}
}
if( targetSectionIndex >= 0 )
preferencesWindowType.GetProperty( "selectedSectionIndex", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, targetSectionIndex, null );
} );
#endif
if( currentPhase == Phase.Setup )
{
contextMenu.AddSeparator( "" );
contextMenu.AddItem( new GUIContent( "Refresh Sub-Assets of Searched Objects" ), false, () =>
{
for( int i = objectsToSearch.Count - 1; i >= 0; i-- )
objectsToSearch[i].RefreshSubAssets();
} );
}
}
// Shows lock button at the top-right corner
// Credit: http://leahayes.co.uk/2013/04/30/adding-the-little-padlock-button-to-your-editorwindow.html
private void ShowButton( Rect position )
{
if( lockButtonStyle == null )
lockButtonStyle = "IN LockButton";
IsLocked = GUI.Toggle( position, IsLocked, GUIContent.none, lockButtonStyle );
}
private static AssetUsageDetectorWindow GetWindow( WindowFilter filter )
{
AssetUsageDetectorWindow[] windows = Resources.FindObjectsOfTypeAll<AssetUsageDetectorWindow>();
AssetUsageDetectorWindow window = System.Array.Find( windows, ( w ) => w && !w.IsLocked );
if( !window )
window = System.Array.Find( windows, ( w ) => w );
if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
{
window.Show();
window.Focus();
return window;
}
Rect? windowTargetPosition = null;
if( window )
{
Rect position = window.position;
position.position += new Vector2( 50f, 50f );
windowTargetPosition = position;
}
window = CreateInstance<AssetUsageDetectorWindow>();
window.titleContent = windowTitle;
window.minSize = windowMinSize;
if( windowTargetPosition.HasValue )
{
window.shouldRepositionSelf = true;
window.windowTargetPosition = windowTargetPosition.Value;
}
window.Show( true );
window.Focus();
return window;
}
[MenuItem( "Window/Asset Usage Detector/Active Window" )]
private static void OpenActiveWindow()
{
GetWindow( WindowFilter.AlwaysReturnActive );
}
[MenuItem( "Window/Asset Usage Detector/New Window" )]
private static void OpenNewWindow()
{
GetWindow( WindowFilter.AlwaysReturnNew );
}
// Quickly initiate search for the selected assets
[MenuItem( "GameObject/Search for References/This Object Only", priority = 49 )]
[MenuItem( "Assets/Search for References", priority = 1000 )]
private static void SearchSelectedAssetReferences( MenuCommand command )
{
// This happens when this button is clicked via hierarchy's right click context menu
// and is called once for each object in the selection. We don't want that, we want
// the function to be called only once
if( command.context )
{
EditorApplication.update -= CallSearchSelectedAssetReferencesOnce;
EditorApplication.update += CallSearchSelectedAssetReferencesOnce;
}
else
ShowAndSearch( Selection.objects );
}
[MenuItem( "GameObject/Search for References/Include Children", priority = 49 )]
private static void SearchSelectedAssetReferencesWithChildren( MenuCommand command )
{
if( command.context )
{
EditorApplication.update -= CallSearchSelectedAssetReferencesWithChildrenOnce;
EditorApplication.update += CallSearchSelectedAssetReferencesWithChildrenOnce;
}
else
ShowAndSearch( Selection.objects, true );
}
// Show the menu item only if there is a selection in the Editor
[MenuItem( "GameObject/Search for References/This Object Only", validate = true )]
[MenuItem( "GameObject/Search for References/Include Children", validate = true )]
[MenuItem( "Assets/Search for References", validate = true )]
private static bool SearchSelectedAssetReferencesValidate( MenuCommand command )
{
return Selection.objects.Length > 0;
}
// Quickly show the AssetUsageDetector window and initiate a search
public static void ShowAndSearch( IEnumerable<Object> searchObjects, bool? shouldSearchChildren = null )
{
GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchObjects, null, shouldSearchChildren );
}
// Quickly show the AssetUsageDetector window and initiate a search
public static void ShowAndSearch( AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren = null )
{
if( searchParameters == null )
{
Debug.LogError( "searchParameters can't be null!" );
return;
}
GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren );
}
private static void CallSearchSelectedAssetReferencesOnce()
{
EditorApplication.update -= CallSearchSelectedAssetReferencesOnce;
SearchSelectedAssetReferences( new MenuCommand( null ) );
}
private static void CallSearchSelectedAssetReferencesWithChildrenOnce()
{
EditorApplication.update -= CallSearchSelectedAssetReferencesWithChildrenOnce;
SearchSelectedAssetReferencesWithChildren( new MenuCommand( null ) );
}
private void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren )
{
if( !ReturnToSetupPhase() )
{
Debug.LogError( "Need to reset the previous search first!" );
return;
}
objectsToSearch.Clear();
if( searchObjects != null )
{
foreach( Object obj in searchObjects )
objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) );
}
if( searchParameters != null )
{
ParseSceneSearchMode( searchParameters.searchInScenes );
searchInAssetsFolder = searchParameters.searchInAssetsFolder;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchInProjectSettings = searchParameters.searchInProjectSettings;
searchDepthLimit = searchParameters.searchDepthLimit;
fieldModifiers = searchParameters.fieldModifiers;
propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch;
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows;
hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks;
noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
showDetailedProgressBar = searchParameters.showDetailedProgressBar;
searchInAssetsSubset.Clear();
if( searchParameters.searchInAssetsSubset != null )
{
foreach( Object obj in searchParameters.searchInAssetsSubset )
searchInAssetsSubset.Add( obj );
}
excludedAssets.Clear();
if( searchParameters.excludedAssetsFromSearch != null )
{
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
excludedAssets.Add( obj );
}
excludedScenes.Clear();
if( searchParameters.excludedScenesFromSearch != null )
{
foreach( Object obj in searchParameters.excludedScenesFromSearch )
excludedScenes.Add( obj );
}
}
InitiateSearch();
Repaint();
}
private void Awake()
{
LoadPrefs();
}
private void OnEnable()
{
if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip )
wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
#endif
}
private void OnDisable()
{
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
#endif
SearchResultTooltip.Hide();
}
private void OnDestroy()
{
if( core != null )
core.SaveCache();
SavePrefs();
if( searchResult != null && currentPhase == Phase.Complete )
searchResult.RestoreInitialSceneSetup();
}
private void SavePrefs()
{
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers );
EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers );
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks );
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
}
private void LoadPrefs()
{
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
fieldModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_FIELDS, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
propertyModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_PROPERTIES, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true );
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
}
private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
{
SceneSearchMode sceneSearchMode = SceneSearchMode.None;
if( searchInOpenScenes )
sceneSearchMode |= SceneSearchMode.OpenScenes;
if( !hideOptionsInPlayMode || !EditorApplication.isPlaying )
{
if( searchInScenesInBuild )
sceneSearchMode |= searchInScenesInBuildTickedOnly ? SceneSearchMode.ScenesInBuildSettingsTickedOnly : SceneSearchMode.ScenesInBuildSettingsAll;
if( searchInAllScenes )
sceneSearchMode |= SceneSearchMode.AllScenes;
}
return sceneSearchMode;
}
private void ParseSceneSearchMode( SceneSearchMode sceneSearchMode )
{
searchInOpenScenes = ( sceneSearchMode & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes;
searchInScenesInBuild = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll || ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly;
searchInScenesInBuildTickedOnly = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) != SceneSearchMode.ScenesInBuildSettingsAll;
searchInAllScenes = ( sceneSearchMode & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes;
}
private void Update()
{
if( shouldRepositionSelf )
{
shouldRepositionSelf = false;
position = windowTargetPosition;
}
}
private void OnGUI()
{
// Make the window scrollable
scrollPosition = EditorGUILayout.BeginScrollView( scrollPosition, Utilities.GL_EXPAND_WIDTH, Utilities.GL_EXPAND_HEIGHT );
GUILayout.BeginVertical();
if( currentPhase == Phase.Processing )
{
// If we are stuck at this phase, then we have encountered an exception
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase();
}
else if( currentPhase == Phase.Setup )
{
DrawObjectsToSearchSection();
GUILayout.Space( 10f );
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCH IN</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
if( searchInAssetsFolder )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
excludedAssetsDrawer.Draw( excludedAssets );
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
GUILayout.Space( 5f );
dontSearchInSourceAssets = WordWrappingToggleLeft( "Don't search \"SEARCHED OBJECTS\" themselves for references", dontSearchInSourceAssets );
searchUnusedMaterialProperties = WordWrappingToggleLeft( "Search unused material properties (e.g. normal map of a material that no longer uses normal mapping)", searchUnusedMaterialProperties );
Utilities.DrawSeparatorLine();
if( searchInAllScenes && !EditorApplication.isPlaying )
GUI.enabled = false;
searchInOpenScenes = WordWrappingToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes );
if( !EditorApplication.isPlaying )
{
searchInScenesInBuild = WordWrappingToggleLeft( "Scenes in Build Settings", searchInScenesInBuild );
if( searchInScenesInBuild )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
GUILayout.EndHorizontal();
}
GUI.enabled = true;
searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes );
}
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
excludedScenesDrawer.Draw( excludedScenes );
GUILayout.EndVertical();
GUILayout.EndHorizontal();
Utilities.DrawSeparatorLine();
searchInProjectSettings = WordWrappingToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );
GUILayout.Space( 10f );
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
#if UNITY_2018_3_OR_NEWER
hideReduntantPrefabVariantLinks = WordWrappingToggleLeft( "Hide redundant prefab variant links (when the same value is assigned to the same Component of a prefab and its variant(s))", hideReduntantPrefabVariantLinks );
#endif
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar );
GUILayout.Space( 10f );
// Don't let the user press the GO button without any valid search location
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings )
GUI.enabled = false;
if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) )
{
InitiateSearch();
GUIUtility.ExitGUI();
}
GUILayout.Space( 5f );
}
else if( currentPhase == Phase.Complete )
{
// Draw the results of the search
GUI.enabled = false;
DrawObjectsToSearchSection();
if( drawObjectsToSearchSection )
GUILayout.Space( 10f );
GUI.enabled = true;
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase();
if( searchResult == null )
{
EditorGUILayout.HelpBox( "ERROR: searchResult is null", MessageType.Error );
return;
}
else if( !searchResult.SearchCompletedSuccessfully )
EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error );
if( searchResult.NumberOfGroups == 0 )
{
GUILayout.Space( 10f );
GUILayout.Box( "No references found...", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
}
else
{
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges );
EditorGUILayout.Space();
scrollPosition.y = searchResult.DrawOnGUI( this, scrollPosition.y, noAssetDatabaseChanges );
}
}
if( Event.current.type == EventType.MouseLeaveWindow )
{
SearchResultTooltip.Hide();
if( searchResult != null )
searchResult.CancelDelayedTreeViewTooltip();
}
GUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
private void DrawObjectsToSearchSection()
{
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCHED OBJECTS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect();
searchedObjectsHeaderRect.x += 5f;
searchedObjectsHeaderRect.yMin += ( searchedObjectsHeaderRect.height - EditorGUIUtility.singleLineHeight ) * 0.5f;
searchedObjectsHeaderRect.height = EditorGUIUtility.singleLineHeight;
drawObjectsToSearchSection = EditorGUI.Foldout( searchedObjectsHeaderRect, drawObjectsToSearchSection, GUIContent.none, true );
if( drawObjectsToSearchSection )
objectsToSearchDrawer.Draw( objectsToSearch );
}
private bool WordWrappingToggleLeft( string label, bool value )
{
GUILayout.BeginHorizontal();
bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 );
if( GUILayout.Button( label, EditorStyles.wordWrappedLabel ) )
{
GUI.FocusControl( null );
result = !value;
}
GUILayout.EndHorizontal();
return result;
}
private void InitiateSearch()
{
currentPhase = Phase.Processing;
SavePrefs();
#if UNITY_2018_3_OR_NEWER
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
#endif
// Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
searchInScenes = GetSceneSearchMode( true ),
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
searchInProjectSettings = searchInProjectSettings,
//fieldModifiers = fieldModifiers,
//propertyModifiers = propertyModifiers,
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
lazySceneSearch = lazySceneSearch,
calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows,
hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks,
noAssetDatabaseChanges = noAssetDatabaseChanges,
showDetailedProgressBar = showDetailedProgressBar
} );
currentPhase = Phase.Complete;
// We really don't want SearchRefactoring to affect next searches unless the search is initiated via ShowAndSearch again
searchRefactoring = null;
if( AssetUsageDetectorSettings.ShowCustomTooltip )
wantsMouseMove = wantsMouseEnterLeaveWindow = true;
}
#if UNITY_2018_3_OR_NEWER
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
{
if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
return;
#if UNITY_2020_1_OR_NEWER
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
#else
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
#endif
if( prefabAsset == null || prefabAsset.Equals( null ) )
return;
for( int i = 0; i < objectsToSearch.Count; i++ )
{
Object obj = objectsToSearch[i].obj;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
if( prefabStageObjectSource != null )
objectsToSearch[i].obj = prefabStageObjectSource;
List<ObjectToSearch.SubAsset> subAssets = objectsToSearch[i].subAssets;
for( int j = 0; j < subAssets.Count; j++ )
{
obj = subAssets[j].subAsset;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
if( prefabStageObjectSource != null )
subAssets[j].subAsset = prefabStageObjectSource;
}
}
}
}
}
#endif
private bool ReturnToSetupPhase()
{
if( searchResult != null && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
return false;
searchResult = null;
currentPhase = Phase.Setup;
wantsMouseMove = wantsMouseEnterLeaveWindow = false;
SearchResultTooltip.Hide();
return true;
}
internal void OnSettingsChanged( bool highlightedSearchTextColorChanged = false, bool tooltipDescriptionsColorChanged = false )
{
if( searchResult == null )
return;
wantsMouseMove = wantsMouseEnterLeaveWindow = AssetUsageDetectorSettings.ShowCustomTooltip;
for( int i = searchResult.NumberOfGroups - 1; i >= 0; i-- )
{
if( searchResult[i].treeView != null )
{
searchResult[i].treeView.rowHeight = EditorGUIUtility.singleLineHeight + AssetUsageDetectorSettings.ExtraRowHeight;
searchResult[i].treeView.OnSettingsChanged( highlightedSearchTextColorChanged, tooltipDescriptionsColorChanged );
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests
{
public class OrderByTests : EnumerableTests
{
private class BadComparer1 : IComparer<int>
{
public int Compare(int x, int y)
{
return 1;
}
}
private class BadComparer2 : IComparer<int>
{
public int Compare(int x, int y)
{
return -1;
}
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x1 in new int[] { 1, 6, 0, -1, 3 }
from x2 in new int[] { 55, 49, 9, -100, 24, 25 }
select new { a1 = x1, a2 = x2 };
Assert.Equal(q.OrderBy(e => e.a1).ThenBy(f => f.a2), q.OrderBy(e => e.a1).ThenBy(f => f.a2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 }
from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x2)
select new { a1 = x1, a2 = x2 };
Assert.Equal(q.OrderBy(e => e.a1), q.OrderBy(e => e.a1));
}
[Fact]
public void SourceEmpty()
{
int[] source = { };
Assert.Empty(source.OrderBy(e => e));
}
[Fact]
public void OrderedCount()
{
var source = Enumerable.Range(0, 20).Shuffle();
Assert.Equal(20, source.OrderBy(i => i).Count());
}
//FIXME: This will hang with a larger source. Do we want to deal with that case?
[Fact]
public void SurviveBadComparerAlwaysReturnsNegative()
{
int[] source = { 1 };
int[] expected = { 1 };
Assert.Equal(expected, source.OrderBy(e => e, new BadComparer2()));
}
[Fact]
public void KeySelectorReturnsNull()
{
int?[] source = { null, null, null };
int?[] expected = { null, null, null };
Assert.Equal(expected, source.OrderBy(e => e));
}
[Fact]
public void ElementsAllSameKey()
{
int?[] source = { 9, 9, 9, 9, 9, 9 };
int?[] expected = { 9, 9, 9, 9, 9, 9 };
Assert.Equal(expected, source.OrderBy(e => e));
}
[Fact]
public void KeySelectorCalled()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 45 },
new { Name = "Prakash", Score = 99 }
};
var expected = new[]
{
new { Name = "Prakash", Score = 99 },
new { Name = "Robert", Score = 45 },
new { Name = "Tim", Score = 90 }
};
Assert.Equal(expected, source.OrderBy(e => e.Name, null));
}
[Fact]
public void FirstAndLastAreDuplicatesCustomComparer()
{
string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" };
string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" };
Assert.Equal(expected, source.OrderBy(e => e, StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void FirstAndLastAreDuplicatesNullPassedAsComparer()
{
int[] source = { 5, 1, 3, 2, 5 };
int[] expected = { 1, 2, 3, 5, 5 };
Assert.Equal(expected, source.OrderBy(e => e, null));
}
[Fact]
public void SourceReverseOfResultNullPassedAsComparer()
{
int?[] source = { 100, 30, 9, 5, 0, -50, -75, null };
int?[] expected = { null, -75, -50, 0, 5, 9, 30, 100 };
Assert.Equal(expected, source.OrderBy(e => e, null));
}
[Fact]
public void SameKeysVerifySortStable()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score));
}
[Fact]
public void OrderedToArray()
{
var source = new []
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new []
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score).ToArray());
}
[Fact]
public void EmptyOrderedToArray()
{
Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToArray());
}
[Fact]
public void OrderedToList()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score).ToList());
}
[Fact]
public void EmptyOrderedToList()
{
Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToList());
}
//FIXME: This will hang with a larger source. Do we want to deal with that case?
[Fact]
public void SurviveBadComparerAlwaysReturnsPositive()
{
int[] source = { 1 };
int[] expected = { 1 };
Assert.Equal(expected, source.OrderBy(e => e, new BadComparer1()));
}
private class ExtremeComparer : IComparer<int>
{
public int Compare(int x, int y)
{
if (x == y)
return 0;
if (x < y)
return int.MinValue;
return int.MaxValue;
}
}
[Fact]
public void OrderByExtremeComparer()
{
var outOfOrder = new[] { 7, 1, 0, 9, 3, 5, 4, 2, 8, 6 };
Assert.Equal(Enumerable.Range(0, 10), outOfOrder.OrderBy(i => i, new ExtremeComparer()));
}
[Fact]
public void NullSource()
{
IEnumerable<int> source = null;
Assert.Throws<ArgumentNullException>("source", () => source.OrderBy(i => i));
}
[Fact]
public void NullKeySelector()
{
Func<DateTime, int> keySelector = null;
Assert.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(keySelector));
}
[Fact]
public void FirstOnOrdered()
{
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).First());
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).First());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).First());
}
[Fact]
public void FirstOnEmptyOrderedThrows()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First());
}
[Fact]
public void FirstOrDefaultOnOrdered()
{
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).FirstOrDefault());
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).FirstOrDefault());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).FirstOrDefault());
Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault());
}
[Fact]
public void LastOnOrdered()
{
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).Last());
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).Last());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).Last());
}
[Fact]
public void LastOnEmptyOrderedThrows()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last());
}
[Fact]
public void LastOrDefaultOnOrdered()
{
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).LastOrDefault());
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).LastOrDefault());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).LastOrDefault());
Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault());
}
[Fact]
public void EnumeratorDoesntContinue()
{
var enumerator = NumberRangeGuaranteedNotCollectionType(0, 3).Shuffle().OrderBy(i => i).GetEnumerator();
while (enumerator.MoveNext()) { }
Assert.False(enumerator.MoveNext());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using static System.Runtime.Intrinsics.X86.Sse;
using static System.Runtime.Intrinsics.X86.Sse2;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSingle32()
{
var test = new InsertVector128Test__InsertSingle32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertVector128Test__InsertSingle32
{
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(InsertVector128Test__InsertSingle32 testClass)
{
var result = Sse41.Insert(_fld1, _fld2, 32);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static InsertVector128Test__InsertSingle32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public InsertVector128Test__InsertSingle32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Insert(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Insert(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar1,
_clsVar2,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.Insert(left, right, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertVector128Test__InsertSingle32();
var result = Sse41.Insert(test._fld1, test._fld2, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld1, _fld2, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld1, test._fld2, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(left[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (i == 2 ? BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(right[0]) : BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.32): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="NavigatorInput.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Xsl.XsltOld {
using Res = System.Xml.Utils.Res;
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using Keywords = System.Xml.Xsl.Xslt.KeywordsTable;
internal class NavigatorInput {
private XPathNavigator _Navigator;
private PositionInfo _PositionInfo;
private InputScopeManager _Manager;
private NavigatorInput _Next;
private string _Href;
private Keywords _Atoms;
internal NavigatorInput Next {
get {
return _Next;
}
set {
_Next = value;
}
}
internal string Href {
get {
return _Href;
}
}
internal Keywords Atoms {
get {
return _Atoms;
}
}
internal XPathNavigator Navigator {
get {
AssertInput();
return _Navigator;
}
}
internal InputScopeManager InputScopeManager {
get {
AssertInput();
return _Manager;
}
}
internal bool Advance() {
AssertInput();
return _Navigator.MoveToNext();
}
internal bool Recurse() {
AssertInput();
return _Navigator.MoveToFirstChild();
}
internal bool ToParent() {
AssertInput();
return _Navigator.MoveToParent();
}
internal void Close() {
_Navigator = null;
_PositionInfo = null;
}
//
// Input document properties
//
//
// XPathNavigator does not support line and position numbers
//
internal int LineNumber {
get { return _PositionInfo.LineNumber; }
}
internal int LinePosition {
get { return _PositionInfo.LinePosition; }
}
internal XPathNodeType NodeType {
get {
AssertInput();
return _Navigator.NodeType;
}
}
internal string Name {
get {
AssertInput();
return _Navigator.Name;
}
}
internal string LocalName {
get {
AssertInput();
return _Navigator.LocalName;
}
}
internal string NamespaceURI {
get {
AssertInput();
return _Navigator.NamespaceURI;
}
}
internal string Prefix {
get {
AssertInput();
return _Navigator.Prefix;
}
}
internal string Value {
get {
AssertInput();
return _Navigator.Value;
}
}
internal bool IsEmptyTag {
get {
AssertInput();
return _Navigator.IsEmptyElement;
}
}
internal string BaseURI {
get {
return _Navigator.BaseURI;
}
}
internal bool MoveToFirstAttribute() {
AssertInput();
return _Navigator.MoveToFirstAttribute();
}
internal bool MoveToNextAttribute() {
AssertInput();
return _Navigator.MoveToNextAttribute();
}
internal bool MoveToFirstNamespace() {
AssertInput();
return _Navigator.MoveToFirstNamespace(XPathNamespaceScope.ExcludeXml);
}
internal bool MoveToNextNamespace() {
AssertInput();
return _Navigator.MoveToNextNamespace(XPathNamespaceScope.ExcludeXml);
}
//
// Constructor
//
internal NavigatorInput(XPathNavigator navigator, string baseUri, InputScope rootScope) {
if (navigator == null) {
throw new ArgumentNullException("navigator");
}
if (baseUri == null) {
throw new ArgumentNullException("baseUri");
}
Debug.Assert(navigator.NameTable != null);
_Next = null;
_Href = baseUri;
_Atoms = new Keywords(navigator.NameTable);
_Navigator = navigator;
_Manager = new InputScopeManager(_Navigator, rootScope);
_PositionInfo = PositionInfo.GetPositionInfo(_Navigator);
/*BeginReading:*/
AssertInput();
if (NodeType == XPathNodeType.Root) {
_Navigator.MoveToFirstChild();
}
}
internal NavigatorInput(XPathNavigator navigator): this(navigator, navigator.BaseURI, null) {}
//
// Debugging support
//
[System.Diagnostics.Conditional("DEBUG")]
internal void AssertInput() {
Debug.Assert(_Navigator != null);
}
}
}
| |
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET 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 SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Text;
namespace SnmpSharpNet
{
/// <summary>
/// SNMP version 2 packet class.
/// </summary>
///
/// <remarks>
/// Available packet classes are:
/// <ul>
/// <li><see cref="SnmpV1Packet"/></li>
/// <li><see cref="SnmpV1TrapPacket"/></li>
/// <li><see cref="SnmpV2Packet"/></li>
/// <li><see cref="SnmpV3Packet"/></li>
/// </ul>
///
/// This class is provided to simplify encoding and decoding of packets and to provide consistent interface
/// for users who wish to handle transport part of protocol on their own without using the <see cref="UdpTarget"/>
/// class.
///
/// <see cref="SnmpPacket"/> and derived classes have been developed to implement SNMP version 1, 2 and 3 packet
/// support.
///
/// For SNMP version 1 and 2 packet, <see cref="SnmpV1Packet"/> and <see cref="SnmpV2Packet"/> classes
/// provides sufficient support for encoding and decoding data to/from BER buffers to satisfy requirements
/// of most applications.
///
/// SNMP version 3 on the other hand requires a lot more information to be passed to the encoder method and
/// returned by the decode method. While using SnmpV3Packet class for full packet handling is possible, transport
/// specific class <see cref="UdpTarget"/> uses <see cref="SecureAgentParameters"/> class to store protocol
/// version 3 specific information that carries over from request to request when used on the same SNMP agent
/// and therefore simplifies both initial definition of agents configuration (mostly security) as well as
/// removes the need for repeated initialization of the packet class for subsequent requests.
///
/// If you decide not to use transport helper class(es) like <see cref="UdpTarget"/>, BER encoding and
/// decoding and packets is easily done with SnmpPacket derived classes.
///
/// Example, SNMP version 2 packet encoding:
/// <code>
/// SnmpV2Packet packetv2 = new SnmpV2Packet();
/// packetv2.Community.Set("public");
/// packetv2.Pdu.Set(mypdu);
/// byte[] berpacket = packetv2.encode();
/// </code>
///
/// Example, SNMP version 2 packet decoding:
/// <code>
/// SnmpV2Packet packetv2 = new SnmpV2Packet();
/// packetv2.decode(inbuffer,inlen);
/// </code>
/// </remarks>
public class SnmpV2Packet: SnmpPacket
{
/// <summary>
/// SNMP community name
/// </summary>
protected OctetString _snmpCommunity;
/// <summary>
/// Get SNMP community value used by SNMP version 1 and version 2 protocols.
/// </summary>
public OctetString Community
{
get
{
return _snmpCommunity;
}
}
/// <summary>
/// SNMP Protocol Data Unit
/// </summary>
public Pdu _pdu;
/// <summary>
/// Access to the packet <see cref="Pdu"/>.
/// </summary>
public override SnmpSharpNet.Pdu Pdu
{
get { return _pdu; }
}
/// <summary>
/// Standard constructor.
/// </summary>
public SnmpV2Packet()
: base(SnmpVersion.Ver2)
{
_protocolVersion.Value = (int)SnmpVersion.Ver2;
_pdu = new Pdu();
_snmpCommunity = new OctetString();
}
/// <summary>
/// Standard constructor.
/// </summary>
/// <param name="snmpCommunity">SNMP community name for the packet</param>
public SnmpV2Packet(string snmpCommunity)
: this()
{
_snmpCommunity.Set(snmpCommunity);
}
#region Encode & Decode methods
/// <summary>
/// Decode received SNMP packet.
/// </summary>
/// <param name="buffer">BER encoded packet buffer</param>
/// <param name="length">BER encoded packet buffer length</param>
/// <exception cref="SnmpException">Thrown when invalid encoding has been found in the packet</exception>
/// <exception cref="OverflowException">Thrown when parsed header points to more data then is available in the packet</exception>
/// <exception cref="SnmpInvalidVersionException">Thrown when parsed packet is not SNMP version 1</exception>
/// <exception cref="SnmpInvalidPduTypeException">Thrown when received PDU is of a type not supported by SNMP version 1</exception>
public override int decode(byte[] buffer, int length)
{
MutableByte buf = new MutableByte(buffer, length);
int headerLength;
int offset = 0;
offset = base.decode(buffer, buffer.Length);
if (Version != SnmpVersion.Ver2)
throw new SnmpInvalidVersionException("Invalid protocol version");
offset = _snmpCommunity.decode(buf, offset);
int tmpOffset = offset;
byte asnType = AsnType.ParseHeader(buf, ref tmpOffset, out headerLength);
// Check packet length
if (headerLength + offset > buf.Length)
throw new OverflowException("Insufficient data in packet");
if (asnType != (byte)PduType.Get && asnType != (byte)PduType.GetNext && asnType != (byte)PduType.Set &&
asnType != (byte)PduType.GetBulk && asnType != (byte)PduType.Response && asnType != (byte)PduType.V2Trap &&
asnType != (byte)PduType.Inform)
throw new SnmpInvalidPduTypeException("Invalid SNMP operation received: " + string.Format("0x{0:x2}", asnType));
// Now process the Protocol Data Unit
offset = this.Pdu.decode(buf, offset);
return length;
}
/// <summary>
/// Encode SNMP packet for sending.
/// </summary>
/// <returns>BER encoded SNMP packet.</returns>
public override byte[] encode()
{
MutableByte buf = new MutableByte();
if (this.Pdu.Type != PduType.Get && this.Pdu.Type != PduType.GetNext &&
this.Pdu.Type != PduType.Set && this.Pdu.Type != PduType.V2Trap &&
this.Pdu.Type != PduType.Response && this.Pdu.Type != PduType.GetBulk &&
this.Pdu.Type != PduType.Inform)
throw new SnmpInvalidPduTypeException("Invalid SNMP PDU type while attempting to encode PDU: " + string.Format("0x{0:x2}", this.Pdu.Type));
// snmp version
_protocolVersion.encode(buf);
// community string
_snmpCommunity.encode(buf);
// pdu
_pdu.encode(buf);
// wrap the packet into a sequence
MutableByte tmpBuf = new MutableByte();
AsnType.BuildHeader(tmpBuf, SnmpConstants.SMI_SEQUENCE, buf.Length);
buf.Prepend(tmpBuf);
return buf;
}
#endregion
#region Helper methods
/// <summary>
/// Build SNMP RESPONSE packet for the received INFORM packet.
/// </summary>
/// <returns>SNMP version 2 packet containing RESPONSE to the INFORM packet contained in the class instance.</returns>
public SnmpV2Packet BuildInformResponse()
{
return SnmpV2Packet.BuildInformResponse(this);
}
/// <summary>
/// Build SNMP RESPONSE packet for the INFORM packet class.
/// </summary>
/// <param name="informPacket">SNMP INFORM packet</param>
/// <returns>SNMP version 2 packet containing RESPONSE to the INFORM packet contained in the parameter.</returns>
/// <exception cref="SnmpInvalidPduTypeException">Parameter is not an INFORM SNMP version 2 packet class</exception>
/// <exception cref="SnmpInvalidVersionException">Parameter is not a SNMP version 2 packet</exception>
public static SnmpV2Packet BuildInformResponse(SnmpV2Packet informPacket)
{
if (informPacket.Version != SnmpVersion.Ver2)
throw new SnmpInvalidVersionException("INFORM packet can only be parsed from an SNMP version 2 packet.");
if (informPacket.Pdu.Type != PduType.Inform)
throw new SnmpInvalidPduTypeException("Inform response can only be built for INFORM packets.");
SnmpV2Packet response = new SnmpV2Packet(informPacket.Community.ToString());
response.Pdu.Type = PduType.Response;
response.Pdu.TrapObjectID.Set(informPacket.Pdu.TrapObjectID);
response.Pdu.TrapSysUpTime.Value = informPacket.Pdu.TrapSysUpTime.Value;
foreach (Vb v in informPacket.Pdu.VbList)
{
response.Pdu.VbList.Add(v.Oid, v.Value);
}
response.Pdu.RequestId = informPacket.Pdu.RequestId;
return response;
}
#endregion
/// <summary>
/// String representation of the SNMP v1 Packet contents.
/// </summary>
/// <returns>String representation of the class.</returns>
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.AppendFormat("SnmpV2Packet:\nCommunity: {0}\n{1}\n", Community.ToString(), Pdu.ToString());
return str.ToString();
}
}
}
| |
namespace android.content.pm
{
[global::MonoJavaBridge.JavaClass()]
public partial class ActivityInfo : android.content.pm.ComponentInfo, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ActivityInfo()
{
InitJNI();
}
protected ActivityInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString1836;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.ActivityInfo._toString1836)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._toString1836)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _dump1837;
public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ActivityInfo._dump1837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._dump1837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _writeToParcel1838;
public override void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ActivityInfo._writeToParcel1838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._writeToParcel1838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents1839;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ActivityInfo._describeContents1839);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._describeContents1839);
}
internal static global::MonoJavaBridge.MethodId _getThemeResource1840;
public virtual int getThemeResource()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ActivityInfo._getThemeResource1840);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._getThemeResource1840);
}
internal static global::MonoJavaBridge.MethodId _ActivityInfo1841;
public ActivityInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._ActivityInfo1841);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ActivityInfo1842;
public ActivityInfo(android.content.pm.ActivityInfo arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ActivityInfo.staticClass, global::android.content.pm.ActivityInfo._ActivityInfo1842, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _theme1843;
public int theme
{
get
{
return default(int);
}
set
{
}
}
public static int LAUNCH_MULTIPLE
{
get
{
return 0;
}
}
public static int LAUNCH_SINGLE_TOP
{
get
{
return 1;
}
}
public static int LAUNCH_SINGLE_TASK
{
get
{
return 2;
}
}
public static int LAUNCH_SINGLE_INSTANCE
{
get
{
return 3;
}
}
internal static global::MonoJavaBridge.FieldId _launchMode1844;
public int launchMode
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _permission1845;
public global::java.lang.String permission
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _taskAffinity1846;
public global::java.lang.String taskAffinity
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _targetActivity1847;
public global::java.lang.String targetActivity
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
public static int FLAG_MULTIPROCESS
{
get
{
return 1;
}
}
public static int FLAG_FINISH_ON_TASK_LAUNCH
{
get
{
return 2;
}
}
public static int FLAG_CLEAR_TASK_ON_LAUNCH
{
get
{
return 4;
}
}
public static int FLAG_ALWAYS_RETAIN_TASK_STATE
{
get
{
return 8;
}
}
public static int FLAG_STATE_NOT_NEEDED
{
get
{
return 16;
}
}
public static int FLAG_EXCLUDE_FROM_RECENTS
{
get
{
return 32;
}
}
public static int FLAG_ALLOW_TASK_REPARENTING
{
get
{
return 64;
}
}
public static int FLAG_NO_HISTORY
{
get
{
return 128;
}
}
public static int FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS
{
get
{
return 256;
}
}
internal static global::MonoJavaBridge.FieldId _flags1848;
public int flags
{
get
{
return default(int);
}
set
{
}
}
public static int SCREEN_ORIENTATION_UNSPECIFIED
{
get
{
return -1;
}
}
public static int SCREEN_ORIENTATION_LANDSCAPE
{
get
{
return 0;
}
}
public static int SCREEN_ORIENTATION_PORTRAIT
{
get
{
return 1;
}
}
public static int SCREEN_ORIENTATION_USER
{
get
{
return 2;
}
}
public static int SCREEN_ORIENTATION_BEHIND
{
get
{
return 3;
}
}
public static int SCREEN_ORIENTATION_SENSOR
{
get
{
return 4;
}
}
public static int SCREEN_ORIENTATION_NOSENSOR
{
get
{
return 5;
}
}
internal static global::MonoJavaBridge.FieldId _screenOrientation1849;
public int screenOrientation
{
get
{
return default(int);
}
set
{
}
}
public static int CONFIG_MCC
{
get
{
return 1;
}
}
public static int CONFIG_MNC
{
get
{
return 2;
}
}
public static int CONFIG_LOCALE
{
get
{
return 4;
}
}
public static int CONFIG_TOUCHSCREEN
{
get
{
return 8;
}
}
public static int CONFIG_KEYBOARD
{
get
{
return 16;
}
}
public static int CONFIG_KEYBOARD_HIDDEN
{
get
{
return 32;
}
}
public static int CONFIG_NAVIGATION
{
get
{
return 64;
}
}
public static int CONFIG_ORIENTATION
{
get
{
return 128;
}
}
public static int CONFIG_SCREEN_LAYOUT
{
get
{
return 256;
}
}
public static int CONFIG_UI_MODE
{
get
{
return 512;
}
}
public static int CONFIG_FONT_SCALE
{
get
{
return 1073741824;
}
}
internal static global::MonoJavaBridge.FieldId _configChanges1850;
public int configChanges
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _softInputMode1851;
public int softInputMode
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR1852;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.pm.ActivityInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ActivityInfo"));
global::android.content.pm.ActivityInfo._toString1836 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "toString", "()Ljava/lang/String;");
global::android.content.pm.ActivityInfo._dump1837 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V");
global::android.content.pm.ActivityInfo._writeToParcel1838 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.content.pm.ActivityInfo._describeContents1839 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "describeContents", "()I");
global::android.content.pm.ActivityInfo._getThemeResource1840 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "getThemeResource", "()I");
global::android.content.pm.ActivityInfo._ActivityInfo1841 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "<init>", "()V");
global::android.content.pm.ActivityInfo._ActivityInfo1842 = @__env.GetMethodIDNoThrow(global::android.content.pm.ActivityInfo.staticClass, "<init>", "(Landroid/content/pm/ActivityInfo;)V");
}
}
}
| |
// 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.DataLake.Analytics
{
using Azure;
using DataLake;
using Management;
using Azure;
using Management;
using DataLake;
using Models;
using Rest;
using Rest.Azure;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for FirewallRulesOperations.
/// </summary>
public static partial class FirewallRulesOperationsExtensions
{
/// <summary>
/// Creates or updates the specified firewall rule. During update, the firewall
/// rule with the specified name will be replaced with this new firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to add or replace the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to create or update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update the firewall rule.
/// </param>
public static FirewallRule CreateOrUpdate(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the specified firewall rule. During update, the firewall
/// rule with the specified name will be replaced with this new firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to add or replace the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to create or update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update the firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FirewallRule> CreateOrUpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to which to update the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the firewall rule.
/// </param>
public static FirewallRule Update(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters))
{
return operations.UpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to which to update the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FirewallRule> UpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified firewall rule from the specified Data Lake Analytics
/// account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to delete the
/// firewall rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to delete.
/// </param>
public static void Delete(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName)
{
operations.DeleteAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified firewall rule from the specified Data Lake Analytics
/// account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to delete the
/// firewall rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Data Lake Analytics firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to get the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to retrieve.
/// </param>
public static FirewallRule Get(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName)
{
return operations.GetAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Data Lake Analytics firewall rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to get the firewall
/// rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FirewallRule> GetAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Analytics firewall rules within the specified Data Lake
/// Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to get the firewall
/// rules.
/// </param>
public static IPage<FirewallRule> ListByAccount(this IFirewallRulesOperations operations, string resourceGroupName, string accountName)
{
return operations.ListByAccountAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Analytics firewall rules within the specified Data Lake
/// Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to get the firewall
/// rules.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<FirewallRule>> ListByAccountAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Analytics firewall rules within the specified Data Lake
/// Analytics account.
/// </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<FirewallRule> ListByAccountNext(this IFirewallRulesOperations operations, string nextPageLink)
{
return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Analytics firewall rules within the specified Data Lake
/// Analytics account.
/// </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<FirewallRule>> ListByAccountNextAsync(this IFirewallRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Extensions;
using CppSharp.Generators.C;
using CppSharp.Generators.NAPI;
using CppSharp.Passes;
using CppSharp.Utils.FSM;
using static CppSharp.Generators.Cpp.NAPISources;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.Cpp
{
public class NAPISources : NAPICodeGenerator
{
public override string FileExtension => "cpp";
public NAPISources(BindingContext context, IEnumerable<TranslationUnit> units)
: base(context, units)
{
}
public static string GetTranslationUnitName(TranslationUnit unit)
{
var paths = unit.FileRelativePath.Split('/').ToList();
paths = paths.Select(p => Path.GetFileNameWithoutExtension(p.ToLowerInvariant())).ToList();
var name = string.Join('_', paths);
return name;
}
public override void Process()
{
GenerateFilePreamble(CommentKind.BCPL);
PushBlock(BlockKind.Includes);
WriteInclude(TranslationUnit.IncludePath, CInclude.IncludeKind.Angled);
WriteInclude("node/node_api.h", CInclude.IncludeKind.Angled);
WriteInclude("assert.h", CInclude.IncludeKind.Angled);
WriteInclude("stdio.h", CInclude.IncludeKind.Angled);
WriteInclude("NAPIHelpers.h", CInclude.IncludeKind.Quoted);
PopBlock(NewLineKind.BeforeNextBlock);
var collector = new NAPIClassReturnCollector();
TranslationUnit.Visit(collector);
PushBlock();
foreach (var @class in collector.Classes)
{
var ctor = @class.Methods.First(m => m.IsConstructor);
WriteLine($"extern napi_ref ctor_{GetCIdentifier(Context, @ctor)};");
}
PopBlock(NewLineKind.BeforeNextBlock);
var registerGen = new NAPIRegister(Context, TranslationUnits);
registerGen.Process();
WriteLine(registerGen.Generate());
var name = GetTranslationUnitName(TranslationUnit);
WriteLine($"void register_{name}(napi_env env, napi_value exports)");
WriteOpenBraceAndIndent();
WriteLine("napi_value value;");
NewLine();
TranslationUnit.Visit(this);
UnindentAndWriteCloseBrace();
}
public override bool VisitClassDecl(Class @class)
{
if (@class.IsIncomplete)
return true;
PushBlock();
WriteLine($"value = register_class_{GetCIdentifier(Context, @class)}(env);");
WriteLine($"NAPI_CALL_NORET(env, napi_set_named_property(env, exports, \"{@class.Name}\", value));");
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
public override bool VisitFunctionDecl(Function function)
{
if (function.IsOperator)
return true;
PushBlock();
WriteLine($"value = register_function_{GetCIdentifier(Context, function)}(env);");
WriteLine($"NAPI_CALL_NORET(env, napi_set_named_property(env, exports, \"{@function.Name}\", value));");
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
if (@enum.IsIncomplete)
return false;
PushBlock();
WriteLine($"value = register_enum_{GetCIdentifier(Context, @enum)}(env, exports);");
WriteLine($"NAPI_CALL_NORET(env, napi_set_named_property(env, exports, \"{@enum.Name}\", value));");
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
public static string GetCIdentifier(BindingContext context, Declaration decl,
TypePrintScopeKind scope = TypePrintScopeKind.Qualified)
{
var cTypePrinter = new CppTypePrinter(context)
{
PrintFlavorKind = CppTypePrintFlavorKind.C,
};
cTypePrinter.PushScope(TypePrintScopeKind.Local);
var functionName = cTypePrinter.VisitDeclaration(decl).ToString();
if (scope == TypePrintScopeKind.Local)
return functionName;
cTypePrinter.PushScope(scope);
var qualifiedParentName = cTypePrinter.VisitDeclaration(decl.Namespace).ToString();
// HACK: CppTypePrinter code calls into decl.QualifiedName, which does not take into
// account language flavor, that code needs to be reworked. For now, hack around it.
qualifiedParentName = qualifiedParentName.Replace("::", "_");
return $"{qualifiedParentName}_{functionName}";
}
}
public class NAPIClassReturnCollector : TranslationUnitPass
{
public readonly HashSet<Class> Classes = new HashSet<Class>();
private TranslationUnit translationUnit;
public override bool VisitFunctionDecl(Function function)
{
if (!NAPICodeGenerator.ShouldGenerate(function))
return false;
var retType = function.ReturnType.Type.Desugar();
if (retType.IsPointer())
retType = retType.GetFinalPointee().Desugar();
if (!(retType is TagType tagType))
return base.VisitFunctionDecl(function);
if (!(tagType.Declaration is Class @class))
return base.VisitFunctionDecl(function);
if (@class.TranslationUnit == translationUnit)
return base.VisitFunctionDecl(function);
Classes.Add(@class);
return true;
}
public override bool VisitTranslationUnit(TranslationUnit unit)
{
translationUnit = unit;
return base.VisitTranslationUnit(unit);
}
}
public class NAPIRegister : NAPICodeGenerator
{
public NAPIRegister(BindingContext context, IEnumerable<TranslationUnit> units)
: base(context, units)
{
}
public override void Process()
{
TranslationUnit.Visit(this);
}
public override bool VisitClassDecl(Class @class)
{
if (@class.IsIncomplete)
return true;
PushBlock(BlockKind.InternalsClass, @class);
var callbacks = new NAPIInvokes(Context);
@class.Visit(callbacks);
Write(callbacks.Generate());
PopBlock(NewLineKind.BeforeNextBlock);
PushBlock(BlockKind.Class, @class);
Write($"static napi_value register_class_{GetCIdentifier(Context, @class)}");
WriteLine("(napi_env env)");
WriteOpenBraceAndIndent();
var sources = new NAPIRegisterImpl(Context);
sources.Indent(CurrentIndentation);
@class.Visit(sources);
Write(sources.Generate());
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
return false;
}
public override void GenerateFunctionGroup(List<Function> group)
{
var function = group.First();
if (function.IsOperator)
return;
PushBlock(BlockKind.Function);
var callbacks = new NAPIInvokes(Context);
callbacks.GenerateFunctionGroup(group);
Write(callbacks.Generate());
PopBlock(NewLineKind.BeforeNextBlock);
PushBlock(BlockKind.Function);
Write($"static napi_value register_function_{GetCIdentifier(Context, function)}");
WriteLine("(napi_env env)");
WriteOpenBraceAndIndent();
WriteLine("napi_status status;");
var qualifiedMethodId = GetCIdentifier(Context, function);
var valueId = $"_{qualifiedMethodId}";
WriteLine($"napi_value {valueId};");
var callbackId = $"callback_function_{qualifiedMethodId}";
WriteLine($"status = napi_create_function(env, \"{function.Name}\", NAPI_AUTO_LENGTH, " +
$"{callbackId}, 0, &{valueId});");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine($"return {valueId};");
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
public override bool VisitEnumDecl(Enumeration @enum)
{
if (@enum.IsIncomplete)
return false;
PushBlock(BlockKind.Enum);
Write($"static napi_value register_enum_{GetCIdentifier(Context, @enum)}");
WriteLine("(napi_env env, napi_value exports)");
WriteOpenBraceAndIndent();
var sources = new NAPIRegisterImpl(Context);
sources.Indent(CurrentIndentation);
@enum.Visit(sources);
Write(sources.Generate());
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
}
public class NAPIRegisterImpl : NAPICodeGenerator
{
public NAPIRegisterImpl(BindingContext context)
: base(context, null)
{
}
public override bool VisitClassDecl(Class @class)
{
WriteLine("napi_status status;");
WriteLine("napi_property_attributes attributes = (napi_property_attributes) (napi_default | napi_enumerable);");
WriteLine("napi_property_descriptor props[] =");
WriteOpenBraceAndIndent();
WriteLine("// { utf8name, name, method, getter, setter, value, attributes, data }");
VisitClassDeclContext(@class);
@class.FindHierarchy(c =>
{
WriteLine($"// {@class.QualifiedOriginalName}");
return VisitClassDeclContext(c);
});
NewLine();
Unindent();
WriteLine("};");
NewLine();
string ctorCallbackId = "nullptr";
var ctor = @class.Constructors.FirstOrDefault();
if (ctor != null)
{
var ctorQualifiedId = GetCIdentifier(Context, ctor);
ctorCallbackId = $"callback_method_{ctorQualifiedId}";
}
WriteLine("napi_value constructor;");
WriteLine($"status = napi_define_class(env, \"{@class.Name}\", NAPI_AUTO_LENGTH, " +
$"{ctorCallbackId}, nullptr, sizeof(props) / sizeof(props[0]), props, &constructor);");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine($"status = napi_create_reference(env, constructor, 1, &ctor_{GetCIdentifier(Context, ctor)});");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine("return constructor;");
return true;
}
public override bool VisitMethodDecl(Method method)
{
if (method.IsConstructor)
return true;
PushBlock(BlockKind.Method);
var attributes = "attributes";
if (method.IsStatic)
attributes += " | napi_static";
var qualifiedId = GetCIdentifier(Context, method);
var callbackId = $"callback_method_{qualifiedId}";
Write($"{{ \"{method.Name}\", nullptr, {callbackId}, nullptr, nullptr, nullptr, (napi_property_attributes)({attributes}), nullptr }},");
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
enumItemIndex = 0;
WriteLine("napi_status status;");
WriteLine("napi_value result;");
WriteLine("NAPI_CALL(env, napi_create_object(env, &result));");
NewLine();
PushBlock();
foreach (var item in @enum.Items)
item.Visit(this);
PopBlock(NewLineKind.Always);
WriteLine("napi_property_attributes attributes = (napi_property_attributes) (napi_default | napi_enumerable);");
WriteLine("napi_property_descriptor props[] =");
WriteOpenBraceAndIndent();
WriteLine("// { utf8name, name, method, getter, setter, value, attributes, data }");
var items = @enum.Items.Where(item => item.IsGenerated).ToList();
for (int i = 0; i < items.Count; i++)
{
var item = items[i];
var isLast = i == items.Count - 1;
Write($"{{ \"{item.Name}\", nullptr, nullptr, nullptr, nullptr, i_{i}, attributes, nullptr }}");
WriteLine(isLast ? string.Empty : ",");
}
Unindent();
WriteLine("};");
NewLine();
var @sizeof = $"sizeof(props) / sizeof(props[0])";
WriteLine($"NAPI_CALL(env, napi_define_properties(env, result, {@sizeof}, props));");
NewLine();
WriteLine("return result;");
return true;
}
static int enumItemIndex = 0;
public override bool VisitEnumItemDecl(Enumeration.Item item)
{
PushBlock(BlockKind.EnumItem);
WriteLine("// " + item.Name);
WriteLine($"napi_value i_{enumItemIndex};");
var @enum = item.Namespace as Enumeration;
var (_, function) = NAPIMarshalNativeToManagedPrinter.GetNAPIPrimitiveType(@enum.BuiltinType.Type);
WriteLine($"status = {function}(env, {@enum.GetItemValueAsString(item)}, &i_{enumItemIndex++});");
WriteLine("assert(status == napi_ok);");
PopBlock(NewLineKind.BeforeNextBlock);
return true;
}
public override bool VisitProperty(Property property)
{
return true;
}
}
public class NAPIInvokes : NAPICodeGenerator
{
public NAPIInvokes(BindingContext context)
: base(context, null)
{
}
public NAPIInvokes(BindingContext context, IEnumerable<TranslationUnit> units)
: base(context, units)
{
}
public override void GenerateFunctionGroup(List<Function> @group)
{
var function = @group.First();
PushBlock(BlockKind.Function, function);
GenerateFunctionCallback(@group);
NewLine();
// TODO:
WriteLine("return nullptr;");
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
public override void GenerateMethodGroup(List<Method> @group)
{
var method = @group.First();
if (method.IsConstructor)
{
GenerateMethodDestructor(method);
WriteLine($"static napi_ref ctor_{GetCIdentifier(Context, method)};");
NewLine();
}
PushBlock(BlockKind.Method);
GenerateFunctionCallback(@group.OfType<Function>().ToList());
NewLine();
WriteLine("return _this;");
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
public virtual void GenerateFunctionCallback(List<Function> @group)
{
var function = @group.First();
WriteLine($"// {function.QualifiedName}");
var type = function is Method ? "method" : "function";
var callbackId = $"callback_{type}_{GetCIdentifier(Context, function)}";
Write($"static napi_value {callbackId}");
WriteLine("(napi_env env, napi_callback_info info)");
WriteOpenBraceAndIndent();
WriteLine("napi_status status;");
WriteLine("napi_value _this;");
WriteLine("size_t argc;");
WriteLine("status = napi_get_cb_info(env, info, &argc, nullptr, &_this, nullptr);");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine("napi_value args[argc];");
WriteLine("napi_valuetype types[argc];");
NewLine();
// Handle the zero arguments case right away if one exists.
CheckZeroArguments(@group);
NewLineIfNeeded();
// Check if the arguments are in the expected range.
CheckArgumentsRange(@group);
NewLine();
var needsArguments = @group.Any(f => f.Parameters.Any(p => p.IsGenerated));
if (needsArguments)
{
WriteLine("status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine("for (size_t i = 0; i < argc; i++)");
WriteOpenBraceAndIndent();
{
WriteLine("status = napi_typeof(env, args[i], &types[i]);");
WriteLine("assert(status == napi_ok);");
}
UnindentAndWriteCloseBrace();
NewLine();
}
var method = function as Method;
if (method != null)
{
var @class = method.Namespace as Class;
if (method.IsConstructor)
{
WriteLine($"{@class.QualifiedOriginalName}* instance = nullptr;");
}
else
{
WriteLine($"{@class.QualifiedOriginalName}* instance;");
WriteLine("status = napi_unwrap(env, _this, (void**) &instance);");
}
NewLine();
}
if (needsArguments)
{
var stateMachine = CalculateOverloadStates(@group);
CheckArgumentsOverload(@group, stateMachine);
// Error state.
Unindent();
WriteLine($"error:");
Indent();
WriteLine("status = napi_throw_type_error(env, nullptr, \"Unsupported argument type\");");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine("return nullptr;");
NewLine();
GenerateOverloadCalls(@group, stateMachine);
}
else
{
GenerateFunctionCall(function);
}
if (method != null && method.IsConstructor)
{
WriteLine("napi_ref result;");
WriteLine($"status = napi_wrap(env, _this, instance, dtor_{GetCIdentifier(Context, method)}" +
$", nullptr, &result);");
WriteLine("assert(status == napi_ok);");
NewLine();
}
}
public virtual void CheckZeroArguments(List<Function> @group)
{
var zeroParamsOverload = @group.Where(f => f.Parameters.Count == 0 ||
(f.Parameters.Count >= 1 && f.Parameters.First().HasDefaultValue)).ToArray();
if (zeroParamsOverload.Length == 0 || @group.Count <= 1)
return;
if (zeroParamsOverload.Length > 1)
throw new Exception($"Found ambiguity between default parameter overloads for: " +
$"{@group.First().QualifiedOriginalName}");
var index = @group.FindIndex(f => f == zeroParamsOverload.First());
WriteLine($"if (argc == 0)");
WriteLineIndent($"goto overload{index};");
NeedNewLine();
}
public virtual void CheckArgumentsRange(IEnumerable<Function> @group)
{
var enumerable = @group as List<Function> ?? @group.ToList();
var (minArgs, maxArgs) = (enumerable.Min(m => m.Parameters.Count),
enumerable.Max(m => m.Parameters.Count));
var rangeCheck = minArgs > 0 ? $"argc < {minArgs} || argc > {maxArgs}" : $"argc > {maxArgs}";
WriteLine($"if ({rangeCheck})");
WriteOpenBraceAndIndent();
{
WriteLine("status = napi_throw_type_error(env, nullptr, \"Unsupported number of arguments\");");
WriteLine("assert(status == napi_ok);");
NewLine();
WriteLine("return nullptr;");
}
UnindentAndWriteCloseBrace();
}
public virtual void CheckArgumentsOverload(List<Function> @group, DFSM stateMachine)
{
int GetParamIndex(Transition transition, string state)
{
var isInitialState = stateMachine.Q0.Contains(state);
var paramIndex = isInitialState ? 0 : int.Parse(transition.StartState.Split(' ').Last().Split('_').Last()) + 1;
return paramIndex;
}
var typeCheckStates = stateMachine.Q.Except(stateMachine.F).ToList();
var finalStates = stateMachine.F;
// Create a set of unique parameter types.
var uniqueTypes = @group.SelectMany(method => method.Parameters)
.Select(p => p.Type).Distinct().ToList();
// Type check states.
for (var i = 0; i < typeCheckStates.Count; i++)
{
NewLineIfNeeded();
if (i > 0)
{
Unindent();
WriteLine($"typecheck{i}:");
Indent();
}
var state = typeCheckStates[i];
var transitions = stateMachine.Delta.Where(t => t.StartState == state).ToArray();
// Deal with default parameters.
var currentParamIndex = GetParamIndex(transitions.First(), state);
var defaultParams = @group.Where(f => f.Parameters.Count > currentParamIndex)
.Select(f => f.Parameters[currentParamIndex])
.Where(p => p.HasDefaultValue).ToArray();
// Check for an ambiguous case of overload resolution and throw. This does prevents some technically
// legal overloads from being generated, so in the future this can be updated to just throw
// a runtime error in JS instead, which would allow the ambiguous overloads to be called when
// resolved with all explicit arguments.
if (defaultParams.Length > 1)
throw new Exception($"Found ambiguity between default parameter overloads for: " +
$"{@group.First().QualifiedOriginalName}");
if (defaultParams.Length == 1)
{
WriteLine($"if (argc == {currentParamIndex})");
var overload = defaultParams.First().Namespace as Function;
var index = @group.FindIndex(f => f == overload);
WriteLineIndent($"goto overload{index};");
NewLine();
}
foreach (var transition in transitions)
{
NewLineIfNeeded();
var paramIndex = GetParamIndex(transition, state);
var type = uniqueTypes[transition.Symbol];
var condition = GenerateTypeCheckForParameter(paramIndex, type);
WriteLine($"if ({condition})");
var nextState = typeCheckStates.Contains(transition.EndState)
? $"typecheck{typeCheckStates.FindIndex(s => s == transition.EndState)}"
: $"overload{finalStates.FindIndex(s => s == transition.EndState)}";
WriteLineIndent($"goto {nextState};");
NewLine();
}
WriteLine("goto error;");
NeedNewLine();
NeedNewLine();
}
NewLineIfNeeded();
}
public virtual string GenerateTypeCheckForParameter(int paramIndex, Type type)
{
var typeChecker = new NAPITypeCheckGen(paramIndex);
type.Visit(typeChecker);
var condition = typeChecker.Generate();
if (string.IsNullOrWhiteSpace(condition))
throw new NotSupportedException();
return condition;
}
public virtual void GenerateOverloadCalls(IList<Function> @group, DFSM stateMachine)
{
// Final states.
for (var i = 0; i < stateMachine.F.Count; i++)
{
NewLineIfNeeded();
var function = @group[i];
WriteLine($"// {function.Signature}");
Unindent();
WriteLine($"overload{i}:");
Indent();
WriteOpenBraceAndIndent();
{
GenerateFunctionCall(function);
}
UnindentAndWriteCloseBrace();
NeedNewLine();
}
}
public virtual void GenerateFunctionCall(Function function)
{
var @params = GenerateFunctionParamsMarshal(function.Parameters, function);
var method = function as Method;
var isVoidReturn = function.ReturnType.Type.IsPrimitiveType(PrimitiveType.Void);
PushBlock();
{
if (!isVoidReturn)
{
CTypePrinter.PushContext(TypePrinterContextKind.Native);
var returnType = function.ReturnType.Visit(CTypePrinter);
CTypePrinter.PopContext();
Write($"{returnType} {Helpers.ReturnIdentifier} = ");
}
var @class = function.Namespace as Class;
var property = method?.AssociatedDeclaration as Property;
var field = property?.Field;
if (field != null)
{
Write($"instance->{field.OriginalName}");
var isGetter = property.GetMethod == method;
if (isGetter)
WriteLine(";");
else
WriteLine($" = {@params[0].Name};");
}
else
{
if (method != null && method.IsConstructor)
{
Write($"instance = new {@class.QualifiedOriginalName}(");
}
else if (IsNativeFunctionOrStaticMethod(function))
{
Write($"::{function.QualifiedOriginalName}(");
}
else
{
if (function.IsNativeMethod())
Write($"instance->");
Write($"{base.GetMethodIdentifier(function, TypePrinterContextKind.Native)}(");
}
GenerateFunctionParams(@params);
WriteLine(");");
}
}
PopBlock(NewLineKind.IfNotEmpty);
GenerateFunctionParamsMarshalCleanups(@params);
var isCtor = method != null && method.IsConstructor;
var needsReturn = !isVoidReturn || (this is QuickJSInvokes && !isCtor);
if (needsReturn)
{
NewLine();
GenerateFunctionCallReturnMarshal(function);
}
if (isCtor)
{
WriteLine("goto wrap;");
}
}
public bool IsNativeFunctionOrStaticMethod(Function function)
{
var method = function as Method;
if (method == null)
return true;
if (!IsCLIGenerator && method.IsOperator)
return false;
if (method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind))
return true;
return method.IsStatic || method.Conversion != MethodConversionKind.None;
}
public void GenerateFunctionParams(List<ParamMarshal> @params)
{
var names = @params.Select(param =>
string.IsNullOrWhiteSpace(param.Prefix) ? param.Name : (param.Prefix + param.Name))
.ToList();
Write(string.Join(", ", names));
}
public static DFSM CalculateOverloadStates(IEnumerable<Function> group)
{
var functionGroup = group.ToList();
// Create a set of unique parameter types.
var uniqueTypes = functionGroup.SelectMany(method => method.Parameters)
.Select(p => p.Type).Distinct().ToList();
// Consider the alphabet as sequential ordered numbers, one per type.
var Sigma = Enumerable.Range(0, uniqueTypes.Count).Select(i => (char) i).ToArray();
var Q = new List<string> {"S"};
var overloadStates = Enumerable.Range(0, functionGroup.Count).Select(i => $"F{i}")
.ToArray();
Q.AddRange(overloadStates);
var Delta = new List<Transition>();
// Setup states and transitions.
for (var methodIndex = 0; methodIndex < functionGroup.Count; methodIndex++)
{
var method = functionGroup[methodIndex];
var curState = "S";
for (var paramIndex = 0; paramIndex < method.Parameters.Count; paramIndex++)
{
var param = method.Parameters[paramIndex];
var typeIndex = uniqueTypes.FindIndex(p => p.Equals(param.Type));
var isLastTransition = paramIndex == method.Parameters.Count - 1;
var nextState = isLastTransition ? $"F{methodIndex}" : $"{methodIndex}_{paramIndex}";
if (!isLastTransition)
Q.Add(nextState);
Delta.Add(new Transition(curState, (char) typeIndex, nextState));
curState = nextState;
}
}
var Q0 = new List<string> {"S"};
var F = overloadStates;
var NDFSM = new NDFSM(Q, Sigma, Delta, Q0, F);
var DFSM = Minimize.PowersetConstruction(NDFSM);
// Add the zero-parameters overload manually if one exists since it got optimized out.
var zeroParamsOverload = functionGroup.SingleOrDefault(f => f.Parameters.Count == 0);
if (zeroParamsOverload != null)
{
var index = functionGroup.FindIndex(f => f == zeroParamsOverload);
DFSM.F.Insert(index, $"F{index}");
}
#if OPTIMIZE_STATES
DFSM = Minimize.MinimizeDFSM(DFSM);
#endif
// The construction step above can result in unordered final states, so re-order them to
// make the following code generation steps easier.
DFSM.F = DFSM.F.OrderBy(f => f).ToList();
return DFSM;
}
private void GenerateMethodDestructor(Method method)
{
PushBlock(BlockKind.Destructor);
Write($"static void dtor_{GetCIdentifier(Context, method)}");
WriteLine("(napi_env env, void* finalize_data, void* finalize_hint)");
WriteOpenBraceAndIndent();
UnindentAndWriteCloseBrace();
PopBlock(NewLineKind.BeforeNextBlock);
}
public override bool VisitMethodDecl(Method method)
{
return true;
}
public override bool VisitFunctionDecl(Function function)
{
return true;
}
public override bool VisitFieldDecl(Field field)
{
return true;
}
public override bool VisitProperty(Property property)
{
return true;
}
}
}
| |
using ICSharpCode.TextEditor.Actions;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor.Util;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ICSharpCode.TextEditor
{
public class TextAreaClipboardHandler
{
public delegate bool ClipboardContainsTextDelegate();
private const string LineSelectedType = "MSDEVLineSelect";
private TextArea textArea;
public static TextAreaClipboardHandler.ClipboardContainsTextDelegate GetClipboardContainsText;
[ThreadStatic]
private static int SafeSetClipboardDataVersion;
public event CopyTextEventHandler CopyText;
public bool EnableCut
{
get
{
return this.textArea.EnableCutOrPaste;
}
}
public bool EnableCopy
{
get
{
return true;
}
}
public bool EnablePaste
{
get
{
if (!this.textArea.EnableCutOrPaste)
{
return false;
}
TextAreaClipboardHandler.ClipboardContainsTextDelegate getClipboardContainsText = TextAreaClipboardHandler.GetClipboardContainsText;
if (getClipboardContainsText != null)
{
return getClipboardContainsText();
}
bool result;
try
{
result = Clipboard.ContainsText();
}
catch (ExternalException)
{
result = false;
}
return result;
}
}
public bool EnableDelete
{
get
{
return this.textArea.SelectionManager.HasSomethingSelected && !this.textArea.SelectionManager.SelectionIsReadonly;
}
}
public bool EnableSelectAll
{
get
{
return true;
}
}
public TextAreaClipboardHandler(TextArea textArea)
{
this.textArea = textArea;
textArea.SelectionManager.SelectionChanged += new EventHandler(this.DocumentSelectionChanged);
}
private void DocumentSelectionChanged(object sender, EventArgs e)
{
}
private bool CopyTextToClipboard(string stringToCopy, bool asLine)
{
if (stringToCopy.Length > 0)
{
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormats.UnicodeText, true, stringToCopy);
if (asLine)
{
MemoryStream memoryStream = new MemoryStream(1);
memoryStream.WriteByte(1);
dataObject.SetData("MSDEVLineSelect", false, memoryStream);
}
if (this.textArea.Document.HighlightingStrategy.Name != "Default")
{
dataObject.SetData(DataFormats.Rtf, RtfWriter.GenerateRtf(this.textArea));
}
this.OnCopyText(new CopyTextEventArgs(stringToCopy));
TextAreaClipboardHandler.SafeSetClipboard(dataObject);
return true;
}
return false;
}
private static void SafeSetClipboard(object dataObject)
{
int version = ++TextAreaClipboardHandler.SafeSetClipboardDataVersion;
try
{
Clipboard.SetDataObject(dataObject, true);
}
catch (ExternalException)
{
Timer timer = new Timer();
timer.Interval = 100;
timer.Tick += delegate
{
timer.Stop();
timer.Dispose();
if (TextAreaClipboardHandler.SafeSetClipboardDataVersion == version)
{
try
{
Clipboard.SetDataObject(dataObject, true, 10, 50);
}
catch (ExternalException)
{
}
}
}
;
timer.Start();
}
}
private bool CopyTextToClipboard(string stringToCopy)
{
return this.CopyTextToClipboard(stringToCopy, false);
}
public void Cut(object sender, EventArgs e)
{
if (this.textArea.SelectionManager.HasSomethingSelected)
{
if (this.CopyTextToClipboard(this.textArea.SelectionManager.SelectedText))
{
if (this.textArea.SelectionManager.SelectionIsReadonly)
{
return;
}
this.textArea.BeginUpdate();
this.textArea.Caret.Position = this.textArea.SelectionManager.SelectionCollection[0].StartPosition;
this.textArea.SelectionManager.RemoveSelectedText();
this.textArea.EndUpdate();
return;
}
}
else
{
if (this.textArea.Document.TextEditorProperties.CutCopyWholeLine)
{
int lineNumberForOffset = this.textArea.Document.GetLineNumberForOffset(this.textArea.Caret.Offset);
LineSegment lineSegment = this.textArea.Document.GetLineSegment(lineNumberForOffset);
string text = this.textArea.Document.GetText(lineSegment.Offset, lineSegment.TotalLength);
this.textArea.SelectionManager.SetSelection(this.textArea.Document.OffsetToPosition(lineSegment.Offset), this.textArea.Document.OffsetToPosition(lineSegment.Offset + lineSegment.TotalLength));
if (this.CopyTextToClipboard(text, true))
{
if (this.textArea.SelectionManager.SelectionIsReadonly)
{
return;
}
this.textArea.BeginUpdate();
this.textArea.Caret.Position = this.textArea.Document.OffsetToPosition(lineSegment.Offset);
this.textArea.SelectionManager.RemoveSelectedText();
this.textArea.Document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.PositionToEnd, new TextLocation(0, lineNumberForOffset)));
this.textArea.EndUpdate();
}
}
}
}
public void Copy(object sender, EventArgs e)
{
if (!this.CopyTextToClipboard(this.textArea.SelectionManager.SelectedText) && this.textArea.Document.TextEditorProperties.CutCopyWholeLine)
{
int lineNumberForOffset = this.textArea.Document.GetLineNumberForOffset(this.textArea.Caret.Offset);
LineSegment lineSegment = this.textArea.Document.GetLineSegment(lineNumberForOffset);
string text = this.textArea.Document.GetText(lineSegment.Offset, lineSegment.TotalLength);
this.CopyTextToClipboard(text, true);
}
}
public void Paste(object sender, EventArgs e)
{
if (!this.textArea.EnableCutOrPaste)
{
return;
}
int num = 0;
while (true)
{
try
{
IDataObject dataObject = Clipboard.GetDataObject();
if (dataObject == null)
{
break;
}
bool dataPresent = dataObject.GetDataPresent("MSDEVLineSelect");
if (dataObject.GetDataPresent(DataFormats.UnicodeText))
{
string text = (string)dataObject.GetData(DataFormats.UnicodeText);
if (!string.IsNullOrEmpty(text))
{
this.textArea.Document.UndoStack.StartUndoGroup();
try
{
if (this.textArea.SelectionManager.HasSomethingSelected)
{
this.textArea.Caret.Position = this.textArea.SelectionManager.SelectionCollection[0].StartPosition;
this.textArea.SelectionManager.RemoveSelectedText();
}
if (dataPresent)
{
int column = this.textArea.Caret.Column;
this.textArea.Caret.Column = 0;
if (!this.textArea.IsReadOnly(this.textArea.Caret.Offset))
{
this.textArea.InsertString(text);
}
this.textArea.Caret.Column = column;
}
else
{
this.textArea.InsertString(text);
}
}
finally
{
this.textArea.Document.UndoStack.EndUndoGroup();
}
}
}
break;
}
catch (ExternalException)
{
if (num > 5)
{
throw;
}
}
num++;
}
}
public void Delete(object sender, EventArgs e)
{
new Delete().Execute(this.textArea);
}
public void SelectAll(object sender, EventArgs e)
{
new SelectWholeDocument().Execute(this.textArea);
}
protected virtual void OnCopyText(CopyTextEventArgs e)
{
if (this.CopyText != null)
{
this.CopyText(this, e);
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Voxalia.Shared;
using Voxalia.Shared.Collision;
using Voxalia.Shared.Files;
using Voxalia.ServerGame.WorldSystem;
using Voxalia.ServerGame.JointSystem;
using Voxalia.ServerGame.ItemSystem.CommonItems;
using BEPUphysics.Character;
using BEPUutilities;
using Voxalia.ServerGame.ItemSystem;
using Voxalia.ServerGame.NetworkSystem;
using Voxalia.ServerGame.NetworkSystem.PacketsOut;
using FreneticScript;
namespace Voxalia.ServerGame.EntitySystem
{
public abstract class CharacterEntity: LivingEntity
{
public CharacterEntity(Region tregion, double maxhealth)
: base(tregion, maxhealth)
{
CGroup = CollisionUtil.Character;
}
public override long GetRAMUsage()
{
return base.GetRAMUsage() + 200 + (Path == null ? 0 : Path.Length * 30);
}
public string model = "cube";
public double mod_xrot = 0;
public double mod_yrot = 0;
public double mod_zrot = 0;
public double mod_scale = 1;
public System.Drawing.Color mod_color = System.Drawing.Color.White;
public bool Upward = false;
public double XMove;
public double YMove;
public bool Downward = false;
public bool Click = false;
public bool AltClick = false;
public bool Use = false;
public bool ItemLeft = false;
public bool ItemRight = false;
public bool ItemUp = false;
public bool ItemDown = false;
public double SprintOrWalk = 0f;
public byte[] GetCharacterNetData()
{
DataStream ds = new DataStream();
DataWriter dr = new DataWriter(ds);
dr.WriteBytes(GetPosition().ToDoubleBytes());
Quaternion quat = GetOrientation();
dr.WriteFloat((float)quat.X);
dr.WriteFloat((float)quat.Y);
dr.WriteFloat((float)quat.Z);
dr.WriteFloat((float)quat.W);
dr.WriteFloat((float)GetMass());
dr.WriteFloat((float)CBAirForce);
dr.WriteFloat((float)CBAirSpeed);
dr.WriteFloat((float)CBCrouchSpeed);
dr.WriteFloat((float)CBDownStepHeight);
dr.WriteFloat((float)CBGlueForce);
dr.WriteFloat((float)CBHHeight);
dr.WriteFloat((float)CBJumpSpeed);
dr.WriteFloat((float)CBMargin);
dr.WriteFloat((float)CBMaxSupportSlope);
dr.WriteFloat((float)CBMaxTractionSlope);
dr.WriteFloat((float)CBProneSpeed);
dr.WriteFloat((float)CBRadius);
dr.WriteFloat((float)CBSlideForce);
dr.WriteFloat((float)CBSlideJumpSpeed);
dr.WriteFloat((float)CBSlideSpeed);
dr.WriteFloat((float)CBStandSpeed);
dr.WriteFloat((float)CBStepHeight);
dr.WriteFloat((float)CBTractionForce);
dr.WriteFloat((float)mod_xrot);
dr.WriteFloat((float)mod_yrot);
dr.WriteFloat((float)mod_zrot);
dr.WriteFloat((float)mod_scale);
dr.WriteInt(mod_color.ToArgb());
byte dtx = 0;
if (Visible)
{
dtx |= 1;
}
if (CGroup == CollisionUtil.Solid)
{
dtx |= 2;
}
else if (CGroup == CollisionUtil.NonSolid)
{
dtx |= 4;
}
else if (CGroup == CollisionUtil.Item)
{
dtx |= 2 | 4;
}
else if (CGroup == CollisionUtil.Player)
{
dtx |= 8;
}
else if (CGroup == CollisionUtil.Water)
{
dtx |= 2 | 8;
}
else if (CGroup == CollisionUtil.WorldSolid)
{
dtx |= 2 | 4 | 8;
}
else if (CGroup == CollisionUtil.Character)
{
dtx |= 16;
}
dr.Write(dtx);
dr.WriteInt(TheServer.Networking.Strings.IndexForString(model));
dr.Flush();
byte[] Data = ds.ToArray();
dr.Close();
return Data;
}
public virtual void Solidify()
{
CGroup = CollisionUtil.Character;
if (Body != null)
{
Body.CollisionInformation.CollisionRules.Group = CGroup;
}
}
public virtual void Desolidify()
{
CGroup = CollisionUtil.NonSolid;
if (Body != null)
{
Body.CollisionInformation.CollisionRules.Group = CGroup;
}
}
/// <summary>
/// The direction the character is currently facing, as Yaw/Pitch.
/// </summary>
public Location Direction;
public bool pup = false;
/// <summary>
/// Returns whether this character is currently crouching.
/// </summary>
public bool IsCrouching
{
get
{
return Downward || DesiredStance == Stance.Crouching || (CBody != null && CBody.StanceManager.CurrentStance == Stance.Crouching);
}
}
public Location TargetPosition = Location.NaN;
public Entity TargetEntity = null;
public double MaxPathFindDistance = 20;
public void GoTo(Location pos)
{
TargetPosition = pos;
TargetEntity = null;
UpdatePath();
}
public void GoTo(Entity e)
{
TargetPosition = Location.NaN;
TargetEntity = e;
UpdatePath();
}
public ListQueue<Location> Path = null;
public double PathFindCloseEnough = 0.8f * 0.8f;
public void UpdatePath()
{
Location goal = TargetPosition;
if (goal.IsNaN())
{
if (TargetEntity == null)
{
Path = null;
return;
}
goal = TargetEntity.GetPosition();
}
Location selfpos = GetPosition();
if ((goal - selfpos).LengthSquared() > MaxPathFindDistance * MaxPathFindDistance)
{
TargetPosition = Location.NaN; // TODO: Configurable "can't find path" result -> giveup vs. teleport
TargetEntity = null;
Path = null;
return;
}
List<Location> tpath = TheRegion.FindPath(selfpos, goal, MaxPathFindDistance, 1);
if (tpath == null)
{
TargetPosition = Location.NaN; // TODO: Configurable "can't find path" result -> giveup vs. teleport
TargetEntity = null;
Path = null;
return;
}
Path = new ListQueue<Location>(tpath);
PathUpdate = 1; // TODO: Configurable update time
}
/// <summary>
/// The internal physics character body.
/// </summary>
public CharacterController CBody;
public override void SpawnBody()
{
MinZ = CBHHeight;
if (CBody != null)
{
DestroyBody();
}
// TODO: Better variable control! (Server should command every detail!)
CBody = new CharacterController(WorldTransform.Translation, CBHHeight * 2f * mod_scale, CBHHeight * 1.1f * mod_scale,
CBHHeight * 1f * mod_scale, CBRadius * mod_scale, CBMargin, Mass, CBMaxTractionSlope, CBMaxSupportSlope, CBStandSpeed, CBCrouchSpeed, CBProneSpeed,
CBTractionForce * Mass, CBSlideSpeed, CBSlideForce * Mass, CBAirSpeed, CBAirForce * Mass, CBJumpSpeed, CBSlideJumpSpeed, CBGlueForce * Mass);
CBody.StanceManager.DesiredStance = Stance.Standing;
CBody.ViewDirection = new Vector3(1f, 0f, 0f);
CBody.Down = new Vector3(0f, 0f, -1f);
CBody.Tag = this;
Body = CBody.Body;
Body.Tag = this;
Body.AngularDamping = 1.0f;
Shape = CBody.Body.CollisionInformation.Shape;
Body.CollisionInformation.CollisionRules.Group = CGroup;
CBody.StepManager.MaximumStepHeight = CBStepHeight;
CBody.StepManager.MinimumDownStepHeight = CBDownStepHeight;
TheRegion.PhysicsWorld.Add(CBody);
RigidTransform transf = new RigidTransform(Vector3.Zero, Body.Orientation);
BoundingBox box;
Body.CollisionInformation.Shape.GetBoundingBox(ref transf, out box);
MinZ = box.Min.Z;
}
public override AbstractPacketOut GetUpdatePacket()
{
return new CharacterUpdatePacketOut(this);
}
public double PathUpdate = 0;
bool PathMovement = false;
public override void Tick()
{
if (TheRegion.Delta <= 0)
{
return;
}
if (!IsSpawned)
{
return;
}
PathUpdate -= TheRegion.Delta;
if (PathUpdate <= 0)
{
UpdatePath();
}
if (Path != null)
{
PathMovement = true;
Location spos = GetPosition();
while (Path.Length > 0 && ((Path.Peek() - spos).LengthSquared() < PathFindCloseEnough || (Path.Peek() - spos + new Location(0, 0, -1.5)).LengthSquared() < PathFindCloseEnough))
{
Path.Pop();
}
if (Path.Length <= 0)
{
Path = null;
}
else
{
Location targetdir = (Path.Peek() - spos).Normalize();
Location movegoal = Utilities.RotateVector(targetdir, (270 + Direction.Yaw) * Utilities.PI180);
Vector2 movegoal2 = new Vector2((double)movegoal.X, (double)movegoal.Y);
if (movegoal2.LengthSquared() > 0)
{
movegoal2.Normalize();
}
XMove = movegoal2.X;
YMove = movegoal2.Y;
if (movegoal.Z > 0.4)
{
CBody.Jump();
}
}
}
if (Path == null && PathMovement)
{
XMove = 0;
YMove = 0;
PathMovement = false;
}
while (Direction.Yaw < 0)
{
Direction.Yaw += 360;
}
while (Direction.Yaw > 360)
{
Direction.Yaw -= 360;
}
if (Direction.Pitch > 89.9f)
{
Direction.Pitch = 89.9f;
}
if (Direction.Pitch < -89.9f)
{
Direction.Pitch = -89.9f;
}
CBody.ViewDirection = Utilities.ForwardVector_Deg(Direction.Yaw, Direction.Pitch).ToBVector();
if (Upward && !IsFlying && !pup && CBody.SupportFinder.HasSupport)
{
CBody.Jump();
pup = true;
}
else if (!Upward)
{
pup = false;
}
double speedmod = new Vector2(XMove, YMove).Length() * 2;
speedmod *= (1f + SprintOrWalk * 0.5f);
if (ItemDoSpeedMod)
{
speedmod *= ItemSpeedMod;
}
Material mat = TheRegion.GetBlockMaterial(GetPosition() + new Location(0, 0, -0.05f));
speedmod *= mat.GetSpeedMod();
CBody.StandingSpeed = CBStandSpeed * speedmod;
CBody.CrouchingSpeed = CBCrouchSpeed * speedmod;
double frictionmod = 1f;
frictionmod *= mat.GetFrictionMod();
CBody.SlidingForce = CBSlideForce * frictionmod * Mass;
CBody.AirForce = CBAirForce * frictionmod * Mass;
CBody.TractionForce = CBTractionForce * frictionmod * Mass;
CBody.VerticalMotionConstraint.MaximumGlueForce = CBGlueForce * Mass;
if (CurrentSeat == null)
{
Vector3 movement = new Vector3(XMove, YMove, 0);
if (Upward && IsFlying)
{
movement.Z = 1;
}
else if (Downward && IsFlying)
{
movement.Z = -1;
}
if (movement.LengthSquared() > 0)
{
movement.Normalize();
}
if (Downward)
{
CBody.StanceManager.DesiredStance = Stance.Crouching;
}
else
{
CBody.StanceManager.DesiredStance = DesiredStance;
}
CBody.HorizontalMotionConstraint.MovementDirection = new Vector2(movement.X, movement.Y);
if (IsFlying)
{
Location forw = Utilities.RotateVector(new Location(-movement.Y, movement.X, movement.Z), Direction.Yaw * Utilities.PI180, Direction.Pitch * Utilities.PI180);
SetPosition(GetPosition() + forw * TheRegion.Delta * CBStandSpeed * 2 * speedmod);
CBody.HorizontalMotionConstraint.MovementDirection = Vector2.Zero;
Body.LinearVelocity = new Vector3(0, 0, 0);
}
}
else
{
CurrentSeat.HandleInput(this);
}
base.Tick();
RigidTransform transf = new RigidTransform(Vector3.Zero, Body.Orientation);
BoundingBox box;
Body.CollisionInformation.Shape.GetBoundingBox(ref transf, out box);
MinZ = box.Min.Z;
}
const double defHalfHeight = 1.3f;
public double CBHHeight = defHalfHeight;
public double CBProneSpeed = 1f;
public double CBMargin = 0.01f;
public double CBStepHeight = 0.6f;
public double CBDownStepHeight = 0.6f;
public double CBRadius = 0.3f;
public double CBMaxTractionSlope = 1.0f;
public double CBMaxSupportSlope = 1.3f;
public double CBStandSpeed = 5.0f;
public double CBCrouchSpeed = 2.5f;
public double CBSlideSpeed = 3f;
public double CBAirSpeed = 1f;
public double CBTractionForce = 100f;
public double CBSlideForce = 70f;
public double CBAirForce = 50f;
public double CBJumpSpeed = 8f;
public double CBSlideJumpSpeed = 3.5f;
public double CBGlueForce = 500f;
public override void DestroyBody()
{
if (CBody == null)
{
return;
}
TheRegion.PhysicsWorld.Remove(CBody);
CBody = null;
Body = null;
}
public double ItemSpeedMod = 1;
public bool ItemDoSpeedMod = false;
public bool IsFlying = false;
public double PreFlyMass = 0;
public static readonly Quaternion PreFlyOrient = Quaternion.CreateFromAxisAngle(Vector3.UnitX, Math.PI * 0.5);
public virtual void Fly()
{
if (IsFlying)
{
return;
}
//PreFlyOrient = GetOrientation();
PreFlyMass = GetMass();
IsFlying = true;
SetMass(0);
CBody.Body.AngularVelocity = Vector3.Zero;
}
public virtual void Unfly()
{
if (!IsFlying)
{
return;
}
SetMass(PreFlyMass);
IsFlying = false;
CBody.Body.LocalInertiaTensorInverse = new Matrix3x3();
SysConsole.Output(OutputType.INFO, "PFI: " + PreFlyOrient);
CBody.Body.Orientation = PreFlyOrient;
CBody.Body.AngularVelocity = Vector3.Zero;
}
public Stance DesiredStance = Stance.Standing;
public EntityUseable UsedNow = null;
public Location ForwardVector()
{
return Utilities.ForwardVector_Deg(Direction.Yaw, Direction.Pitch);
}
public abstract Location GetEyePosition();
public double MinZ = -defHalfHeight * 1.5f;
public override Location GetPosition()
{
return base.GetPosition() + new Location(0, 0, MinZ);
}
public override void SetPosition(Location pos)
{
base.SetPosition(pos + new Location(0, 0, -MinZ));
}
public Location GetCenter()
{
return base.GetPosition();
}
public override Quaternion GetOrientation()
{
return Quaternion.CreateFromAxisAngle(Vector3.UnitY, (double)Direction.Pitch)
* Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (double)Direction.Yaw);
}
public override void SetOrientation(Quaternion rot)
{
Matrix trot = Matrix.CreateFromQuaternion(rot);
Location ang = Utilities.MatrixToAngles(trot);
Direction.Yaw = ang.Yaw;
Direction.Pitch = ang.Pitch;
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.ViewServices;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.GestionClient.DemandeContact.Tabs.Search;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.DemandeContact;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionClient.DemandeContact;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.DataGrid.Manager;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionClient.DemandeContact.Tabs
{
public class SearchViewModel : TabBase, IDisposable
{
private readonly IResourceWrapper _resourceWrapper;
private readonly ILoaderReferentiel _referentiel;
private readonly INotificationViewService _notificationService;
private readonly IDepotDemandeContact _demandeContact;
private readonly IModelBuilderDetails _builderDetails;
private ObservableCollection<DemandeContactResult> _searchResult;
private bool _searchOverflow;
private bool _isLoading;
private ICommand _resetCommand;
private ICommand _searchCommand;
private ICommand _doubleClickCommand;
private DataGridColumnManager _manager;
private SearchEntityViewModel _entity;
protected ChannelObserver<UpdateListMessage> ObserverUpdateList { get; private set; }
[ResolveConstructor]
public SearchViewModel(
IResourceWrapper resourceWrapper,
IMessenging messengingService,
IApplicationContext applicationContext,
ILoaderReferentiel referentiel,
INotificationViewService notificationService,
IDepotDemandeContact demandeContact,
IModelBuilderDetails builderDetails)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_referentiel = referentiel;
_notificationService = notificationService;
_demandeContact = demandeContact;
_builderDetails = builderDetails;
InitializeCommands();
InitializeMessenging();
InitializeUI();
}
public DataGridColumnManager DataGridManager
{
get
{
return _manager;
}
set
{
if (_manager != value)
{
_manager = value;
NotifyPropertyChanged(() => DataGridManager);
}
}
}
public ObservableCollection<DemandeContactResult> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public bool SearchOverflow
{
get
{
return _searchOverflow;
}
set
{
if (_searchOverflow != value)
{
_searchOverflow = value;
NotifyPropertyChanged(() => SearchOverflow);
}
}
}
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
public ICommand ResetCommand
{
get
{
return _resetCommand;
}
set
{
if (_resetCommand != value)
{
_resetCommand = value;
NotifyPropertyChanged(() => ResetCommand);
}
}
}
/// <summary>
/// Command de recherche des demande de contact.
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
public SearchEntityViewModel Entity
{
get
{
return _entity;
}
set
{
if (_entity != value)
{
_entity = value;
NotifyPropertyChanged(() => Entity);
}
}
}
private void InitializeCommands()
{
_resetCommand = new ActionCommand(OnReset);
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<DemandeContactResult>(OnDoubleClickCommand);
}
private void InitializeMessenging()
{
ObserverUpdateList = _messengingService.CreateObserver<UpdateListMessage>(Msg =>
{
if (Msg.Type != TypeUpdateList.RechercheDemandeContact)
return;
});
ObserverUpdateList.Subscribe(ThreadOption.UIThread);
}
private void InitializeUI()
{
SearchResult = new ObservableCollection<DemandeContactResult>();
SearchOverflow = false;
IsLoading = false;
Entity = new SearchEntityViewModel(_referentiel);
DataGridManager = new DataGridColumnManager();
}
private void DisposeMessenging()
{
ObserverUpdateList.Unsubscribe();
}
private void OnReset()
{
Entity.Criterias.Reset();
}
private void OnSearch()
{
if (IsLoading)
return;
Entity.Criterias.NotifyAllCheckError(Entity.Criterias);
if (Entity.Criterias.HasErrors)
{
var message = _resourceWrapper.ErrorsResourceManager.GetString("ERROR_CHECK");
_notificationService.ShowNotification(message);
return;
}
var limitValue = _referentiel.Referentiel.Parametres.Where(x => x.Code.Equals("SearchDemandeContactLimit")).Select(x => x.Valeur).FirstOrDefault();
var limit = Convert.ToInt32(limitValue);
var criterias = AutoMapper.Mapper.Map<SearchDemandeContactEntityCriteriasViewModel, SearchDemandeContactCriteriasDto>(Entity.Criterias);
_demandeContact.Search(
criterias,
r =>
{
foreach (var P in r)
SearchResult.Add(P);
SearchOverflow = SearchResult.Count == limit;
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(DemandeContactResult selected)
{
if (selected != null)
{
DemandeContactHelper.AddDemandeContactTab(selected, _messengingService, _applicationContext, _demandeContact, _builderDetails);
}
}
public void Dispose()
{
DisposeMessenging();
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// RequestSpotInstances Request Marshaller
/// </summary>
public class RequestSpotInstancesRequestMarshaller : IMarshaller<IRequest, RequestSpotInstancesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((RequestSpotInstancesRequest)input);
}
public IRequest Marshall(RequestSpotInstancesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2");
request.Parameters.Add("Action", "RequestSpotInstances");
request.Parameters.Add("Version", "2014-10-01");
if(publicRequest != null)
{
if(publicRequest.IsSetAvailabilityZoneGroup())
{
request.Parameters.Add("AvailabilityZoneGroup", StringUtils.FromString(publicRequest.AvailabilityZoneGroup));
}
if(publicRequest.IsSetInstanceCount())
{
request.Parameters.Add("InstanceCount", StringUtils.FromInt(publicRequest.InstanceCount));
}
if(publicRequest.IsSetLaunchGroup())
{
request.Parameters.Add("LaunchGroup", StringUtils.FromString(publicRequest.LaunchGroup));
}
if(publicRequest.IsSetLaunchSpecification())
{
if(publicRequest.LaunchSpecification.IsSetAddressingType())
{
request.Parameters.Add("LaunchSpecification" + "." + "AddressingType", StringUtils.FromString(publicRequest.LaunchSpecification.AddressingType));
}
if(publicRequest.LaunchSpecification.IsSetBlockDeviceMappings())
{
int publicRequestLaunchSpecificationlistValueIndex = 1;
foreach(var publicRequestLaunchSpecificationlistValue in publicRequest.LaunchSpecification.BlockDeviceMappings)
{
if(publicRequestLaunchSpecificationlistValue.IsSetDeviceName())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "DeviceName", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.DeviceName));
}
if(publicRequestLaunchSpecificationlistValue.IsSetEbs())
{
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetDeleteOnTermination())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "DeleteOnTermination", StringUtils.FromBool(publicRequestLaunchSpecificationlistValue.Ebs.DeleteOnTermination));
}
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetEncrypted())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "Encrypted", StringUtils.FromBool(publicRequestLaunchSpecificationlistValue.Ebs.Encrypted));
}
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetIops())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "Iops", StringUtils.FromInt(publicRequestLaunchSpecificationlistValue.Ebs.Iops));
}
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetSnapshotId())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "SnapshotId", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.Ebs.SnapshotId));
}
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetVolumeSize())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "VolumeSize", StringUtils.FromInt(publicRequestLaunchSpecificationlistValue.Ebs.VolumeSize));
}
if(publicRequestLaunchSpecificationlistValue.Ebs.IsSetVolumeType())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Ebs" + "." + "VolumeType", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.Ebs.VolumeType));
}
}
if(publicRequestLaunchSpecificationlistValue.IsSetNoDevice())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "NoDevice", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.NoDevice));
}
if(publicRequestLaunchSpecificationlistValue.IsSetVirtualName())
{
request.Parameters.Add("LaunchSpecification" + "." + "BlockDeviceMapping" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "VirtualName", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.VirtualName));
}
publicRequestLaunchSpecificationlistValueIndex++;
}
}
if(publicRequest.LaunchSpecification.IsSetEbsOptimized())
{
request.Parameters.Add("LaunchSpecification" + "." + "EbsOptimized", StringUtils.FromBool(publicRequest.LaunchSpecification.EbsOptimized));
}
if(publicRequest.LaunchSpecification.IsSetIamInstanceProfile())
{
if(publicRequest.LaunchSpecification.IamInstanceProfile.IsSetArn())
{
request.Parameters.Add("LaunchSpecification" + "." + "IamInstanceProfile" + "." + "Arn", StringUtils.FromString(publicRequest.LaunchSpecification.IamInstanceProfile.Arn));
}
if(publicRequest.LaunchSpecification.IamInstanceProfile.IsSetName())
{
request.Parameters.Add("LaunchSpecification" + "." + "IamInstanceProfile" + "." + "Name", StringUtils.FromString(publicRequest.LaunchSpecification.IamInstanceProfile.Name));
}
}
if(publicRequest.LaunchSpecification.IsSetImageId())
{
request.Parameters.Add("LaunchSpecification" + "." + "ImageId", StringUtils.FromString(publicRequest.LaunchSpecification.ImageId));
}
if(publicRequest.LaunchSpecification.IsSetInstanceType())
{
request.Parameters.Add("LaunchSpecification" + "." + "InstanceType", StringUtils.FromString(publicRequest.LaunchSpecification.InstanceType));
}
if(publicRequest.LaunchSpecification.IsSetKernelId())
{
request.Parameters.Add("LaunchSpecification" + "." + "KernelId", StringUtils.FromString(publicRequest.LaunchSpecification.KernelId));
}
if(publicRequest.LaunchSpecification.IsSetKeyName())
{
request.Parameters.Add("LaunchSpecification" + "." + "KeyName", StringUtils.FromString(publicRequest.LaunchSpecification.KeyName));
}
if(publicRequest.LaunchSpecification.IsSetMonitoringEnabled())
{
request.Parameters.Add("LaunchSpecification" + "." + "Monitoring.Enabled", StringUtils.FromBool(publicRequest.LaunchSpecification.MonitoringEnabled));
}
if(publicRequest.LaunchSpecification.IsSetNetworkInterfaces())
{
int publicRequestLaunchSpecificationlistValueIndex = 1;
foreach(var publicRequestLaunchSpecificationlistValue in publicRequest.LaunchSpecification.NetworkInterfaces)
{
if(publicRequestLaunchSpecificationlistValue.IsSetAssociatePublicIpAddress())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "AssociatePublicIpAddress", StringUtils.FromBool(publicRequestLaunchSpecificationlistValue.AssociatePublicIpAddress));
}
if(publicRequestLaunchSpecificationlistValue.IsSetDeleteOnTermination())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "DeleteOnTermination", StringUtils.FromBool(publicRequestLaunchSpecificationlistValue.DeleteOnTermination));
}
if(publicRequestLaunchSpecificationlistValue.IsSetDescription())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "Description", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.Description));
}
if(publicRequestLaunchSpecificationlistValue.IsSetDeviceIndex())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "DeviceIndex", StringUtils.FromInt(publicRequestLaunchSpecificationlistValue.DeviceIndex));
}
if(publicRequestLaunchSpecificationlistValue.IsSetGroups())
{
int publicRequestLaunchSpecificationlistValuelistValueIndex = 1;
foreach(var publicRequestLaunchSpecificationlistValuelistValue in publicRequestLaunchSpecificationlistValue.Groups)
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "SecurityGroupId" + "." + publicRequestLaunchSpecificationlistValuelistValueIndex, StringUtils.FromString(publicRequestLaunchSpecificationlistValuelistValue));
publicRequestLaunchSpecificationlistValuelistValueIndex++;
}
}
if(publicRequestLaunchSpecificationlistValue.IsSetNetworkInterfaceId())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "NetworkInterfaceId", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.NetworkInterfaceId));
}
if(publicRequestLaunchSpecificationlistValue.IsSetPrivateIpAddress())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "PrivateIpAddress", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.PrivateIpAddress));
}
if(publicRequestLaunchSpecificationlistValue.IsSetPrivateIpAddresses())
{
int publicRequestLaunchSpecificationlistValuelistValueIndex = 1;
foreach(var publicRequestLaunchSpecificationlistValuelistValue in publicRequestLaunchSpecificationlistValue.PrivateIpAddresses)
{
if(publicRequestLaunchSpecificationlistValuelistValue.IsSetPrimary())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "PrivateIpAddressesSet" + "." + publicRequestLaunchSpecificationlistValuelistValueIndex + "." + "Primary", StringUtils.FromBool(publicRequestLaunchSpecificationlistValuelistValue.Primary));
}
if(publicRequestLaunchSpecificationlistValuelistValue.IsSetPrivateIpAddress())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "PrivateIpAddressesSet" + "." + publicRequestLaunchSpecificationlistValuelistValueIndex + "." + "PrivateIpAddress", StringUtils.FromString(publicRequestLaunchSpecificationlistValuelistValue.PrivateIpAddress));
}
publicRequestLaunchSpecificationlistValuelistValueIndex++;
}
}
if(publicRequestLaunchSpecificationlistValue.IsSetSecondaryPrivateIpAddressCount())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "SecondaryPrivateIpAddressCount", StringUtils.FromInt(publicRequestLaunchSpecificationlistValue.SecondaryPrivateIpAddressCount));
}
if(publicRequestLaunchSpecificationlistValue.IsSetSubnetId())
{
request.Parameters.Add("LaunchSpecification" + "." + "NetworkInterface" + "." + publicRequestLaunchSpecificationlistValueIndex + "." + "SubnetId", StringUtils.FromString(publicRequestLaunchSpecificationlistValue.SubnetId));
}
publicRequestLaunchSpecificationlistValueIndex++;
}
}
if(publicRequest.LaunchSpecification.IsSetPlacement())
{
if(publicRequest.LaunchSpecification.Placement.IsSetAvailabilityZone())
{
request.Parameters.Add("LaunchSpecification" + "." + "Placement" + "." + "AvailabilityZone", StringUtils.FromString(publicRequest.LaunchSpecification.Placement.AvailabilityZone));
}
if(publicRequest.LaunchSpecification.Placement.IsSetGroupName())
{
request.Parameters.Add("LaunchSpecification" + "." + "Placement" + "." + "GroupName", StringUtils.FromString(publicRequest.LaunchSpecification.Placement.GroupName));
}
}
if(publicRequest.LaunchSpecification.IsSetRamdiskId())
{
request.Parameters.Add("LaunchSpecification" + "." + "RamdiskId", StringUtils.FromString(publicRequest.LaunchSpecification.RamdiskId));
}
if(publicRequest.LaunchSpecification.IsSetSubnetId())
{
request.Parameters.Add("LaunchSpecification" + "." + "SubnetId", StringUtils.FromString(publicRequest.LaunchSpecification.SubnetId));
}
if(publicRequest.LaunchSpecification.IsSetUserData())
{
request.Parameters.Add("LaunchSpecification" + "." + "UserData", StringUtils.FromString(publicRequest.LaunchSpecification.UserData));
}
}
if(publicRequest.IsSetSpotPrice())
{
request.Parameters.Add("SpotPrice", StringUtils.FromString(publicRequest.SpotPrice));
}
if(publicRequest.IsSetType())
{
request.Parameters.Add("Type", StringUtils.FromString(publicRequest.Type));
}
if(publicRequest.IsSetValidFrom())
{
request.Parameters.Add("ValidFrom", StringUtils.FromDateTime(publicRequest.ValidFrom));
}
if(publicRequest.IsSetValidUntil())
{
request.Parameters.Add("ValidUntil", StringUtils.FromDateTime(publicRequest.ValidUntil));
}
}
return request;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>ManagedPlacementView</c> resource.</summary>
public sealed partial class ManagedPlacementViewName : gax::IResourceName, sys::IEquatable<ManagedPlacementViewName>
{
/// <summary>The possible contents of <see cref="ManagedPlacementViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
CustomerAdGroupCriterion = 1,
}
private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/managedPlacementViews/{ad_group_id_criterion_id}");
/// <summary>Creates a <see cref="ManagedPlacementViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ManagedPlacementViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ManagedPlacementViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ManagedPlacementViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ManagedPlacementViewName"/> with the pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="ManagedPlacementViewName"/> constructed from the provided ids.
/// </returns>
public static ManagedPlacementViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
new ManagedPlacementViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string criterionId) =>
FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ManagedPlacementViewName"/> with pattern
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ManagedPlacementViewName"/> if successful.</returns>
public static ManagedPlacementViewName Parse(string managedPlacementViewName) =>
Parse(managedPlacementViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ManagedPlacementViewName"/> if successful.</returns>
public static ManagedPlacementViewName Parse(string managedPlacementViewName, bool allowUnparsed) =>
TryParse(managedPlacementViewName, allowUnparsed, out ManagedPlacementViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ManagedPlacementViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string managedPlacementViewName, out ManagedPlacementViewName result) =>
TryParse(managedPlacementViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ManagedPlacementViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="managedPlacementViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ManagedPlacementViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string managedPlacementViewName, bool allowUnparsed, out ManagedPlacementViewName result)
{
gax::GaxPreconditions.CheckNotNull(managedPlacementViewName, nameof(managedPlacementViewName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupCriterion.TryParseName(managedPlacementViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(managedPlacementViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private ManagedPlacementViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ManagedPlacementViewName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/managedPlacementViews/{ad_group_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public ManagedPlacementViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ManagedPlacementViewName);
/// <inheritdoc/>
public bool Equals(ManagedPlacementViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ManagedPlacementViewName a, ManagedPlacementViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ManagedPlacementViewName a, ManagedPlacementViewName b) => !(a == b);
}
public partial class ManagedPlacementView
{
/// <summary>
/// <see cref="ManagedPlacementViewName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ManagedPlacementViewName ResourceNameAsManagedPlacementViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ManagedPlacementViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// 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 System.Collections;
using System.Globalization;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListCtorIDicComp
{
public class Driver<KeyType, ValueType>
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
private CultureInfo _english = new CultureInfo("en");
private CultureInfo _german = new CultureInfo("de");
private CultureInfo _danish = new CultureInfo("da");
private CultureInfo _turkish = new CultureInfo("tr");
//CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING
//CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING
//CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING
//CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING
//CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestEnum(IDictionary<String, String> idic)
{
SortedList<String, String> _dic;
String[] keys = new String[idic.Count];
idic.Keys.CopyTo(keys, 0);
String[] values = new String[idic.Count];
idic.Values.CopyTo(values, 0);
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.Ordinal,
StringComparer.OrdinalIgnoreCase};
foreach (StringComparer comparison in predefinedComparers)
{
_dic = new SortedList<String, String>(idic, comparison);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.ContainsKey(keys[i]), String.Format("Err_234afs! key not found: {0}", keys[i]));
m_test.Eval(_dic.ContainsValue(values[i]), String.Format("Err_3497sg! value not found: {0}", values[i]));
}
}
IComparer<String> comparer;
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(idic, comparer);
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//bug #11263 in NDPWhidbey
CultureInfo.DefaultThreadCurrentCulture = _german;
_dic = new SortedList<String, String>(idic, StringComparer.CurrentCulture);
_dic.Add(strAE, value);
//
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(idic, StringComparer.CurrentCultureIgnoreCase);
_dic.Add(straA, value);
m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(idic, StringComparer.CurrentCultureIgnoreCase);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
// was for InvariantCulrureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(idic, StringComparer.OrdinalIgnoreCase);
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
CultureInfo.DefaultThreadCurrentCulture = _turkish;
_dic = new SortedList<String, String>(idic, StringComparer.OrdinalIgnoreCase);
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
//Ordinal - not that many meaningful test
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(idic, StringComparer.Ordinal);
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<String, String>(idic, StringComparer.Ordinal);
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
}
public void TestParm()
{
//passing null will revert to the default comparison mechanism
SortedList<String, String> _dic;
SortedList<String, String> dic1 = new SortedList<String, String>();
dic1 = null;
try
{
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<String, String>(dic1, StringComparer.CurrentCulture);
m_test.Eval(false, String.Format("Err_387tsg! exception not thrown"));
}
catch (ArgumentNullException)
{
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
public void VerifyProperSortUsedForCasedStrings(IDictionary<string, string> idic, StringComparer originalComparer, CultureInfo originalCulture)
{
SortedList<string, string> _dic;
SortedList<string, string> originalDic;
originalDic = new SortedList<string, string>(idic, originalComparer);
_dic = new SortedList<string, string>(originalDic, StringComparer.Ordinal);
CultureInfo.DefaultThreadCurrentCulture = _english;
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsOrdinal[i], "VerifyProperSortUsedForCasedStrings1: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsOrdinal[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<string, string>(originalDic, StringComparer.Ordinal);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsOrdinal[i], "VerifyProperSortUsedForCasedStrings2: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsOrdinal[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCulture);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsEnCulture[i], "VerifyProperSortUsedForCasedStrings3: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsEnCulture[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCulture);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsDaCulture[i], "VerifyProperSortUsedForCasedStrings4: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsDaCulture[i] + ", but found " + _dic.Keys[i]);
}
}
public void VerifyProperSortUsedForNonCasedStrings(IDictionary<string, string> idic, StringComparer originalComparer, CultureInfo originalCulture)
{
SortedList<string, string> _dic;
SortedList<string, string> originalDic;
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<string, string>(originalDic, StringComparer.Ordinal);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseOrdinal[i], "VerifyProperSortUsedForNonCasedStrings1: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseOrdinal[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<string, string>(originalDic, StringComparer.Ordinal);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseOrdinal[i], "VerifyProperSortUsedForNonCasedStrings2: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseOrdinal[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCulture);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseEnCulture[i], "VerifyProperSortUsedForNonCasedStrings3: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseEnCulture[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCulture);
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseDaCulture[i], "VerifyProperSortUsedForNonCasedStrings4: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseDaCulture[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCultureIgnoreCase);
try
{
_dic.Add("apple", "apple");
m_test.Eval(false, "VerifyProperSortUsedForNonCasedStrings7: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected adding apple to IgnoreCase that contains Apple to throw ArgumentException but it did not.");
}
catch (ArgumentException)
{
}
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseEnCulture[i], "VerifyProperSortUsedForNonCasedStrings8: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseEnCulture[i] + ", but found " + _dic.Keys[i]);
}
CultureInfo.DefaultThreadCurrentCulture = originalCulture;
originalDic = new SortedList<string, string>(idic, originalComparer);
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedList<string, string>(originalDic, StringComparer.CurrentCultureIgnoreCase);
try
{
_dic.Add("apple", "apple");
m_test.Eval(false, "VerifyProperSortUsedForNonCasedStrings9: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected adding apple to IgnoreCase that contains Apple to throw ArgumentException but it did not.");
}
catch (ArgumentException)
{
}
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.Keys[i] == Constructor_IDictionary_StringComparer.stringsNoCaseDaCulture[i], "VerifyProperSortUsedForNonCasedStrings10: OriginalCulture/StringComparer" + originalCulture + "/" + originalComparer + "Expected key " + i + " to be " + Constructor_IDictionary_StringComparer.stringsNoCaseDaCulture[i] + ", but found " + _dic.Keys[i]);
}
}
}
public class Constructor_IDictionary_StringComparer
{
private static CultureInfo s_english = new CultureInfo("en");
private static CultureInfo s_german = new CultureInfo("de");
private static CultureInfo s_danish = new CultureInfo("da");
private static CultureInfo s_turkish = new CultureInfo("tr");
private static int s_count = 14;
static public String[] strings = new String[s_count];
static public String[] stringsOrdinal = new String[s_count];
static public String[] stringsEnCulture = new String[s_count];
static public String[] stringsDaCulture = new String[s_count];
static public String[] stringsNoCase = new String[s_count];
static public String[] stringsNoCaseOrdinal = new String[s_count];
static public String[] stringsNoCaseEnCulture = new String[s_count];
static public String[] stringsNoCaseDaCulture = new String[s_count];
[Fact]
public static void RunTests()
{
//This mostly follows the format established by the original author of these tests
Test test = new Test();
Driver<String, String> driver1 = new Driver<String, String>(test);
Driver<SimpleRef<int>, SimpleRef<String>> driver2 = new Driver<SimpleRef<int>, SimpleRef<String>>(test);
Driver<SimpleRef<String>, SimpleRef<int>> driver3 = new Driver<SimpleRef<String>, SimpleRef<int>>(test);
Driver<SimpleRef<int>, SimpleRef<int>> driver4 = new Driver<SimpleRef<int>, SimpleRef<int>>(test);
Driver<SimpleRef<String>, SimpleRef<String>> driver5 = new Driver<SimpleRef<String>, SimpleRef<String>>(test);
SimpleRef<int>[] simpleInts;
SimpleRef<String>[] simpleStrings;
SortedList<String, String> dic1;
SortedList<SimpleRef<int>, SimpleRef<String>> dic2;
SortedList<SimpleRef<String>, SimpleRef<int>> dic3;
SortedList<SimpleRef<int>, SimpleRef<int>> dic4;
SortedList<SimpleRef<String>, SimpleRef<String>> dic5;
for (int i = 0; i < s_count; i++)
{
strings[i] = i.ToString();
stringsOrdinal[i] = i.ToString();
stringsEnCulture[i] = i.ToString();
stringsDaCulture[i] = i.ToString();
stringsNoCase[i] = i.ToString();
stringsNoCaseOrdinal[i] = i.ToString();
stringsNoCaseEnCulture[i] = i.ToString();
stringsNoCaseDaCulture[i] = i.ToString();
}
strings[10] = "Apple";
strings[11] = "\u00C6ble";
strings[12] = "Zebra";
strings[13] = "apple";
stringsOrdinal[10] = "Apple";
stringsOrdinal[11] = "Zebra";
stringsOrdinal[12] = "apple";
stringsOrdinal[13] = "\u00C6ble";
stringsEnCulture[10] = "\u00C6ble";
stringsEnCulture[11] = "apple";
stringsEnCulture[12] = "Apple";
stringsEnCulture[13] = "Zebra";
stringsDaCulture[10] = "apple";
stringsDaCulture[11] = "Apple";
stringsDaCulture[12] = "Zebra";
stringsDaCulture[13] = "\u00C6ble";
stringsNoCase[10] = "Apple";
stringsNoCase[11] = "\u00C6ble";
stringsNoCase[12] = "Zebra";
stringsNoCase[13] = "aapple";
stringsNoCaseOrdinal[10] = "Apple";
stringsNoCaseOrdinal[11] = "Zebra";
stringsNoCaseOrdinal[12] = "aapple";
stringsNoCaseOrdinal[13] = "\u00C6ble";
stringsNoCaseEnCulture[10] = "aapple";
stringsNoCaseEnCulture[11] = "\u00C6ble";
stringsNoCaseEnCulture[12] = "Apple";
stringsNoCaseEnCulture[13] = "Zebra";
stringsNoCaseDaCulture[10] = "Apple";
stringsNoCaseDaCulture[11] = "Zebra";
stringsNoCaseDaCulture[12] = "\u00C6ble";
stringsNoCaseDaCulture[13] = "aapple";
simpleInts = GetSimpleInts(s_count);
simpleStrings = GetSimpleStrings(s_count);
simpleStrings[10].Val = "Apple";
simpleStrings[11].Val = "\u00C6ble";
simpleStrings[12].Val = "Zebra";
simpleStrings[13].Val = "aapple";
dic1 = FillValues(stringsNoCase, stringsNoCase);
dic2 = FillValues(simpleInts, simpleStrings);
dic3 = FillValues(simpleStrings, simpleInts);
dic4 = FillValues(simpleInts, simpleInts);
dic5 = FillValues(simpleStrings, simpleStrings);
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver1.TestEnum(dic1);
//Scenario 2: Parm validation: null
driver1.TestParm();
//Scenario 3: Non-string implementations and check
//Scenario 4: ensure that SortedList items from the passed IDictionary object use the interface IKeyComparer's Equals and GetHashCode APIs.
//Ex. Pass the case invariant IKeyComparer and check
//@TODO!!!
//Scenario 5: Contradictory values and check: ex. IDictionary is case insensitive but IKeyComparer is not
//Add SortedList that uses different type of StringComparer and verify
SortedList<String, String> dicComparison1 = new SortedList<String, String>(StringComparer.CurrentCulture);
SortedList<String, String> dicComparison2 = new SortedList<String, String>(StringComparer.CurrentCultureIgnoreCase);
SortedList<String, String> dicComparison4 = new SortedList<String, String>(StringComparer.OrdinalIgnoreCase);
SortedList<String, String> dicComparison5 = new SortedList<String, String>(StringComparer.Ordinal);
dicComparison1 = FillValues(stringsNoCase, stringsNoCase);
dicComparison2 = FillValues(stringsNoCase, stringsNoCase);
dicComparison4 = FillValues(stringsNoCase, stringsNoCase);
dicComparison5 = FillValues(stringsNoCase, stringsNoCase);
//Add Dictionary that uses different type of StringComparer and verify
Dictionary<String, String> justDicComparison1 = new Dictionary<String, String>();
Dictionary<String, String> justDicComparison2 = new Dictionary<String, String>();
justDicComparison1 = FillDictionaryValues(strings, strings);
justDicComparison2 = FillDictionaryValues(stringsNoCase, stringsNoCase);
//english original
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCulture, s_english);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCultureIgnoreCase, s_english);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.OrdinalIgnoreCase, s_english);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.Ordinal, s_english);
//danish original
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCulture, s_danish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCultureIgnoreCase, s_danish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.OrdinalIgnoreCase, s_danish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.Ordinal, s_danish);
// german original
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCulture, s_german);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCultureIgnoreCase, s_german);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.OrdinalIgnoreCase, s_german);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.Ordinal, s_german);
// turkish original
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCulture, s_turkish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.CurrentCultureIgnoreCase, s_turkish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.OrdinalIgnoreCase, s_turkish);
driver1.VerifyProperSortUsedForCasedStrings(justDicComparison1, StringComparer.Ordinal, s_turkish);
////english original
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCulture, s_english);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCultureIgnoreCase, s_english);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.OrdinalIgnoreCase, s_english);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.Ordinal, s_english);
//danish original
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCulture, s_danish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCultureIgnoreCase, s_danish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.OrdinalIgnoreCase, s_danish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.Ordinal, s_danish);
// german original
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCulture, s_german);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCultureIgnoreCase, s_german);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.OrdinalIgnoreCase, s_german);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.Ordinal, s_german);
// turkish original
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCulture, s_turkish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.CurrentCultureIgnoreCase, s_turkish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.OrdinalIgnoreCase, s_turkish);
driver1.VerifyProperSortUsedForNonCasedStrings(justDicComparison2, StringComparer.Ordinal, s_turkish);
Assert.True(test.result);
}
private static SortedList<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static Dictionary<KeyType, ValueType> FillDictionaryValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
Dictionary<KeyType, ValueType> _dic = new Dictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] simpleInts = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
simpleInts[i] = new SimpleRef<int>(i);
return simpleInts;
}
private static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] simpleStrings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
simpleStrings[i] = new SimpleRef<String>(i.ToString());
return simpleStrings;
}
}
}
| |
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using Neo4j.Driver.Internal;
using Neo4j.Driver.Internal.Result;
using Xunit;
namespace Neo4j.Driver.Tests
{
public class ResultCursorBuilderTests
{
[Fact]
public void ShouldStartInRunRequestedStateRx()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null, reactive: true);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunRequested);
}
[Fact]
public void ShouldStartInRunAndRecordsRequestedState()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunAndRecordsRequested);
}
[Fact]
public void ShouldTransitionToRunCompletedWhenRunCompletedRx()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null, reactive: true);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunRequested);
builder.RunCompleted(0, new[] {"a", "b", "c"}, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunCompleted);
}
[Fact]
public void ShouldNotTransitionToRunCompletedWhenRunCompleted()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunAndRecordsRequested);
builder.RunCompleted(0, new[] {"a", "b", "c"}, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunAndRecordsRequested);
}
[Fact]
public void ShouldTransitionToRecordsStreamingStreamingWhenRecordIsPushedRx()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null, reactive: true);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunRequested);
builder.RunCompleted(0, new[] {"a", "b", "c"}, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunCompleted);
builder.PushRecord(new object[] {1, 2, 3});
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RecordsStreaming);
}
[Fact]
public void ShouldTransitionToRecordsStreamingStreamingWhenRecordIsPushed()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunAndRecordsRequested);
builder.RunCompleted(0, new[] {"a", "b", "c"}, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunAndRecordsRequested);
builder.PushRecord(new object[] {1, 2, 3});
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RecordsStreaming);
}
[Fact]
public void ShouldTransitionToRunCompletedWhenPullCompletedWithHasMore()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null)
{
CurrentState = ResultCursorBuilder.State.RecordsStreaming
};
builder.PullCompleted(true, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunCompleted);
}
[Fact]
public void ShouldTransitionToCompletedWhenPullCompleted()
{
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(), null, null, null)
{
CurrentState = ResultCursorBuilder.State.RecordsStreaming
};
builder.PullCompleted(false, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.Completed);
}
[Fact]
public async Task ShouldInvokeResourceHandlerWhenCompleted()
{
var actions = new Queue<Action>();
var resourceHandler = new Mock<IResultResourceHandler>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions), null, null,
resourceHandler.Object);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PushRecord(new object[] {1}));
actions.Enqueue(() => builder.PushRecord(new object[] {2}));
actions.Enqueue(() => builder.PushRecord(new object[] {3}));
actions.Enqueue(() => builder.PullCompleted(false, null));
var cursor = builder.CreateCursor();
var hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Never);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Never);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Never);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeFalse();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Once);
}
[Fact]
public async Task ShouldPauseAndResumeStreamingWithWatermarks()
{
var actions = new Queue<Action>();
var resourceHandler = new Mock<IResultResourceHandler>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(),
CreateMoreTaskQueue(actions),
null,
resourceHandler.Object, 2);
var counter = 0;
builder.RunCompleted(0, new[] {"a"}, null);
builder.PullCompleted(true, null);
builder.CurrentState.Should().Be(ResultCursorBuilder.State.RunCompleted);
actions.Enqueue(() =>
{
builder.PushRecord(new object[] {1});
counter++;
builder.PushRecord(new object[] {2});
counter++;
builder.PullCompleted(true, null);
});
actions.Enqueue(() =>
{
builder.PushRecord(new object[] {3});
counter++;
builder.PullCompleted(false, null);
});
var cursor = builder.CreateCursor();
var hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Never);
counter.Should().Be(2);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
resourceHandler.Verify(x => x.OnResultConsumedAsync(), Times.Once);
counter.Should().Be(3);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeTrue();
counter.Should().Be(3);
hasNext = await cursor.FetchAsync();
hasNext.Should().BeFalse();
counter.Should().Be(3);
}
public class Reactive
{
private int moreCallCount;
private int cancelCallCount;
[Fact]
public async Task ShouldCallMoreOnceAndReturnRecords()
{
var actions = new Queue<Action>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions),
MoreFunction(), CancelFunction(), null, reactive: true);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PushRecord(new object[] {1}));
actions.Enqueue(() => builder.PushRecord(new object[] {2}));
actions.Enqueue(() => builder.PushRecord(new object[] {3}));
actions.Enqueue(() => builder.PullCompleted(false, null));
var list = await builder.CreateCursor().ToListAsync(r => r[0].As<int>());
list.Should().BeEquivalentTo(1, 2, 3);
moreCallCount.Should().Be(1);
cancelCallCount.Should().Be(0);
}
[Fact]
public async Task ShouldCallMoreTwiceAndReturnRecords()
{
var actions = new Queue<Action>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions),
MoreFunction(), CancelFunction(), null, reactive: true);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PushRecord(new object[] {1}));
actions.Enqueue(() => builder.PullCompleted(true, null));
actions.Enqueue(() => builder.PushRecord(new object[] {2}));
actions.Enqueue(() => builder.PushRecord(new object[] {3}));
actions.Enqueue(() => builder.PullCompleted(false, null));
var list = await builder.CreateCursor().ToListAsync(r => r[0].As<int>());
list.Should().BeEquivalentTo(1, 2, 3);
moreCallCount.Should().Be(2);
cancelCallCount.Should().Be(0);
}
[Fact]
public async Task ShouldCallMoreThreeTimesAndReturnRecords()
{
var actions = new Queue<Action>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions),
MoreFunction(), CancelFunction(), null, reactive: true);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PushRecord(new object[] {1}));
actions.Enqueue(() => builder.PullCompleted(true, null));
actions.Enqueue(() => builder.PushRecord(new object[] {2}));
actions.Enqueue(() => builder.PullCompleted(true, null));
actions.Enqueue(() => builder.PushRecord(new object[] {3}));
actions.Enqueue(() => builder.PullCompleted(false, null));
var list = await builder.CreateCursor().ToListAsync(r => r[0].As<int>());
list.Should().BeEquivalentTo(1, 2, 3);
moreCallCount.Should().Be(3);
cancelCallCount.Should().Be(0);
}
[Fact]
public async Task ShouldCallCancelAndReturnNoRecords()
{
var actions = new Queue<Action>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions),
MoreFunction(), CancelFunction(), null, reactive: true);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PullCompleted(false, null));
var cursor = builder.CreateCursor();
var keys = await cursor.KeysAsync();
keys.Should().BeEquivalentTo("a");
cursor.Cancel();
var list = await cursor.ToListAsync(r => r[0].As<int>());
list.Should().BeEmpty();
moreCallCount.Should().Be(0);
cancelCallCount.Should().Be(1);
}
[Fact]
public async Task ShouldReturnFirstBatchOfRecordsAndCancel()
{
var actions = new Queue<Action>();
var builder =
new ResultCursorBuilder(CreateSummaryBuilder(), CreateTaskQueue(actions),
MoreFunction(), CancelFunction(), null, reactive: true);
actions.Enqueue(() => builder.RunCompleted(0, new[] {"a"}, null));
actions.Enqueue(() => builder.PushRecord(new object[] {1}));
actions.Enqueue(() => builder.PushRecord(new object[] {2}));
actions.Enqueue(() => builder.PullCompleted(true, null));
actions.Enqueue(() => builder.PullCompleted(false, null));
var cursor = builder.CreateCursor();
var keys = await cursor.KeysAsync();
keys.Should().BeEquivalentTo("a");
var hasRecord1 = await cursor.FetchAsync();
var record1 = cursor.Current;
hasRecord1.Should().BeTrue();
record1[0].Should().Be(1);
var hasRecord2 = await cursor.FetchAsync();
var record2 = cursor.Current;
hasRecord2.Should().BeTrue();
record2[0].Should().Be(2);
cursor.Cancel();
var list = await cursor.ToListAsync(r => r[0].As<int>());
list.Should().BeEmpty();
moreCallCount.Should().Be(1);
cancelCallCount.Should().Be(1);
}
private Func<IResultStreamBuilder, long, long, Task> MoreFunction()
{
return (cursorBuilder, id, n) =>
{
Interlocked.Increment(ref moreCallCount);
return Task.CompletedTask;
};
}
private Func<IResultStreamBuilder, long, Task> CancelFunction()
{
return (cursorBuilder, id) =>
{
Interlocked.Increment(ref cancelCallCount);
return Task.CompletedTask;
};
}
}
private static SummaryBuilder CreateSummaryBuilder()
{
return new SummaryBuilder(new Query("Fake"), Mock.Of<IServerInfo>());
}
private static Func<Task> CreateTaskQueue(Queue<Action> actions = null)
{
if (actions == null)
{
actions = new Queue<Action>();
}
return () =>
{
if (actions.TryDequeue(out var action))
{
action();
}
return Task.CompletedTask;
};
}
private static Func<IResultStreamBuilder, long, long, Task> CreateMoreTaskQueue(Queue<Action> actions)
{
return (b, id, n) =>
{
if (actions.TryDequeue(out var action))
{
action();
}
return Task.CompletedTask;
};
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.AspNet
{
public interface IEntityStore<TModel, TKey> : IDisposable
{
Task<TKey> CreateAsync(TModel model);
Task UpdateAsync(TModel model);
Task DeleteAsync(TModel model);
Task<TModel> FindByIdAsync(TKey id);
Task<TModel> FindByNameAsync(string name);
}
public class CrmEntityStoreSettings
{
public virtual bool DeleteByStatusCode { get; set; }
public virtual PortalSolutions PortalSolutions { get; set; }
}
public abstract class CrmEntityStore<TModel, TKey> : BaseStore
where TModel : CrmModel<TKey>, new()
where TKey : IEquatable<TKey>
{
protected virtual CrmEntityStoreSettings Settings { get; private set; }
protected virtual string LogicalName { get; private set; }
protected virtual string PrimaryIdAttribute { get; private set; }
protected virtual string PrimaryNameAttribute { get; private set; }
protected virtual Version BaseSolutionCrmVersion { get; private set; }
protected CrmEntityStore(string logicalName, string primaryIdAttribute, string primaryNameAttribute, CrmDbContext context, CrmEntityStoreSettings settings)
: base(context)
{
if (string.IsNullOrWhiteSpace(logicalName)) throw new ArgumentNullException("logicalName");
if (string.IsNullOrWhiteSpace(primaryIdAttribute)) throw new ArgumentNullException("primaryIdAttribute");
if (string.IsNullOrWhiteSpace(primaryNameAttribute)) throw new ArgumentNullException("primaryNameAttribute");
if (context == null) throw new ArgumentNullException("context");
LogicalName = logicalName;
PrimaryIdAttribute = primaryIdAttribute;
PrimaryNameAttribute = primaryNameAttribute;
Settings = settings;
BaseSolutionCrmVersion = settings.PortalSolutions != null
? settings.PortalSolutions.BaseSolutionCrmVersion
: null;
}
#region IEntityStore
public virtual Task<TKey> CreateAsync(TModel model)
{
ThrowIfDisposed();
if (model == null) throw new ArgumentNullException("model");
var entity = ToEntity(model);
var id = Context.Service.Create(entity);
return Task.FromResult(ToKey(id));
}
public virtual async Task UpdateAsync(TModel model)
{
ThrowIfDisposed();
if (model == null) throw new ArgumentNullException("model");
var entity = ToEntity(model);
var snapshot = await FetchByIdAsync(entity.ToEntityReference()).WithCurrentCulture();
Execute(ToUpdateRequests(entity, snapshot));
}
public virtual Task DeleteAsync(TModel model)
{
ThrowIfDisposed();
if (model == null) throw new ArgumentNullException("model");
Execute(ToDeleteRequests(model));
return Task.FromResult(model);
}
public virtual Task<TModel> FindByIdAsync(TKey id)
{
ThrowIfDisposed();
if (ToGuid(id) == Guid.Empty) throw new ArgumentException("Invalid ID.");
return FindByConditionAsync(new Condition(PrimaryIdAttribute, ConditionOperator.Equal, id));
}
public virtual Task<TModel> FindByNameAsync(string name)
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Invalid name.");
return FindByConditionAsync(new Condition(PrimaryNameAttribute, ConditionOperator.Equal, name));
}
protected abstract RetrieveRequest ToRetrieveRequest(EntityReference id);
protected virtual Entity ToEntity(TModel model)
{
return model.Entity;
}
protected virtual TModel ToModel(Entity entity)
{
if (entity == null) return null;
var model = new TModel();
model.SetEntity(entity);
return model;
}
protected virtual IEnumerable<OrganizationRequest> ToUpdateRequests(Entity entity, Entity snapshot)
{
var changedEntity = entity.ToChangedEntity(snapshot);
var removedEntities = entity.ToRemovedEntities(snapshot);
// update the local identity entity graph
if (changedEntity != null)
{
yield return new UpdateRequest { Target = changedEntity };
}
// delete removed child entities
foreach (var removedEntity in removedEntities)
{
yield return new DeleteRequest { Target = removedEntity.ToEntityReference() };
}
}
protected virtual IEnumerable<OrganizationRequest> ToDeleteRequests(TModel model)
{
if (Settings.DeleteByStatusCode)
{
yield return GetDeactivateRequest(new EntityReference(LogicalName, ToGuid(model.Id)));
}
else
{
yield return new DeleteRequest { Target = new EntityReference(LogicalName, ToGuid(model.Id)) };
}
}
protected virtual async Task<TModel> FindByConditionAsync(Condition condition)
{
var entity = await FetchByConditionAsync(condition).WithCurrentCulture();
return ToModel(entity);
}
protected virtual Task<Entity> FetchByConditionAsync(params Condition[] conditions)
{
// fetch the local identity by a condition
var fetch = new Fetch
{
Entity = new FetchEntity(LogicalName)
{
Attributes = FetchAttribute.None,
Filters = new[] { new Filter {
Conditions = GetActiveEntityConditions().Concat(conditions).ToArray()
} }
}
};
return FetchAsync(fetch);
}
protected virtual async Task<TModel> FindByIdAsync(EntityReference id)
{
var entity = await FetchByIdAsync(id).WithCurrentCulture();
return ToModel(entity);
}
protected virtual Task<Entity> FetchByIdAsync(EntityReference id)
{
var request = this.ToRetrieveRequest(id);
var response = this.Context.Service.Execute(request) as RetrieveResponse;
return Task.FromResult(response.Entity);
}
protected virtual Guid ToGuid(TKey key)
{
return ToGuid<TKey>(key);
}
protected virtual TKey ToKey(Guid guid)
{
return ToKey<TKey>(guid);
}
protected virtual async Task<Entity> FetchAsync(Fetch fetch)
{
// fetch a lightweight entity
var entity = await FetchSingleOrDefaultAsync(fetch).WithCurrentCulture();
// expand to the full entity by ID
return entity != null
? await FetchByIdAsync(entity.ToEntityReference()).WithCurrentCulture()
: null;
}
protected virtual OrganizationRequest GetDeactivateRequest(EntityReference entity)
{
return new OrganizationRequest("SetState")
{
Parameters = new ParameterCollection
{
{ "EntityMoniker", entity },
{ "State", new OptionSetValue(1) },
{ "Status", new OptionSetValue(2) },
}
};
}
protected virtual IEnumerable<Condition> GetActiveEntityConditions()
{
return GetActiveStateConditions();
}
protected virtual IEnumerable<Condition> GetActiveStateConditions()
{
yield return EntityExtensions.ActiveStateCondition;
}
protected void MergeRelatedEntities(ICollection<Entity> parents, Relationship relationship, string relatedLogicalName, ColumnSet relatedColumns)
{
if (parents == null || parents.Count == 0)
{
return;
}
var parentIds = parents.Select(parent => parent.Id).Cast<object>().ToList();
var parentIdsCondition = new[] { new Condition { Attribute = PrimaryIdAttribute, Operator = ConditionOperator.In, Values = parentIds } };
var fetchRelatedEntities = new Fetch
{
Entity = new FetchEntity(relatedLogicalName, relatedColumns.Columns)
{
Filters = new[] { new Filter {
Conditions = GetActiveStateConditions().Concat(parentIdsCondition).ToList()
} }
}
};
var relatedEntities = Context.Service.RetrieveMultiple(fetchRelatedEntities);
foreach (var parent in parents)
{
var parentId = parent.ToEntityReference();
var relatedSubset = relatedEntities.Entities.Where(binding => Equals(binding.GetAttributeValue<EntityReference>(PrimaryIdAttribute), parentId));
parent.RelatedEntities[relationship] = new EntityCollection(relatedSubset.ToList());
}
}
private void Execute(IEnumerable<OrganizationRequest> requests)
{
// the current OrganizationServiceCache implementation does not support ExecuteMultiple
//Context.Service.ExecuteMultiple(requests);
foreach (var request in requests)
{
Context.Service.Execute(request);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NServiceKit.Redis;
using NServiceKit.Redis.Generic;
namespace NServiceKit.ServiceInterface.Auth
{
/// <summary>Interface for redis client manager facade.</summary>
public interface IRedisClientManagerFacade : IClearable
{
/// <summary>Gets the client.</summary>
///
/// <returns>The client.</returns>
IRedisClientFacade GetClient();
}
/// <summary>Interface for clearable.</summary>
public interface IClearable
{
/// <summary>Clears this object to its blank/initial state.</summary>
void Clear();
}
/// <summary>Interface for redis client facade.</summary>
public interface IRedisClientFacade : IDisposable
{
/// <summary>Gets all items from set.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>all items from set.</returns>
HashSet<string> GetAllItemsFromSet(string setId);
/// <summary>Stores the given item.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="item">The item.</param>
void Store<T>(T item) where T : class, new();
/// <summary>Gets value from hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
///
/// <returns>The value from hash.</returns>
string GetValueFromHash(string hashId, string key);
/// <summary>Sets entry in hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="value"> The value.</param>
void SetEntryInHash(string hashId, string key, string value);
/// <summary>Removes the entry from hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
void RemoveEntryFromHash(string hashId, string key);
/// <summary>Adds an item to set to 'item'.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="item"> The item.</param>
void AddItemToSet(string setId, string item);
/// <summary>Gets as.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>An ITypedRedisClientFacade<T></returns>
ITypedRedisClientFacade<T> As<T>();
}
/// <summary>Interface for typed redis client facade.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
public interface ITypedRedisClientFacade<T>
{
/// <summary>Gets the next sequence.</summary>
///
/// <returns>The next sequence.</returns>
int GetNextSequence();
/// <summary>Gets by identifier.</summary>
///
/// <param name="id">The identifier.</param>
///
/// <returns>The by identifier.</returns>
T GetById(object id);
/// <summary>Gets by identifiers.</summary>
///
/// <param name="ids">The identifiers.</param>
///
/// <returns>The by identifiers.</returns>
List<T> GetByIds(IEnumerable ids);
}
/// <summary>The redis client manager facade.</summary>
public class RedisClientManagerFacade : IRedisClientManagerFacade
{
private readonly IRedisClientsManager redisManager;
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.RedisClientManagerFacade class.</summary>
///
/// <param name="redisManager">Manager for redis.</param>
public RedisClientManagerFacade(IRedisClientsManager redisManager)
{
this.redisManager = redisManager;
}
/// <summary>Gets the client.</summary>
///
/// <returns>The client.</returns>
public IRedisClientFacade GetClient()
{
return new RedisClientFacade(redisManager.GetClient());
}
/// <summary>Clears this object to its blank/initial state.</summary>
public void Clear()
{
using (var redis = redisManager.GetClient())
redis.FlushAll();
}
private class RedisClientFacade : IRedisClientFacade
{
private readonly IRedisClient redisClient;
class RedisITypedRedisClientFacade<T> : ITypedRedisClientFacade<T>
{
private readonly IRedisTypedClient<T> redisTypedClient;
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.RedisClientManagerFacade.RedisClientFacade.RedisITypedRedisClientFacade<T> class.</summary>
///
/// <param name="redisTypedClient">The redis typed client.</param>
public RedisITypedRedisClientFacade(IRedisTypedClient<T> redisTypedClient)
{
this.redisTypedClient = redisTypedClient;
}
/// <summary>Gets the next sequence.</summary>
///
/// <returns>The next sequence.</returns>
public int GetNextSequence()
{
return (int) redisTypedClient.GetNextSequence();
}
/// <summary>Gets by identifier.</summary>
///
/// <param name="id">The identifier.</param>
///
/// <returns>The by identifier.</returns>
public T GetById(object id)
{
return redisTypedClient.GetById(id);
}
/// <summary>Gets by identifiers.</summary>
///
/// <param name="ids">The identifiers.</param>
///
/// <returns>The by identifiers.</returns>
public List<T> GetByIds(IEnumerable ids)
{
return redisTypedClient.GetByIds(ids).ToList();
}
}
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.RedisClientManagerFacade.RedisClientFacade class.</summary>
///
/// <param name="redisClient">The redis client.</param>
public RedisClientFacade(IRedisClient redisClient)
{
this.redisClient = redisClient;
}
/// <summary>Gets all items from set.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>all items from set.</returns>
public HashSet<string> GetAllItemsFromSet(string setId)
{
return redisClient.GetAllItemsFromSet(setId);
}
/// <summary>Stores the given item.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="item">The item.</param>
public void Store<T>(T item) where T : class , new()
{
redisClient.Store(item);
}
/// <summary>Gets value from hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
///
/// <returns>The value from hash.</returns>
public string GetValueFromHash(string hashId, string key)
{
return redisClient.GetValueFromHash(hashId, key);
}
/// <summary>Sets entry in hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="value"> The value.</param>
public void SetEntryInHash(string hashId, string key, string value)
{
redisClient.SetEntryInHash(hashId, key, value);
}
/// <summary>Removes the entry from hash.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
public void RemoveEntryFromHash(string hashId, string key)
{
redisClient.RemoveEntryFromHash(hashId, key);
}
/// <summary>Adds an item to set to 'item'.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="item"> The item.</param>
public void AddItemToSet(string setId, string item)
{
redisClient.AddItemToSet(setId, item);
}
/// <summary>Gets as.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>An ITypedRedisClientFacade<T></returns>
public ITypedRedisClientFacade<T> As<T>()
{
return new RedisITypedRedisClientFacade<T>(redisClient.As<T>());
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
this.redisClient.Dispose();
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary.Metadata
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary metadata implementation.
/// </summary>
internal class BinaryType : IBinaryType
{
/** Empty metadata. */
public static readonly BinaryType Empty =
new BinaryType(BinaryTypeId.Object, BinaryTypeNames.TypeNameObject, null, null, false, null, null, null);
/** Empty dictionary. */
private static readonly IDictionary<string, BinaryField> EmptyDict = new Dictionary<string, BinaryField>();
/** Empty list. */
private static readonly ICollection<string> EmptyList = new List<string>().AsReadOnly();
/** Type name map. */
private static readonly string[] TypeNames = new string[byte.MaxValue];
/** Fields. */
private readonly IDictionary<string, BinaryField> _fields;
/** Enum values. */
private readonly IDictionary<string, int> _enumNameToValue;
/** Enum names. */
private readonly IDictionary<int, string> _enumValueToName;
/** Enum flag. */
private readonly bool _isEnum;
/** Type id. */
private readonly int _typeId;
/** Type name. */
private readonly string _typeName;
/** Aff key field name. */
private readonly string _affinityKeyFieldName;
/** Type descriptor. */
private readonly IBinaryTypeDescriptor _descriptor;
/** Marshaller. */
private readonly Marshaller _marshaller;
/** Schema. */
private readonly BinaryObjectSchema _schema = new BinaryObjectSchema();
/// <summary>
/// Initializes the <see cref="BinaryType"/> class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability.")]
static BinaryType()
{
TypeNames[BinaryTypeId.Bool] = BinaryTypeNames.TypeNameBool;
TypeNames[BinaryTypeId.Byte] = BinaryTypeNames.TypeNameByte;
TypeNames[BinaryTypeId.Short] = BinaryTypeNames.TypeNameShort;
TypeNames[BinaryTypeId.Char] = BinaryTypeNames.TypeNameChar;
TypeNames[BinaryTypeId.Int] = BinaryTypeNames.TypeNameInt;
TypeNames[BinaryTypeId.Long] = BinaryTypeNames.TypeNameLong;
TypeNames[BinaryTypeId.Float] = BinaryTypeNames.TypeNameFloat;
TypeNames[BinaryTypeId.Double] = BinaryTypeNames.TypeNameDouble;
TypeNames[BinaryTypeId.Decimal] = BinaryTypeNames.TypeNameDecimal;
TypeNames[BinaryTypeId.String] = BinaryTypeNames.TypeNameString;
TypeNames[BinaryTypeId.Guid] = BinaryTypeNames.TypeNameGuid;
TypeNames[BinaryTypeId.Timestamp] = BinaryTypeNames.TypeNameTimestamp;
TypeNames[BinaryTypeId.Enum] = BinaryTypeNames.TypeNameEnum;
TypeNames[BinaryTypeId.Object] = BinaryTypeNames.TypeNameObject;
TypeNames[BinaryTypeId.ArrayBool] = BinaryTypeNames.TypeNameArrayBool;
TypeNames[BinaryTypeId.ArrayByte] = BinaryTypeNames.TypeNameArrayByte;
TypeNames[BinaryTypeId.ArrayShort] = BinaryTypeNames.TypeNameArrayShort;
TypeNames[BinaryTypeId.ArrayChar] = BinaryTypeNames.TypeNameArrayChar;
TypeNames[BinaryTypeId.ArrayInt] = BinaryTypeNames.TypeNameArrayInt;
TypeNames[BinaryTypeId.ArrayLong] = BinaryTypeNames.TypeNameArrayLong;
TypeNames[BinaryTypeId.ArrayFloat] = BinaryTypeNames.TypeNameArrayFloat;
TypeNames[BinaryTypeId.ArrayDouble] = BinaryTypeNames.TypeNameArrayDouble;
TypeNames[BinaryTypeId.ArrayDecimal] = BinaryTypeNames.TypeNameArrayDecimal;
TypeNames[BinaryTypeId.ArrayString] = BinaryTypeNames.TypeNameArrayString;
TypeNames[BinaryTypeId.ArrayGuid] = BinaryTypeNames.TypeNameArrayGuid;
TypeNames[BinaryTypeId.ArrayTimestamp] = BinaryTypeNames.TypeNameArrayTimestamp;
TypeNames[BinaryTypeId.ArrayEnum] = BinaryTypeNames.TypeNameArrayEnum;
TypeNames[BinaryTypeId.Array] = BinaryTypeNames.TypeNameArrayObject;
TypeNames[BinaryTypeId.Collection] = BinaryTypeNames.TypeNameCollection;
TypeNames[BinaryTypeId.Dictionary] = BinaryTypeNames.TypeNameMap;
}
/// <summary>
/// Get type name by type ID.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <returns>Type name.</returns>
private static string GetTypeName(int typeId)
{
var typeName = (typeId >= 0 && typeId < TypeNames.Length) ? TypeNames[typeId] : null;
if (typeName != null)
return typeName;
throw new BinaryObjectException("Invalid type ID: " + typeId);
}
/// <summary>
/// Initializes a new instance of the <see cref="BinaryType" /> class.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="readSchemas">Whether to read schemas.</param>
public BinaryType(BinaryReader reader, bool readSchemas = false)
{
_typeId = reader.ReadInt();
_typeName = reader.ReadString();
_affinityKeyFieldName = reader.ReadString();
int fieldsNum = reader.ReadInt();
_fields = new Dictionary<string, BinaryField>(fieldsNum);
for (int i = 0; i < fieldsNum; ++i)
{
string name = reader.ReadString();
BinaryField field = new BinaryField(reader);
_fields[name] = field;
}
_isEnum = reader.ReadBoolean();
if (_isEnum)
{
var count = reader.ReadInt();
_enumNameToValue = new Dictionary<string, int>(count);
for (var i = 0; i < count; i++)
{
_enumNameToValue[reader.ReadString()] = reader.ReadInt();
}
_enumValueToName = _enumNameToValue.ToDictionary(x => x.Value, x => x.Key);
}
if (readSchemas)
{
var cnt = reader.ReadInt();
for (var i = 0; i < cnt; i++)
{
var schemaId = reader.ReadInt();
var ids = new int[reader.ReadInt()];
for (var j = 0; j < ids.Length; j++)
{
ids[j] = reader.ReadInt();
}
_schema.Add(schemaId, ids);
}
}
_marshaller = reader.Marshaller;
}
/// <summary>
/// Initializes a new instance of the <see cref="BinaryType" /> class.
/// </summary>
/// <param name="desc">Descriptor.</param>
/// <param name="marshaller">Marshaller.</param>
/// <param name="fields">Fields.</param>
public BinaryType(IBinaryTypeDescriptor desc, Marshaller marshaller,
IDictionary<string, BinaryField> fields = null)
: this (desc.TypeId, desc.TypeName, fields, desc.AffinityKeyFieldName, desc.IsEnum,
GetEnumValues(desc), marshaller, null)
{
_descriptor = desc;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <param name="typeName">Type name.</param>
/// <param name="fields">Fields.</param>
/// <param name="affKeyFieldName">Affinity key field name.</param>
/// <param name="isEnum">Enum flag.</param>
/// <param name="enumValues">Enum values.</param>
/// <param name="marshaller">Marshaller.</param>
/// <param name="schema"></param>
public BinaryType(int typeId, string typeName, IDictionary<string, BinaryField> fields,
string affKeyFieldName, bool isEnum, IDictionary<string, int> enumValues, Marshaller marshaller,
BinaryObjectSchema schema)
{
_typeId = typeId;
_typeName = typeName;
_affinityKeyFieldName = affKeyFieldName;
_fields = fields;
_isEnum = isEnum;
_enumNameToValue = enumValues;
if (_enumNameToValue != null)
{
_enumValueToName = _enumNameToValue.ToDictionary(x => x.Value, x => x.Key);
}
_marshaller = marshaller;
_schema = schema;
}
/// <summary>
/// Type ID.
/// </summary>
/// <returns></returns>
public int TypeId
{
get { return _typeId; }
}
/// <summary>
/// Gets type name.
/// </summary>
public string TypeName
{
get { return _typeName; }
}
/// <summary>
/// Gets field names for that type.
/// </summary>
public ICollection<string> Fields
{
get { return _fields != null ? _fields.Keys : EmptyList; }
}
/// <summary>
/// Gets field type for the given field name.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <returns>
/// Field type.
/// </returns>
public string GetFieldTypeName(string fieldName)
{
IgniteArgumentCheck.NotNullOrEmpty(fieldName, "fieldName");
if (_fields != null)
{
BinaryField fieldMeta;
if (!_fields.TryGetValue(fieldName, out fieldMeta))
{
throw new BinaryObjectException("BinaryObject field does not exist: " + fieldName);
}
return GetTypeName(fieldMeta.TypeId);
}
return null;
}
/// <summary>
/// Gets optional affinity key field name.
/// </summary>
public string AffinityKeyFieldName
{
get { return _affinityKeyFieldName; }
}
/** <inheritdoc /> */
public bool IsEnum
{
get { return _isEnum; }
}
/** <inheritdoc /> */
public IEnumerable<IBinaryObject> GetEnumValues()
{
if (!_isEnum)
{
throw new NotSupportedException(
"IBinaryObject.Value is only supported for enums. " +
"Check IBinaryObject.GetBinaryType().IsEnum property before accessing Value.");
}
if (_marshaller == null)
{
yield break;
}
foreach (var pair in _enumValueToName)
{
yield return new BinaryEnum(_typeId, pair.Key, _marshaller);
}
}
/// <summary>
/// Gets the descriptor.
/// </summary>
public IBinaryTypeDescriptor Descriptor
{
get { return _descriptor; }
}
/// <summary>
/// Gets fields map.
/// </summary>
/// <returns>Fields map.</returns>
public IDictionary<string, BinaryField> GetFieldsMap()
{
return _fields ?? EmptyDict;
}
/// <summary>
/// Gets the enum values map.
/// </summary>
public IDictionary<string, int> EnumValuesMap
{
get { return _enumNameToValue; }
}
/// <summary>
/// Gets the schema.
/// </summary>
public BinaryObjectSchema Schema
{
get { return _schema; }
}
/// <summary>
/// Updates the fields.
/// </summary>
public void UpdateFields(IDictionary<string, BinaryField> fields)
{
if (fields == null || fields.Count == 0)
return;
Debug.Assert(_fields != null);
foreach (var field in fields)
_fields[field.Key] = field.Value;
}
/// <summary>
/// Gets the enum value by name.
/// </summary>
public int? GetEnumValue(string valueName)
{
IgniteArgumentCheck.NotNullOrEmpty(valueName, "valueName");
if (!_isEnum)
{
throw new NotSupportedException("Can't get enum value for a non-enum type: " + _typeName);
}
int res;
return _enumNameToValue != null && _enumNameToValue.TryGetValue(valueName, out res) ? res : (int?) null;
}
/// <summary>
/// Gets the name of the enum value.
/// </summary>
public string GetEnumName(int value)
{
if (!_isEnum)
{
throw new NotSupportedException("Can't get enum value for a non-enum type: " + _typeName);
}
string res;
return _enumValueToName != null && _enumValueToName.TryGetValue(value, out res) ? res : null;
}
/// <summary>
/// Gets the enum values.
/// </summary>
private static IDictionary<string, int> GetEnumValues(IBinaryTypeDescriptor desc)
{
if (desc == null || desc.Type == null || !desc.IsEnum)
{
return null;
}
var enumType = desc.Type;
var values = Enum.GetValues(enumType);
var res = new Dictionary<string, int>(values.Length);
var underlyingType = Enum.GetUnderlyingType(enumType);
foreach (var value in values)
{
var name = Enum.GetName(enumType, value);
Debug.Assert(name != null);
res[name] = GetEnumValueAsInt(underlyingType, value);
}
return res;
}
/// <summary>
/// Gets the enum value as int.
/// </summary>
private static int GetEnumValueAsInt(Type underlyingType, object value)
{
if (underlyingType == typeof(int))
{
return (int) value;
}
if (underlyingType == typeof(byte))
{
return (byte) value;
}
if (underlyingType == typeof(sbyte))
{
return (sbyte) value;
}
if (underlyingType == typeof(short))
{
return (short) value;
}
if (underlyingType == typeof(ushort))
{
return (ushort) value;
}
if (underlyingType == typeof(uint))
{
return unchecked((int) (uint) value);
}
throw new BinaryObjectException("Unexpected enum underlying type: " + underlyingType);
}
}
}
| |
// 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.Threading;
namespace Internal.TypeSystem
{
/// <summary>
/// Represents an array type - either a multidimensional array, or a vector
/// (a one-dimensional array with a zero lower bound).
/// </summary>
public sealed partial class ArrayType : ParameterizedType
{
private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays
internal ArrayType(TypeDesc elementType, int rank)
: base(elementType)
{
_rank = rank;
}
public override int GetHashCode()
{
// ComputeArrayTypeHashCode expects -1 for an SzArray
return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank);
}
public override DefType BaseType
{
get
{
return this.Context.GetWellKnownType(WellKnownType.Array);
}
}
/// <summary>
/// Gets the type of the element of this array.
/// </summary>
public TypeDesc ElementType
{
get
{
return this.ParameterType;
}
}
internal MethodDesc[] _methods;
/// <summary>
/// Gets a value indicating whether this type is a vector.
/// </summary>
public new bool IsSzArray
{
get
{
return _rank < 0;
}
}
/// <summary>
/// Gets a value indicating whether this type is an mdarray.
/// </summary>
public new bool IsMdArray
{
get
{
return _rank > 0;
}
}
/// <summary>
/// Gets the rank of this array. Note this returns "1" for both vectors, and
/// for general arrays of rank 1. Use <see cref="IsSzArray"/> to disambiguate.
/// </summary>
public int Rank
{
get
{
return (_rank < 0) ? 1 : _rank;
}
}
private void InitializeMethods()
{
int numCtors;
if (IsSzArray)
{
numCtors = 1;
// Jagged arrays have constructor for each possible depth
var t = this.ElementType;
while (t.IsSzArray)
{
t = ((ArrayType)t).ElementType;
numCtors++;
}
}
else
{
// Multidimensional arrays have two ctors, one with and one without lower bounds
numCtors = 2;
}
MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors];
for (int i = 0; i < methods.Length; i++)
methods[i] = new ArrayMethod(this, (ArrayMethodKind)i);
Interlocked.CompareExchange(ref _methods, methods, null);
}
public override IEnumerable<MethodDesc> GetMethods()
{
if (_methods == null)
InitializeMethods();
return _methods;
}
public MethodDesc GetArrayMethod(ArrayMethodKind kind)
{
if (_methods == null)
InitializeMethods();
return _methods[(int)kind];
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc elementType = this.ElementType;
TypeDesc instantiatedElementType = elementType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (instantiatedElementType != elementType)
return Context.GetArrayType(instantiatedElementType, _rank);
return this;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array;
flags |= TypeFlags.HasGenericVarianceComputed;
flags |= TypeFlags.HasFinalizerComputed;
flags |= TypeFlags.AttributeCacheComputed;
return flags;
}
}
public enum ArrayMethodKind
{
Get,
Set,
Address,
AddressWithHiddenArg,
Ctor
}
/// <summary>
/// Represents one of the methods on array types. While array types are not typical
/// classes backed by metadata, they do have methods that can be referenced from the IL
/// and the type system needs to provide a way to represent them.
/// </summary>
/// <remarks>
/// There are two array Address methods (<see cref="ArrayMethodKind.Address"/> and
/// <see cref="ArrayMethodKind.AddressWithHiddenArg"/>). One is used when referencing Address
/// method from IL, the other is used when *compiling* the method body.
/// The reason we need to do this is that the Address method is required to do a type check using a type
/// that is only known at the callsite. The trick we use is that we tell codegen that the
/// <see cref="ArrayMethodKind.Address"/> method requires a hidden instantiation parameter (even though it doesn't).
/// The instantiation parameter is where we capture the type at the callsite.
/// When we compile the method body, we compile it as <see cref="ArrayMethodKind.AddressWithHiddenArg"/> that
/// has the hidden argument explicitly listed in it's signature and is available as a regular parameter.
/// </remarks>
public sealed partial class ArrayMethod : MethodDesc
{
private ArrayType _owningType;
private ArrayMethodKind _kind;
internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind)
{
_owningType = owningType;
_kind = kind;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
public ArrayType OwningArray
{
get
{
return _owningType;
}
}
public ArrayMethodKind Kind
{
get
{
return _kind;
}
}
private MethodSignature _signature;
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
switch (_kind)
{
case ArrayMethodKind.Get:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType, parameters);
break;
}
case ArrayMethodKind.Set:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
parameters[_owningType.Rank] = _owningType.ElementType;
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters);
break;
}
case ArrayMethodKind.Address:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
case ArrayMethodKind.AddressWithHiddenArg:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
parameters[0] = Context.SystemModule.GetType("System", "EETypePtr");
for (int i = 0; i < _owningType.Rank; i++)
parameters[i + 1] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
default:
{
int numArgs;
if (_owningType.IsSzArray)
{
numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor;
}
else
{
numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank;
}
var argTypes = new TypeDesc[numArgs];
for (int i = 0; i < argTypes.Length; i++)
argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes);
}
break;
}
}
return _signature;
}
}
public override string Name
{
get
{
switch (_kind)
{
case ArrayMethodKind.Get:
return "Get";
case ArrayMethodKind.Set:
return "Set";
case ArrayMethodKind.Address:
case ArrayMethodKind.AddressWithHiddenArg:
return "Address";
default:
return ".ctor";
}
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc owningType = this.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind);
else
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewRelic.Microsoft.SqlServer.Plugin.Configuration;
using NewRelic.Microsoft.SqlServer.Plugin.Properties;
using NewRelic.Microsoft.SqlServer.Plugin.QueryTypes;
using NSubstitute;
using NUnit.Framework;
namespace NewRelic.Microsoft.SqlServer.Plugin
{
[TestFixture]
public class SqlEndpointTests
{
public IEnumerable<TestCaseData> ComponentGuidTestCases
{
get
{
yield return new TestCaseData(new SqlServerEndpoint("FooServer", ".", false)).Returns(Constants.SqlServerComponentGuid).SetName("SqlServer Sets Appropriate Guid");
yield return new TestCaseData(new AzureSqlEndpoint("FooServer", "")).Returns(Constants.SqlAzureComponentGuid).SetName("AzureSqlEndpoint Sets Appropriate Guid");
}
}
[Test]
public void Assert_endpoint_appropriately_massages_duplicated_data()
{
var endpoint = Substitute.For<SqlEndpointBase>("", "");
var resultSet1 = new object[]
{
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
ExecutionCount = 10,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO BAR"),
ExecutionCount = 8,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO BAR"),
ExecutionCount = 8,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("BB12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 500,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("CC12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 600,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("EE12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM BAR"),
ExecutionCount = 100,
QueryType = "Reads",
},
};
IEnumerable<SqlDmlActivity> outputResults1 = endpoint.CalculateSqlDmlActivityIncrease(resultSet1).Cast<SqlDmlActivity>().ToArray();
Assert.That(outputResults1, Is.Not.Null);
Assert.That(outputResults1.Count(), Is.EqualTo(1));
SqlDmlActivity sqlDmlActivity = outputResults1.First();
Assert.That(string.Format("Reads:{0} Writes:{1}", sqlDmlActivity.Reads, sqlDmlActivity.Writes), Is.EqualTo("Reads:0 Writes:0"));
}
[Test]
[TestCaseSource("ComponentGuidTestCases")]
public string Assert_correct_component_guid_supplied_to_query_context(SqlEndpointBase endpoint)
{
QueryContext queryContext = endpoint.CreateQueryContext(Substitute.For<ISqlQuery>(), new object[0]);
return queryContext.ComponentGuid;
}
[Test]
public void Assert_endpoint_appropriately_massages_data()
{
var endpoint = Substitute.For<SqlEndpointBase>("", "");
var resultSet1 = new object[]
{
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
ExecutionCount = 10,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO BAR"),
ExecutionCount = 8,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("BB12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 500,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("CC12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 600,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("EE12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM BAR"),
ExecutionCount = 100,
QueryType = "Reads",
},
};
IEnumerable<SqlDmlActivity> outputResults1 = endpoint.CalculateSqlDmlActivityIncrease(resultSet1).Cast<SqlDmlActivity>().ToArray();
Assert.That(outputResults1, Is.Not.Null);
Assert.That(outputResults1.Count(), Is.EqualTo(1));
SqlDmlActivity sqlDmlActivity = outputResults1.First();
Assert.That(string.Format("Reads:{0} Writes:{1}", sqlDmlActivity.Reads, sqlDmlActivity.Writes), Is.EqualTo("Reads:0 Writes:0"));
var resultSet2 = new object[]
{
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
ExecutionCount = 14,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO BAR"),
ExecutionCount = 18,
QueryType = "Writes",
},
//Tests Duplicate Results gets aggregated
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO BAR"),
ExecutionCount = 2,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("BB12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 550,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("CC12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM FOO"),
ExecutionCount = 625,
QueryType = "Reads",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("DD12"),
SqlStatementHash = Encoding.UTF8.GetBytes("SELECT * FROM BAR"),
ExecutionCount = 1,
QueryType = "Reads",
},
};
SqlDmlActivity[] outputResults2 = endpoint.CalculateSqlDmlActivityIncrease(resultSet2).Cast<SqlDmlActivity>().ToArray();
Assert.That(outputResults2, Is.Not.Null);
Assert.That(outputResults2.Count(), Is.EqualTo(1));
sqlDmlActivity = outputResults2.First();
Assert.That(string.Format("Reads:{0} Writes:{1}", sqlDmlActivity.Reads, sqlDmlActivity.Writes), Is.EqualTo("Reads:76 Writes:16"));
}
[Test]
public void Assert_sql_dml_actvity_data_takes_create_time_ms_into_account()
{
var endpoint = Substitute.For<SqlEndpointBase>("", "");
var d1 = new DateTime(2013, 06, 20, 8, 28, 10, 100);
var d2 = new DateTime(2013, 06, 20, 8, 28, 10, 200);
var resultSet1 = new object[]
{
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
CreationTime = d1,
ExecutionCount = 10,
QueryType = "Writes",
},
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
CreationTime = d2,
ExecutionCount = 12,
QueryType = "Writes",
},
};
IEnumerable<SqlDmlActivity> outputResults1 = endpoint.CalculateSqlDmlActivityIncrease(resultSet1).Cast<SqlDmlActivity>().ToArray();
Assert.That(outputResults1, Is.Not.Null);
Assert.That(outputResults1.Count(), Is.EqualTo(1));
SqlDmlActivity sqlDmlActivity = outputResults1.First();
Assert.That(string.Format("Reads:{0} Writes:{1}", sqlDmlActivity.Reads, sqlDmlActivity.Writes), Is.EqualTo("Reads:0 Writes:0"));
var resultSet2 = new object[]
{
new SqlDmlActivity
{
PlanHandle = Encoding.UTF8.GetBytes("AA11"),
SqlStatementHash = Encoding.UTF8.GetBytes("INSERT INTO FOO"),
CreationTime = d2,
ExecutionCount = 15,
QueryType = "Writes",
},
};
SqlDmlActivity[] outputResults2 = endpoint.CalculateSqlDmlActivityIncrease(resultSet2).Cast<SqlDmlActivity>().ToArray();
Assert.That(outputResults2, Is.Not.Null);
Assert.That(outputResults2.Count(), Is.EqualTo(1));
sqlDmlActivity = outputResults2.First();
Assert.That(string.Format("Reads:{0} Writes:{1}", sqlDmlActivity.Reads, sqlDmlActivity.Writes), Is.EqualTo("Reads:0 Writes:3"));
}
[Test]
public void Assert_database_names_are_replaced_when_included_databases_with_display_names_are_configured()
{
var includedDatabases = new[]
{
new Database {Name = "Foo", DisplayName = "Fantastic",},
new Database {Name = "Bar", DisplayName = "Baracuda",},
new Database {Name = "Baz", DisplayName = "Assassins",},
new Database {Name = "Quux",},
};
var databaseMetric1 = Substitute.For<IDatabaseMetric>();
databaseMetric1.DatabaseName = "Foo";
// Test for case-insensitivity
var databaseMetric2 = Substitute.For<IDatabaseMetric>();
databaseMetric2.DatabaseName = "BAZ";
var databaseMetric3 = Substitute.For<IDatabaseMetric>();
databaseMetric3.DatabaseName = "Bar";
var databaseMetric4 = Substitute.For<IDatabaseMetric>();
databaseMetric4.DatabaseName = "Quux";
var results = new object[]
{
databaseMetric1,
databaseMetric2,
databaseMetric3,
databaseMetric4,
};
SqlServerEndpoint.ApplyDatabaseDisplayNames(includedDatabases, results);
Assert.That(databaseMetric1.DatabaseName, Is.EqualTo("Fantastic"));
Assert.That(databaseMetric2.DatabaseName, Is.EqualTo("Assassins"));
Assert.That(databaseMetric3.DatabaseName, Is.EqualTo("Baracuda"));
Assert.That(databaseMetric4.DatabaseName, Is.EqualTo("Quux"));
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Project.Automation
{
public class OAProperty : EnvDTE.Property
{
#region fields
private OAProperties parent;
private PropertyInfo pi;
#endregion
#region ctors
public OAProperty(OAProperties parent, PropertyInfo pi)
{
this.parent = parent;
this.pi = pi;
}
#endregion
#region EnvDTE.Property
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public object Application
{
get { return null; }
}
/// <summary>
/// Gets the Collection containing the Property object supporting this property.
/// </summary>
public EnvDTE.Properties Collection
{
get
{
//todo: EnvDTE.Property.Collection
return this.parent;
}
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public EnvDTE.DTE DTE
{
get
{
return this.parent.DTE;
}
}
/// <summary>
/// Returns one element of a list.
/// </summary>
/// <param name="index1">The index of the item to display.</param>
/// <param name="index2">The index of the item to display. Reserved for future use.</param>
/// <param name="index3">The index of the item to display. Reserved for future use.</param>
/// <param name="index4">The index of the item to display. Reserved for future use.</param>
/// <returns>The value of a property</returns>
public object get_IndexedValue(object index1, object index2, object index3, object index4)
{
ParameterInfo[] par = pi.GetIndexParameters();
int len = Math.Min(par.Length, 4);
if(len == 0) return this.Value;
object[] index = new object[len];
Array.Copy(new object[4] { index1, index2, index3, index4 }, index, len);
return this.pi.GetValue(this.parent.Target, index);
}
/// <summary>
/// Setter function to set properties values.
/// </summary>
/// <param name="value"></param>
public void let_Value(object value)
{
this.Value = value;
}
/// <summary>
/// Gets the name of the object.
/// </summary>
public string Name
{
get
{
return pi.Name;
}
}
/// <summary>
/// Gets the number of indices required to access the value.
/// </summary>
public short NumIndices
{
get { return (short)pi.GetIndexParameters().Length; }
}
/// <summary>
/// Sets or gets the object supporting the Property object.
/// </summary>
public object Object
{
get
{
return this.parent.Target;
}
set
{
}
}
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public EnvDTE.Properties Parent
{
get { return this.parent; }
}
/// <summary>
/// Sets the value of the property at the specified index.
/// </summary>
/// <param name="index1">The index of the item to set.</param>
/// <param name="index2">Reserved for future use.</param>
/// <param name="index3">Reserved for future use.</param>
/// <param name="index4">Reserved for future use.</param>
/// <param name="value">The value to set.</param>
public void set_IndexedValue(object index1, object index2, object index3, object index4, object value)
{
ParameterInfo[] par = pi.GetIndexParameters();
int len = Math.Min(par.Length, 4);
if(len == 0)
{
this.Value = value;
}
else
{
object[] index = new object[len];
Array.Copy(new object[4] { index1, index2, index3, index4 }, index, len);
using(AutomationScope scope = new AutomationScope(this.parent.Target.Node.ProjectMgr.Site))
{
this.pi.SetValue(this.parent.Target, value, index);
}
}
}
/// <summary>
/// Gets or sets the value of the property returned by the Property object.
/// </summary>
public object Value
{
get { return pi.GetValue(this.parent.Target, null); }
set
{
using(AutomationScope scope = new AutomationScope(this.parent.Target.Node.ProjectMgr.Site))
{
this.pi.SetValue(this.parent.Target, value, null);
}
}
}
#endregion
}
}
| |
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using CorePhotoInfo.Reporting;
using System.Collections.Generic;
using System;
using ImageSharp;
using ImageSharp.Formats;
using ImageSharp.Formats.Tiff;
namespace CorePhotoInfo.Tiff
{
public class TiffDump
{
private Stream _stream;
private TiffDecoderCore _tiffDecoder;
private IReportWriter _report;
private DirectoryInfo _outputDirectory;
private Dictionary<int, string> _tagDictionary = new Dictionary<int, string>();
private Dictionary<int, string> _exifTagDictionary = new Dictionary<int, string>();
private TiffDump(Stream stream, IReportWriter reportWriter, DirectoryInfo outputDirectory)
{
_stream = stream;
_report = reportWriter;
_outputDirectory = outputDirectory;
_tiffDecoder = new TiffDecoderCore(stream, false, null, null);
}
private void WriteTiffInfo()
{
uint firstIfdOffset = _tiffDecoder.ReadHeader();
_report.WriteSubheader("TiffHeader");
_report.WriteLine("Byte order : {0}", _tiffDecoder.IsLittleEndian ? "Little Endian" : "Big Endian");
WriteTiffIfdInfo(firstIfdOffset, "IFD ", 0, _tagDictionary);
}
private void WriteTiffIfdInfo(uint offset, string ifdPrefix, int? ifdId, Dictionary<int, string> tagDictionary)
{
TiffIfd ifd = _tiffDecoder.ReadIfd(offset);
_report.WriteSubheader($"{ifdPrefix}{ifdId} (Offset = {offset})");
// Write the IFD dump
WriteTiffIfdEntries(ifd, tagDictionary);
// Decode the image
DecodeImage(ifd, $"{ifdPrefix}{ifdId}");
// Write the EXIF IFD
// var exifIfdReference = ExifReader.GetExifIfdReference(ifd, byteOrder);
// if (exifIfdReference != null)
// {
// var exifIfd = await TiffReader.ReadIfdAsync(exifIfdReference.Value, _stream, byteOrder);
// await WriteTiffIfdInfoAsync(exifIfd, byteOrder, $"{ifdPrefix}{ifdId} (EXIF)", null, _exifTagDictionary);
// }
// Write the sub-IFDs
// var subIfdReferences = await TiffReader.ReadSubIfdReferencesAsync(ifd, _stream, byteOrder);
// for (int i = 0; i < subIfdReferences.Length; i++)
// {
// TiffIfd subIfd = await TiffReader.ReadIfdAsync(subIfdReferences[i], _stream, byteOrder);
// await WriteTiffIfdInfoAsync(subIfd, byteOrder, $"{ifdPrefix}{ifdId}-", i, _tagDictionary);
// }
// Write the next IFD
if (ifd.NextIfdOffset != 0)
WriteTiffIfdInfo(ifd.NextIfdOffset, ifdPrefix, ifdId + 1, _tagDictionary);
}
private void WriteTiffIfdEntries(TiffIfd ifd, Dictionary<int, string> tagDictionary)
{
foreach (TiffIfdEntry entry in ifd.Entries)
{
WriteTiffIfdEntryInfo(entry, tagDictionary);
}
}
private void WriteTiffIfdEntryInfo(TiffIfdEntry entry, Dictionary<int, string> tagDictionary)
{
var tagStr = ConvertTagToString(tagDictionary, entry.Tag);
var typeStr = entry.Count == 1 ? $"{entry.Type}" : $"{entry.Type}[{entry.Count}]";
object value = GetTiffIfdEntryValue(entry);
if (value is Array)
value = ConvertArrayToString((Array)value);
_report.WriteLine($"{tagStr} = {value}");
}
private object GetTiffIfdEntryValue(TiffIfdEntry entry)
{
switch (entry.Tag)
{
// Use named enums if known
case TiffTags.Compression:
return (TiffCompression)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.ExtraSamples:
return (TiffExtraSamples)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.FillOrder:
return (TiffFillOrder)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.NewSubfileType:
return (TiffNewSubfileType)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.Orientation:
return (TiffOrientation)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.PhotometricInterpretation:
return (TiffPhotometricInterpretation)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.PlanarConfiguration:
return (TiffPlanarConfiguration)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.ResolutionUnit:
return (TiffResolutionUnit)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.SubfileType:
return (TiffSubfileType)_tiffDecoder.ReadUnsignedInteger(ref entry);
case TiffTags.Threshholding:
return (TiffThreshholding)_tiffDecoder.ReadUnsignedInteger(ref entry);
// Other fields
default:
return GetTiffIfdEntryData(entry);
}
}
private string GetTiffIfdEntryData(TiffIfdEntry entry)
{
switch (entry.Type)
{
case TiffType.Byte:
case TiffType.Short:
case TiffType.Long:
if (entry.Count == 1)
return _tiffDecoder.ReadUnsignedInteger(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadUnsignedIntegerArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.SByte:
case TiffType.SShort:
case TiffType.SLong:
if (entry.Count == 1)
return _tiffDecoder.ReadSignedInteger(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadSignedIntegerArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.Ascii:
return "\"" + _tiffDecoder.ReadString(ref entry) + "\"";
case TiffType.Rational:
if (entry.Count == 1)
return _tiffDecoder.ReadUnsignedRational(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadUnsignedRationalArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.SRational:
if (entry.Count == 1)
return _tiffDecoder.ReadSignedRational(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadSignedRationalArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.Float:
if (entry.Count == 1)
return _tiffDecoder.ReadFloat(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadFloatArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.Double:
if (entry.Count == 1)
return _tiffDecoder.ReadDouble(ref entry).ToString();
else
{
var array = _tiffDecoder.ReadDoubleArray(ref entry);
return ConvertArrayToString(array);
}
case TiffType.Undefined:
return "Undefined";
default:
return $"Unknown Type ({(int)entry.Type})";
}
}
private void DecodeImage(TiffIfd ifd, string imageName)
{
try
{
var image = _tiffDecoder.DecodeImage<Rgba32>(ifd);
var filename = Path.Combine(_outputDirectory.FullName, imageName + ".png");
using (FileStream outputStream = File.OpenWrite(filename))
{
image.Save(outputStream);
}
_report.WriteImage(new FileInfo(filename));
}
catch (Exception e)
{
_report.WriteError(e.Message);
}
}
private string ConvertArrayToString<T>(T[] array)
{
var maxArraySize = 10;
var truncatedArray = array.Take(maxArraySize).Select(i => i.ToString());
var arrayString = string.Join(", ", truncatedArray);
var continuationString = array.Length > maxArraySize ? ", ..." : "";
return $"[{arrayString}{continuationString}]";
}
private string ConvertArrayToString(Array array)
{
var maxArraySize = 10;
var itemsToDisplay = Math.Min(array.Length, maxArraySize);
var truncatedArray = new string[itemsToDisplay];
for (int i = 0; i < itemsToDisplay; i++)
{
truncatedArray[i] = array.GetValue(i).ToString();
}
var arrayString = string.Join(", ", truncatedArray);
var continuationString = array.Length > maxArraySize ? ", ..." : "";
return $"[{arrayString}{continuationString}]";
}
private string ConvertTagToString(Dictionary<int, string> dictionary, int tag)
{
string str;
if (dictionary.TryGetValue(tag, out str))
return str;
else
return $"UNKNOWN {tag}";
}
private void PopulateTagDictionary<T>(Dictionary<int, string> dictionary)
{
TypeInfo type = typeof(T).GetTypeInfo();
foreach (var field in type.GetFields())
{
var name = field.Name;
var value = (int)field.GetRawConstantValue();
if (dictionary.ContainsKey(value))
_report.WriteError("CorePhotoInfo ERROR - Tag defined multiple times '{0}'", value);
else
dictionary.Add(value, name);
}
}
public static void WriteTiffInfo(Stream stream, IReportWriter reportWriter, DirectoryInfo outputDirectory)
{
TiffDump instance = new TiffDump(stream, reportWriter, outputDirectory);
instance.PopulateTagDictionary<TiffTags>(instance._tagDictionary);
// instance.PopulateTagDictionary<DngTags>(instance._tagDictionary);
// instance.PopulateTagDictionary<ExifTags>(instance._exifTagDictionary);
instance.WriteTiffInfo();
}
}
}
| |
/*
* 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.Reflection;
using System.Collections.Generic;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public class UndoState
{
const int UNDOEXPIRESECONDS = 300; // undo expire time (nice to have it came from a ini later)
public ObjectChangeData data;
public DateTime creationtime;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="part"></param>
/// <param name="change">bit field with what is changed</param>
///
public UndoState(SceneObjectPart part, ObjectChangeType change)
{
data = new ObjectChangeData();
data.change = change;
creationtime = DateTime.UtcNow;
if (part.ParentGroup.RootPart == part)
{
if ((change & ObjectChangeType.Position) != 0)
data.position = part.ParentGroup.AbsolutePosition;
if ((change & ObjectChangeType.Rotation) != 0)
data.rotation = part.RotationOffset;
if ((change & ObjectChangeType.Scale) != 0)
data.scale = part.Shape.Scale;
}
else
{
if ((change & ObjectChangeType.Position) != 0)
data.position = part.OffsetPosition;
if ((change & ObjectChangeType.Rotation) != 0)
data.rotation = part.RotationOffset;
if ((change & ObjectChangeType.Scale) != 0)
data.scale = part.Shape.Scale;
}
}
/// <summary>
/// check if undo or redo is too old
/// </summary>
public bool checkExpire()
{
TimeSpan t = DateTime.UtcNow - creationtime;
if (t.Seconds > UNDOEXPIRESECONDS)
return true;
return false;
}
/// <summary>
/// updates undo or redo creation time to now
/// </summary>
public void updateExpire()
{
creationtime = DateTime.UtcNow;
}
/// <summary>
/// Compare the relevant state in the given part to this state.
/// </summary>
/// <param name="part"></param>
/// <returns>true what fiels and related data are equal, False otherwise.</returns>
///
public bool Compare(SceneObjectPart part, ObjectChangeType change)
{
if (data.change != change) // if diferent targets, then they are diferent
return false;
if (part != null)
{
if (part.ParentID == 0)
{
if ((change & ObjectChangeType.Position) != 0 && data.position != part.ParentGroup.AbsolutePosition)
return false;
}
else
{
if ((change & ObjectChangeType.Position) != 0 && data.position != part.OffsetPosition)
return false;
}
if ((change & ObjectChangeType.Rotation) != 0 && data.rotation != part.RotationOffset)
return false;
if ((change & ObjectChangeType.Rotation) != 0 && data.scale == part.Shape.Scale)
return false;
return true;
}
return false;
}
/// <summary>
/// executes the undo or redo to a part or its group
/// </summary>
/// <param name="part"></param>
///
public void PlayState(SceneObjectPart part)
{
part.Undoing = true;
SceneObjectGroup grp = part.ParentGroup;
if (grp != null)
{
grp.doChangeObject(part, data);
}
part.Undoing = false;
}
}
public class UndoRedoState
{
int size;
public LinkedList<UndoState> m_redo = new LinkedList<UndoState>();
public LinkedList<UndoState> m_undo = new LinkedList<UndoState>();
/// <summary>
/// creates a new UndoRedoState with default states memory size
/// </summary>
public UndoRedoState()
{
size = 5;
}
/// <summary>
/// creates a new UndoRedoState with states memory having indicated size
/// </summary>
/// <param name="size"></param>
public UndoRedoState(int _size)
{
if (_size < 3)
size = 3;
else
size = _size;
}
/// <summary>
/// returns number of undo entries in memory
/// </summary>
public int Count
{
get { return m_undo.Count; }
}
/// <summary>
/// clears all undo and redo entries
/// </summary>
public void Clear()
{
m_undo.Clear();
m_redo.Clear();
}
/// <summary>
/// adds a new state undo to part or its group, with changes indicated by what bits
/// </summary>
/// <param name="part"></param>
/// <param name="change">bit field with what is changed</param>
public void StoreUndo(SceneObjectPart part, ObjectChangeType change)
{
lock (m_undo)
{
UndoState last;
if (m_redo.Count > 0) // last code seems to clear redo on every new undo
{
m_redo.Clear();
}
if (m_undo.Count > 0)
{
// check expired entry
last = m_undo.First.Value;
if (last != null && last.checkExpire())
m_undo.Clear();
else
{
// see if we actually have a change
if (last != null)
{
if (last.Compare(part, change))
return;
}
}
}
// limite size
while (m_undo.Count >= size)
m_undo.RemoveLast();
UndoState nUndo = new UndoState(part, change);
m_undo.AddFirst(nUndo);
}
}
/// <summary>
/// executes last state undo to part or its group
/// current state is pushed into redo
/// </summary>
/// <param name="part"></param>
public void Undo(SceneObjectPart part)
{
lock (m_undo)
{
UndoState nUndo;
// expire redo
if (m_redo.Count > 0)
{
nUndo = m_redo.First.Value;
if (nUndo != null && nUndo.checkExpire())
m_redo.Clear();
}
if (m_undo.Count > 0)
{
UndoState goback = m_undo.First.Value;
// check expired
if (goback != null && goback.checkExpire())
{
m_undo.Clear();
return;
}
if (goback != null)
{
m_undo.RemoveFirst();
// redo limite size
while (m_redo.Count >= size)
m_redo.RemoveLast();
nUndo = new UndoState(part, goback.data.change); // new value in part should it be full goback copy?
m_redo.AddFirst(nUndo);
goback.PlayState(part);
}
}
}
}
/// <summary>
/// executes last state redo to part or its group
/// current state is pushed into undo
/// </summary>
/// <param name="part"></param>
public void Redo(SceneObjectPart part)
{
lock (m_undo)
{
UndoState nUndo;
// expire undo
if (m_undo.Count > 0)
{
nUndo = m_undo.First.Value;
if (nUndo != null && nUndo.checkExpire())
m_undo.Clear();
}
if (m_redo.Count > 0)
{
UndoState gofwd = m_redo.First.Value;
// check expired
if (gofwd != null && gofwd.checkExpire())
{
m_redo.Clear();
return;
}
if (gofwd != null)
{
m_redo.RemoveFirst();
// limite undo size
while (m_undo.Count >= size)
m_undo.RemoveLast();
nUndo = new UndoState(part, gofwd.data.change); // new value in part should it be full gofwd copy?
m_undo.AddFirst(nUndo);
gofwd.PlayState(part);
}
}
}
}
}
public class LandUndoState
{
public ITerrainModule m_terrainModule;
public ITerrainChannel m_terrainChannel;
public LandUndoState(ITerrainModule terrainModule, ITerrainChannel terrainChannel)
{
m_terrainModule = terrainModule;
m_terrainChannel = terrainChannel;
}
public bool Compare(ITerrainChannel terrainChannel)
{
return m_terrainChannel == terrainChannel;
}
public void PlaybackState()
{
m_terrainModule.UndoTerrain(m_terrainChannel);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TimeForInsurance.Backend.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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
{
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.Versioning;
using System.Text;
using System.Globalization;
using System.Security;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeTypeHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeTypeHandle(type);
}
// Returns type for interop with EE. The type is guaranteed to be non-null.
internal RuntimeType GetTypeChecked()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
if (genericArgs != null)
{
type = type.MakeGenericType(genericArgs);
}
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
for (int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.Ptr)
type = type.MakePointerType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ByRef)
type = type.MakeByRefType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.SzArray)
type = type.MakeArrayType();
else
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object right) { return left.Equals(right); }
public static bool operator ==(object left, RuntimeTypeHandle right) { return right.Equals(left); }
public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); }
public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); }
// This is the RuntimeType for the type
private RuntimeType m_type;
public override int GetHashCode()
{
return m_type != null ? m_type.GetHashCode() : 0;
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeTypeHandle))
return false;
RuntimeTypeHandle handle = (RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
}
public IntPtr Value
{
get
{
return m_type != null ? m_type.m_handle : IntPtr.Zero;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
internal RuntimeTypeHandle(RuntimeType type)
{
m_type = type;
}
internal static bool IsTypeDefinition(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
if (!((corElemType >= CorElementType.Void && corElemType < CorElementType.Ptr) ||
corElemType == CorElementType.ValueType ||
corElemType == CorElementType.Class ||
corElemType == CorElementType.TypedByRef ||
corElemType == CorElementType.I ||
corElemType == CorElementType.U ||
corElemType == CorElementType.Object))
return false;
if (HasInstantiation(type) && !IsGenericTypeDefinition(type))
return false;
return true;
}
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType >= CorElementType.Boolean && corElemType <= CorElementType.R8) ||
corElemType == CorElementType.I ||
corElemType == CorElementType.U;
}
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.ByRef);
}
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Ptr);
}
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
}
internal static bool IsSZArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.SzArray);
}
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return ((corElemType == CorElementType.Array || corElemType == CorElementType.SzArray) // IsArray
|| (corElemType == CorElementType.Ptr) // IsPointer
|| (corElemType == CorElementType.ByRef)); // IsByRef
}
internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].Value;
}
length = outHandles.Length;
return outHandles;
}
internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].GetTypeHandleInternal().Value;
}
length = outHandles.Length;
return outHandles;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object Allocate(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
internal RuntimeType GetRuntimeType()
{
return m_type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static CorElementType GetCorElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeModule GetModule(RuntimeType type);
[CLSCompliant(false)]
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetBaseType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static TypeAttributes GetAttributes(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetArrayRank(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetToken(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
private bool _firstCall;
private RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
public bool MoveNext()
{
if (_firstCall)
{
_firstCall = false;
}
else if (_handle.Value != IntPtr.Zero)
{
RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle);
}
return !(_handle.Value == IntPtr.Zero);
}
public RuntimeMethodHandleInternal Current
{
get
{
return _handle;
}
}
// Glue to make this work nicely with C# foreach statement
public IntroducedMethodEnumerator GetEnumerator()
{
return this;
}
}
internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type)
{
return new IntroducedMethodEnumerator(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Type[] GetInterfaces(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
Type[] types = null;
GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type);
internal IntPtr GetGCHandle(GCHandleType type)
{
return GetGCHandle(GetNativeHandle(), type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetNumVirtuals(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle);
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsByRefLike(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new RuntimeTypeHandle(type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsValueType(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string name = null;
ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeType type);
internal static Utf8String GetUtf8Name(RuntimeType type)
{
return new Utf8String(_GetUtf8Name(type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CanCastTo(RuntimeType type, RuntimeType target);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
internal IRuntimeMethodInfo GetDefaultConstructor()
{
IRuntimeMethodInfo ctor = null;
GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName);
}
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName)
{
if (name == null || name.Length == 0)
{
if (throwOnError)
throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
RuntimeType type = null;
Object keepAlive = null;
GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly,
JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
pPrivHostBinder,
loadTypeFromPartialName, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (name == null || name.Length == 0)
throw new ArgumentException(null, nameof(name));
Contract.EndContractBlock();
RuntimeType type = null;
GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal Type[] GetInstantiationPublic()
{
Type[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false);
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
internal RuntimeType Instantiate(Type[] inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
RuntimeType type = null;
Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(inst);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type);
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null;
MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeSZArray()
{
RuntimeType type = null;
MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeByRef()
{
RuntimeType type = null;
MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakePointer()
{
RuntimeType type = null;
MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCollectible(RuntimeTypeHandle handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType))
GetGenericTypeDefinition(retType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref retType));
return retType;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericTypeDefinition(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericVariableIndex(RuntimeType type);
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
return GetGenericVariableIndex(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool ContainsGenericVariables(RuntimeType handle);
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
GC.KeepAlive(typeContext);
GC.KeepAlive(methodContext);
return result;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeType type);
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved
// across the lifetime of the RuntimeMethodHandleInternal instance
// 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure
// When in doubt, do not use.
internal struct RuntimeMethodHandleInternal
{
internal static RuntimeMethodHandleInternal EmptyHandle
{
get
{
return new RuntimeMethodHandleInternal();
}
}
internal bool IsNullHandle()
{
return m_handle.IsNull();
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal class RuntimeMethodInfoStub : IRuntimeMethodInfo
{
public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = methodHandleValue;
}
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable 169
private object m_a;
private object m_b;
private object m_c;
private object m_d;
private object m_e;
private object m_f;
private object m_g;
#pragma warning restore 169
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return m_value;
}
}
}
internal interface IRuntimeMethodInfo
{
RuntimeMethodHandleInternal Value
{
get;
}
}
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return method;
}
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
}
internal IRuntimeMethodInfo GetMethodInfo()
{
return m_value;
}
// Used by EE
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public IntPtr Value
{
get
{
return m_value != null ? m_value.Value.Value : IntPtr.Zero;
}
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
RuntimeMethodHandle handle = (RuntimeMethodHandle)obj;
return handle.Value == Value;
}
public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return !left.Equals(right);
}
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
}
[Pure]
internal bool IsNullHandle()
{
return m_value == null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
GC.KeepAlive(m_value);
return ptr;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCAVisibleFromDecoratedType(
RuntimeTypeHandle attrTypeHandle,
IRuntimeMethodInfo attrCtor,
RuntimeTypeHandle sourceTypeHandle,
RuntimeModule sourceModule);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
GC.KeepAlive(method);
return retVal;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string name = null;
ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
GC.KeepAlive(method);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetSlot(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
Contract.Requires(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
return slot;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMethodDef(IRuntimeMethodInfo method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static string GetName(RuntimeMethodHandleInternal method);
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
GC.KeepAlive(method);
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method);
internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new Utf8String(_GetUtf8Name(method));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions);
#region Private Invocation Helpers
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
{
return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
#endregion
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true);
GC.KeepAlive(method);
return types;
}
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null;
GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false);
GC.KeepAlive(method);
return types;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
GetTypicalMethodDefinition(method, JitHelpers.GetObjectHandleOnStack(ref method));
return method;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericParameterCount(RuntimeMethodHandleInternal method);
internal static int GetGenericParameterCount(IRuntimeMethodInfo method) => GetGenericParameterCount(method.Value);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
StripMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref strippedMethod));
return strippedMethod;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void Destroy(RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static bool IsConstructor(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved
// across the lifetime of the RuntimeFieldHandleInternal instance
// 3. When another object is used to keep the RuntimeFieldHandleInternal alive.
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
internal bool IsNullHandle()
{
return m_handle.IsNull();
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal interface IRuntimeFieldInfo
{
RuntimeFieldHandleInternal Value
{
get;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 169
private object m_keepalive;
private object m_c;
private object m_d;
private int m_b;
private object m_e;
private RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 169
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return m_fieldHandle;
}
}
}
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeFieldHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeFieldHandle(field);
}
private IRuntimeFieldInfo m_ptr;
internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo)
{
m_ptr = fieldInfo;
}
internal IRuntimeFieldInfo GetRuntimeFieldInfo()
{
return m_ptr;
}
public IntPtr Value
{
get
{
return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
}
}
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
RuntimeFieldHandle handle = (RuntimeFieldHandle)obj;
return handle.Value == Value;
}
public unsafe bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
}
public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetName(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
GC.KeepAlive(field);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
#region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
#endregion
unsafe static private ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
#region Private Data Members
private RuntimeModule m_ptr;
#endregion
#region Constructor
internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
#endregion
#region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
public override bool Equals(object obj)
{
if (!(obj is ModuleHandle))
return false;
ModuleHandle handle = (ModuleHandle)obj;
return handle.m_ptr == m_ptr;
}
public unsafe bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
}
public static bool operator ==(ModuleHandle left, ModuleHandle right)
{
return left.Equals(right);
}
public static bool operator !=(ModuleHandle left, ModuleHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
private static void ValidateModulePointer(RuntimeModule module)
{
// Make sure we have a valid Module to resolve against.
if (module == null)
throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle);
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
RuntimeType type = null;
ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveType(RuntimeModule module,
int typeToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack type);
// SQL-CLR LKG9 Compiler dependency
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return retVal;
}
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
return ResolveMethod(module.GetNativeHandle(), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
int methodToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
IRuntimeFieldInfo field = null;
ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return field;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveField(RuntimeModule module,
int fieldToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack retField);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash);
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null;
GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
GetPEKind(module.GetNativeHandle(), out lKind, out lMachine);
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion
{
get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeModule module);
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
#endregion
}
internal unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType);
#endregion
#region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
internal RuntimeType[] m_arguments;
internal RuntimeType m_declaringType;
internal RuntimeType m_returnTypeORfieldType;
internal object m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
#endregion
#region Constructors
public Signature(
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
CallingConventions callingConvention)
{
m_pMethod = method.Value;
m_arguments = arguments;
m_returnTypeORfieldType = returnType;
m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention;
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
#endregion
#region Internal Members
internal CallingConventions CallingConvention { get { return (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; } }
internal RuntimeType[] Arguments { get { return m_arguments; } }
internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
}
internal abstract class Resolver
{
internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
internal int ClassTokenOrFilterOffset;
}
// ILHeader info
internal abstract RuntimeType GetJitContext(ref int securityControlFlags);
internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount);
internal abstract byte[] GetLocalsSignature();
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract unsafe byte[] GetRawEHInfo();
// token resolution
internal abstract String GetStringLiteral(int token);
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[] ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=RangeContentEnumerator.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: IEnumerator for TextRange and TextElement content.
//
//
// History:
// 05/27/2003 : [....] - Created
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using MS.Internal;
using System.Text;
using MS.Utility;
using System.Windows.Controls;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows.Documents
{
internal class TextElementEnumerator<TextElementType> : IEnumerator<TextElementType> where TextElementType : TextElement
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Creates an enumerator instance.
// Null start/end creates an empty enumerator.
internal TextElementEnumerator(TextPointer start, TextPointer end)
{
Invariant.Assert(start != null && end != null || start == null && end == null, "If start is null end should be null!");
_start = start;
_end = end;
// Remember what generation the backing store was in when we started,
// so we can throw if this enumerator is accessed after content has
// changed.
if (_start != null)
{
_generation = _start.TextContainer.Generation;
}
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
public void Dispose()
{
// Empty the enumerator
_current = null;
_navigator = null;
GC.SuppressFinalize(this);
}
object System.Collections.IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Return the current object this enumerator is pointing to. This is
/// generally a FrameworkElement, TextElement, an embedded
/// object, or Text content.
/// </summary>
/// <remarks>
/// According to the IEnumerator spec, the Current property keeps
/// the element even after the content has been modified
/// (even if the current element has been deleted from the collection).
/// This is unlike to Reset or MoveNext which throw after any content change.
/// </remarks>
public TextElementType Current
{
get
{
if (_navigator == null)
{
#pragma warning suppress 6503 // IEnumerator.Current is documented to throw this exception
throw new InvalidOperationException(SR.Get(SRID.EnumeratorNotStarted));
}
if (_current == null)
{
#pragma warning suppress 6503 // IEnumerator.Current is documented to throw this exception
throw new InvalidOperationException(SR.Get(SRID.EnumeratorReachedEnd));
}
return _current;
}
}
/// <summary>
/// Advance the enumerator to the next object in the range. Return true if content
/// was found.
/// </summary>
public bool MoveNext()
{
// Throw if the tree has been modified since this enumerator was created.
if (_start != null && _generation != _start.TextContainer.Generation)
{
throw new InvalidOperationException(SR.Get(SRID.EnumeratorVersionChanged));
}
// Return false if the collection is empty
if (_start == null || _start.CompareTo(_end) == 0)
{
return false;
}
// Return false if the navigator reached the end of the collection
if (_navigator != null && _navigator.CompareTo(_end) >= 0)
{
return false;
}
// Advance the navigator
if (_navigator == null)
{
// Set it to the first element for the very first move
_navigator = new TextPointer(_start);
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
else
{
// Move to the next element in the collection
Invariant.Assert(_navigator.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart,
"Unexpected run type in TextElementEnumerator");
_navigator.MoveToElementEdge(ElementEdge.AfterEnd);
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
// Update current cache
if (_navigator.CompareTo(_end) < 0)
{
_current = (TextElementType)_navigator.Parent;
}
else
{
_current = null;
}
// Return true if the content was found
return (_current != null);
}
/// <summary>
/// Reset the enumerator to the start of the range.
/// </summary>
public void Reset()
{
// Throw if the tree has been modified since this enumerator was created.
if (_start != null && _generation != _start.TextContainer.Generation)
{
throw new InvalidOperationException(SR.Get(SRID.EnumeratorVersionChanged));
}
_navigator = null;
_current = null;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion Protected Events
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Internal Events
#endregion Internal Events
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
#endregion Private Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Edges of the span to enumerator over.
private readonly TextPointer _start;
private readonly TextPointer _end;
// Backing store generation when this enumerator was created.
private readonly uint _generation;
// Current position in the enumeration.
private TextPointer _navigator;
// Calculated content at the current position.
private TextElementType _current;
#endregion Private Fields
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.IO;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Collections.Generic;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageReader : BinaryStreamReader {
readonly Image image;
DataDirectory cli;
DataDirectory metadata;
uint table_heap_offset;
public ImageReader (Disposable<Stream> stream, string file_name)
: base (stream.value)
{
image = new Image ();
image.Stream = stream;
image.FileName = file_name;
}
void MoveTo (DataDirectory directory)
{
BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress);
}
void ReadImage ()
{
if (BaseStream.Length < 128)
throw new BadImageFormatException ();
// - DOSHeader
// PE 2
// Start 58
// Lfanew 4
// End 64
if (ReadUInt16 () != 0x5a4d)
throw new BadImageFormatException ();
Advance (58);
MoveTo (ReadUInt32 ());
if (ReadUInt32 () != 0x00004550)
throw new BadImageFormatException ();
// - PEFileHeader
// Machine 2
image.Architecture = ReadArchitecture ();
// NumberOfSections 2
ushort sections = ReadUInt16 ();
// TimeDateStamp 4
image.Timestamp = ReadUInt32 ();
// PointerToSymbolTable 4
// NumberOfSymbols 4
// OptionalHeaderSize 2
Advance (10);
// Characteristics 2
ushort characteristics = ReadUInt16 ();
ushort subsystem, dll_characteristics, linker_version;
ReadOptionalHeaders (out subsystem, out dll_characteristics, out linker_version);
ReadSections (sections);
ReadCLIHeader ();
ReadMetadata ();
ReadDebugHeader ();
image.Kind = GetModuleKind (characteristics, subsystem);
image.Characteristics = (ModuleCharacteristics) dll_characteristics;
image.LinkerVersion = linker_version;
}
TargetArchitecture ReadArchitecture ()
{
return (TargetArchitecture) ReadUInt16 ();
}
static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem)
{
if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll
return ModuleKind.Dll;
if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui
return ModuleKind.Windows;
return ModuleKind.Console;
}
void ReadOptionalHeaders (out ushort subsystem, out ushort dll_characteristics, out ushort linker)
{
// - PEOptionalHeader
// - StandardFieldsHeader
// Magic 2
bool pe64 = ReadUInt16 () == 0x20b;
// pe32 || pe64
linker = ReadUInt16 ();
// CodeSize 4
// InitializedDataSize 4
// UninitializedDataSize4
// EntryPointRVA 4
// BaseOfCode 4
// BaseOfData 4 || 0
// - NTSpecificFieldsHeader
// ImageBase 4 || 8
// SectionAlignment 4
// FileAlignement 4
// OSMajor 2
// OSMinor 2
// UserMajor 2
// UserMinor 2
// SubSysMajor 2
// SubSysMinor 2
// Reserved 4
// ImageSize 4
// HeaderSize 4
// FileChecksum 4
Advance (64);
// SubSystem 2
subsystem = ReadUInt16 ();
// DLLFlags 2
dll_characteristics = ReadUInt16 ();
// StackReserveSize 4 || 8
// StackCommitSize 4 || 8
// HeapReserveSize 4 || 8
// HeapCommitSize 4 || 8
// LoaderFlags 4
// NumberOfDataDir 4
// - DataDirectoriesHeader
// ExportTable 8
// ImportTable 8
Advance (pe64 ? 56 : 40);
// ResourceTable 8
image.Win32Resources = ReadDataDirectory ();
// ExceptionTable 8
// CertificateTable 8
// BaseRelocationTable 8
Advance (24);
// Debug 8
image.Debug = ReadDataDirectory ();
// Copyright 8
// GlobalPtr 8
// TLSTable 8
// LoadConfigTable 8
// BoundImport 8
// IAT 8
// DelayImportDescriptor8
Advance (56);
// CLIHeader 8
cli = ReadDataDirectory ();
if (cli.IsZero)
throw new BadImageFormatException ();
// Reserved 8
Advance (8);
}
string ReadAlignedString (int length)
{
int read = 0;
var buffer = new char [length];
while (read < length) {
var current = ReadByte ();
if (current == 0)
break;
buffer [read++] = (char) current;
}
Advance (-1 + ((read + 4) & ~3) - read);
return new string (buffer, 0, read);
}
string ReadZeroTerminatedString (int length)
{
int read = 0;
var buffer = new char [length];
var bytes = ReadBytes (length);
while (read < length) {
var current = bytes [read];
if (current == 0)
break;
buffer [read++] = (char) current;
}
return new string (buffer, 0, read);
}
void ReadSections (ushort count)
{
var sections = new Section [count];
for (int i = 0; i < count; i++) {
var section = new Section ();
// Name
section.Name = ReadZeroTerminatedString (8);
// VirtualSize 4
Advance (4);
// VirtualAddress 4
section.VirtualAddress = ReadUInt32 ();
// SizeOfRawData 4
section.SizeOfRawData = ReadUInt32 ();
// PointerToRawData 4
section.PointerToRawData = ReadUInt32 ();
// PointerToRelocations 4
// PointerToLineNumbers 4
// NumberOfRelocations 2
// NumberOfLineNumbers 2
// Characteristics 4
Advance (16);
sections [i] = section;
}
image.Sections = sections;
}
void ReadCLIHeader ()
{
MoveTo (cli);
// - CLIHeader
// Cb 4
// MajorRuntimeVersion 2
// MinorRuntimeVersion 2
Advance (8);
// Metadata 8
metadata = ReadDataDirectory ();
// Flags 4
image.Attributes = (ModuleAttributes) ReadUInt32 ();
// EntryPointToken 4
image.EntryPointToken = ReadUInt32 ();
// Resources 8
image.Resources = ReadDataDirectory ();
// StrongNameSignature 8
image.StrongName = ReadDataDirectory ();
// CodeManagerTable 8
// VTableFixups 8
// ExportAddressTableJumps 8
// ManagedNativeHeader 8
}
void ReadMetadata ()
{
MoveTo (metadata);
if (ReadUInt32 () != 0x424a5342)
throw new BadImageFormatException ();
// MajorVersion 2
// MinorVersion 2
// Reserved 4
Advance (8);
image.RuntimeVersion = ReadZeroTerminatedString (ReadInt32 ());
// Flags 2
Advance (2);
var streams = ReadUInt16 ();
var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress);
if (section == null)
throw new BadImageFormatException ();
image.MetadataSection = section;
for (int i = 0; i < streams; i++)
ReadMetadataStream (section);
if (image.PdbHeap != null)
ReadPdbHeap ();
if (image.TableHeap != null)
ReadTableHeap ();
}
void ReadDebugHeader ()
{
if (image.Debug.IsZero) {
image.DebugHeader = new ImageDebugHeader (Empty<ImageDebugHeaderEntry>.Array);
return;
}
MoveTo (image.Debug);
var entries = new ImageDebugHeaderEntry [(int) image.Debug.Size / ImageDebugDirectory.Size];
for (int i = 0; i < entries.Length; i++) {
var directory = new ImageDebugDirectory {
Characteristics = ReadInt32 (),
TimeDateStamp = ReadInt32 (),
MajorVersion = ReadInt16 (),
MinorVersion = ReadInt16 (),
Type = (ImageDebugType) ReadInt32 (),
SizeOfData = ReadInt32 (),
AddressOfRawData = ReadInt32 (),
PointerToRawData = ReadInt32 (),
};
if (directory.AddressOfRawData == 0) {
entries [i] = new ImageDebugHeaderEntry (directory, Empty<byte>.Array);
continue;
}
var position = Position;
try {
MoveTo ((uint) directory.PointerToRawData);
var data = ReadBytes (directory.SizeOfData);
entries [i] = new ImageDebugHeaderEntry (directory, data);
} finally {
Position = position;
}
}
image.DebugHeader = new ImageDebugHeader (entries);
}
void ReadMetadataStream (Section section)
{
// Offset 4
uint offset = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start
// Size 4
uint size = ReadUInt32 ();
var data = ReadHeapData (offset, size);
var name = ReadAlignedString (16);
switch (name) {
case "#~":
case "#-":
image.TableHeap = new TableHeap (data);
table_heap_offset = offset;
break;
case "#Strings":
image.StringHeap = new StringHeap (data);
break;
case "#Blob":
image.BlobHeap = new BlobHeap (data);
break;
case "#GUID":
image.GuidHeap = new GuidHeap (data);
break;
case "#US":
image.UserStringHeap = new UserStringHeap (data);
break;
case "#Pdb":
image.PdbHeap = new PdbHeap (data);
break;
}
}
byte [] ReadHeapData (uint offset, uint size)
{
var position = BaseStream.Position;
MoveTo (offset + image.MetadataSection.PointerToRawData);
var data = ReadBytes ((int) size);
BaseStream.Position = position;
return data;
}
void ReadTableHeap ()
{
var heap = image.TableHeap;
MoveTo (table_heap_offset + image.MetadataSection.PointerToRawData);
// Reserved 4
// MajorVersion 1
// MinorVersion 1
Advance (6);
// HeapSizes 1
var sizes = ReadByte ();
// Reserved2 1
Advance (1);
// Valid 8
heap.Valid = ReadInt64 ();
// Sorted 8
heap.Sorted = ReadInt64 ();
if (image.PdbHeap != null) {
for (int i = 0; i < Mixin.TableCount; i++) {
if (!image.PdbHeap.HasTable ((Table) i))
continue;
heap.Tables [i].Length = image.PdbHeap.TypeSystemTableRows [i];
}
}
for (int i = 0; i < Mixin.TableCount; i++) {
if (!heap.HasTable ((Table) i))
continue;
heap.Tables [i].Length = ReadUInt32 ();
}
SetIndexSize (image.StringHeap, sizes, 0x1);
SetIndexSize (image.GuidHeap, sizes, 0x2);
SetIndexSize (image.BlobHeap, sizes, 0x4);
ComputeTableInformations ();
}
static void SetIndexSize (Heap heap, uint sizes, byte flag)
{
if (heap == null)
return;
heap.IndexSize = (sizes & flag) > 0 ? 4 : 2;
}
int GetTableIndexSize (Table table)
{
return image.GetTableIndexSize (table);
}
int GetCodedIndexSize (CodedIndex index)
{
return image.GetCodedIndexSize (index);
}
void ComputeTableInformations ()
{
uint offset = (uint) BaseStream.Position - table_heap_offset - image.MetadataSection.PointerToRawData; // header
int stridx_size = image.StringHeap.IndexSize;
int guididx_size = image.GuidHeap != null ? image.GuidHeap.IndexSize : 2;
int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2;
var heap = image.TableHeap;
var tables = heap.Tables;
for (int i = 0; i < Mixin.TableCount; i++) {
var table = (Table) i;
if (!heap.HasTable (table))
continue;
int size;
switch (table) {
case Table.Module:
size = 2 // Generation
+ stridx_size // Name
+ (guididx_size * 3); // Mvid, EncId, EncBaseId
break;
case Table.TypeRef:
size = GetCodedIndexSize (CodedIndex.ResolutionScope) // ResolutionScope
+ (stridx_size * 2); // Name, Namespace
break;
case Table.TypeDef:
size = 4 // Flags
+ (stridx_size * 2) // Name, Namespace
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef) // BaseType
+ GetTableIndexSize (Table.Field) // FieldList
+ GetTableIndexSize (Table.Method); // MethodList
break;
case Table.FieldPtr:
size = GetTableIndexSize (Table.Field); // Field
break;
case Table.Field:
size = 2 // Flags
+ stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.MethodPtr:
size = GetTableIndexSize (Table.Method); // Method
break;
case Table.Method:
size = 8 // Rva 4, ImplFlags 2, Flags 2
+ stridx_size // Name
+ blobidx_size // Signature
+ GetTableIndexSize (Table.Param); // ParamList
break;
case Table.ParamPtr:
size = GetTableIndexSize (Table.Param); // Param
break;
case Table.Param:
size = 4 // Flags 2, Sequence 2
+ stridx_size; // Name
break;
case Table.InterfaceImpl:
size = GetTableIndexSize (Table.TypeDef) // Class
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Interface
break;
case Table.MemberRef:
size = GetCodedIndexSize (CodedIndex.MemberRefParent) // Class
+ stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.Constant:
size = 2 // Type
+ GetCodedIndexSize (CodedIndex.HasConstant) // Parent
+ blobidx_size; // Value
break;
case Table.CustomAttribute:
size = GetCodedIndexSize (CodedIndex.HasCustomAttribute) // Parent
+ GetCodedIndexSize (CodedIndex.CustomAttributeType) // Type
+ blobidx_size; // Value
break;
case Table.FieldMarshal:
size = GetCodedIndexSize (CodedIndex.HasFieldMarshal) // Parent
+ blobidx_size; // NativeType
break;
case Table.DeclSecurity:
size = 2 // Action
+ GetCodedIndexSize (CodedIndex.HasDeclSecurity) // Parent
+ blobidx_size; // PermissionSet
break;
case Table.ClassLayout:
size = 6 // PackingSize 2, ClassSize 4
+ GetTableIndexSize (Table.TypeDef); // Parent
break;
case Table.FieldLayout:
size = 4 // Offset
+ GetTableIndexSize (Table.Field); // Field
break;
case Table.StandAloneSig:
size = blobidx_size; // Signature
break;
case Table.EventMap:
size = GetTableIndexSize (Table.TypeDef) // Parent
+ GetTableIndexSize (Table.Event); // EventList
break;
case Table.EventPtr:
size = GetTableIndexSize (Table.Event); // Event
break;
case Table.Event:
size = 2 // Flags
+ stridx_size // Name
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // EventType
break;
case Table.PropertyMap:
size = GetTableIndexSize (Table.TypeDef) // Parent
+ GetTableIndexSize (Table.Property); // PropertyList
break;
case Table.PropertyPtr:
size = GetTableIndexSize (Table.Property); // Property
break;
case Table.Property:
size = 2 // Flags
+ stridx_size // Name
+ blobidx_size; // Type
break;
case Table.MethodSemantics:
size = 2 // Semantics
+ GetTableIndexSize (Table.Method) // Method
+ GetCodedIndexSize (CodedIndex.HasSemantics); // Association
break;
case Table.MethodImpl:
size = GetTableIndexSize (Table.TypeDef) // Class
+ GetCodedIndexSize (CodedIndex.MethodDefOrRef) // MethodBody
+ GetCodedIndexSize (CodedIndex.MethodDefOrRef); // MethodDeclaration
break;
case Table.ModuleRef:
size = stridx_size; // Name
break;
case Table.TypeSpec:
size = blobidx_size; // Signature
break;
case Table.ImplMap:
size = 2 // MappingFlags
+ GetCodedIndexSize (CodedIndex.MemberForwarded) // MemberForwarded
+ stridx_size // ImportName
+ GetTableIndexSize (Table.ModuleRef); // ImportScope
break;
case Table.FieldRVA:
size = 4 // RVA
+ GetTableIndexSize (Table.Field); // Field
break;
case Table.EncLog:
size = 8;
break;
case Table.EncMap:
size = 4;
break;
case Table.Assembly:
size = 16 // HashAlgId 4, Version 4 * 2, Flags 4
+ blobidx_size // PublicKey
+ (stridx_size * 2); // Name, Culture
break;
case Table.AssemblyProcessor:
size = 4; // Processor
break;
case Table.AssemblyOS:
size = 12; // Platform 4, Version 2 * 4
break;
case Table.AssemblyRef:
size = 12 // Version 2 * 4 + Flags 4
+ (blobidx_size * 2) // PublicKeyOrToken, HashValue
+ (stridx_size * 2); // Name, Culture
break;
case Table.AssemblyRefProcessor:
size = 4 // Processor
+ GetTableIndexSize (Table.AssemblyRef); // AssemblyRef
break;
case Table.AssemblyRefOS:
size = 12 // Platform 4, Version 2 * 4
+ GetTableIndexSize (Table.AssemblyRef); // AssemblyRef
break;
case Table.File:
size = 4 // Flags
+ stridx_size // Name
+ blobidx_size; // HashValue
break;
case Table.ExportedType:
size = 8 // Flags 4, TypeDefId 4
+ (stridx_size * 2) // Name, Namespace
+ GetCodedIndexSize (CodedIndex.Implementation); // Implementation
break;
case Table.ManifestResource:
size = 8 // Offset, Flags
+ stridx_size // Name
+ GetCodedIndexSize (CodedIndex.Implementation); // Implementation
break;
case Table.NestedClass:
size = GetTableIndexSize (Table.TypeDef) // NestedClass
+ GetTableIndexSize (Table.TypeDef); // EnclosingClass
break;
case Table.GenericParam:
size = 4 // Number, Flags
+ GetCodedIndexSize (CodedIndex.TypeOrMethodDef) // Owner
+ stridx_size; // Name
break;
case Table.MethodSpec:
size = GetCodedIndexSize (CodedIndex.MethodDefOrRef) // Method
+ blobidx_size; // Instantiation
break;
case Table.GenericParamConstraint:
size = GetTableIndexSize (Table.GenericParam) // Owner
+ GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Constraint
break;
case Table.Document:
size = blobidx_size // Name
+ guididx_size // HashAlgorithm
+ blobidx_size // Hash
+ guididx_size; // Language
break;
case Table.MethodDebugInformation:
size = GetTableIndexSize (Table.Document) // Document
+ blobidx_size; // SequencePoints
break;
case Table.LocalScope:
size = GetTableIndexSize (Table.Method) // Method
+ GetTableIndexSize (Table.ImportScope) // ImportScope
+ GetTableIndexSize (Table.LocalVariable) // VariableList
+ GetTableIndexSize (Table.LocalConstant) // ConstantList
+ 4 * 2; // StartOffset, Length
break;
case Table.LocalVariable:
size = 2 // Attributes
+ 2 // Index
+ stridx_size; // Name
break;
case Table.LocalConstant:
size = stridx_size // Name
+ blobidx_size; // Signature
break;
case Table.ImportScope:
size = GetTableIndexSize (Table.ImportScope) // Parent
+ blobidx_size;
break;
case Table.StateMachineMethod:
size = GetTableIndexSize (Table.Method) // MoveNextMethod
+ GetTableIndexSize (Table.Method); // KickOffMethod
break;
case Table.CustomDebugInformation:
size = GetCodedIndexSize (CodedIndex.HasCustomDebugInformation) // Parent
+ guididx_size // Kind
+ blobidx_size; // Value
break;
default:
throw new NotSupportedException ();
}
tables [i].RowSize = (uint) size;
tables [i].Offset = offset;
offset += (uint) size * tables [i].Length;
}
}
void ReadPdbHeap ()
{
var heap = image.PdbHeap;
var buffer = new ByteBuffer (heap.data);
heap.Id = buffer.ReadBytes (20);
heap.EntryPoint = buffer.ReadUInt32 ();
heap.TypeSystemTables = buffer.ReadInt64 ();
heap.TypeSystemTableRows = new uint [Mixin.TableCount];
for (int i = 0; i < Mixin.TableCount; i++) {
var table = (Table) i;
if (!heap.HasTable (table))
continue;
heap.TypeSystemTableRows [i] = buffer.ReadUInt32 ();
}
}
public static Image ReadImage (Disposable<Stream> stream, string file_name)
{
try {
var reader = new ImageReader (stream, file_name);
reader.ReadImage ();
return reader.image;
} catch (EndOfStreamException e) {
throw new BadImageFormatException (stream.value.GetFileName (), e);
}
}
public static Image ReadPortablePdb (Disposable<Stream> stream, string file_name)
{
try {
var reader = new ImageReader (stream, file_name);
var length = (uint) stream.value.Length;
reader.image.Sections = new[] {
new Section {
PointerToRawData = 0,
SizeOfRawData = length,
VirtualAddress = 0,
VirtualSize = length,
}
};
reader.metadata = new DataDirectory (0, length);
reader.ReadMetadata ();
return reader.image;
} catch (EndOfStreamException e) {
throw new BadImageFormatException (stream.value.GetFileName (), e);
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Foundation;
using UIKit;
using XWeather.Clients;
using SettingsStudio;
using XWeather.WeatherBot;
using XWeather.Constants;
namespace XWeather.iOS
{
public partial class WeatherBotVc : UIViewController
{
WuLocation location;
WeatherBot.WeatherBot weatherBot;
WeatherBotState currentState;
public WeatherBotVc (IntPtr handle) : base (handle) { }
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
makePretty ();
cancelButton.Alpha = 0;
weatherBot = new WeatherBot.WeatherBot (PrivateKeys.CognitiveServices.BingSpeech, PrivateKeys.CognitiveServices.Luis);
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
System.Diagnostics.Debug.WriteLine ($"{PresentingViewController?.DefinesPresentationContext}");
if (weatherBot.CognitiveServicesEnabled)
{
weatherBot.StateChanged += WeatherBot_StateChanged;
weatherBot.WeatherRequestUnderstood += WeatherBot_WeatherRequestUnderstood;
weatherBot.ListenForCommand ();
}
else
{
updateViewState (WeatherBotState.Failure);
updateFeedback ("Please see readme file to enable cognitive services");
}
}
public override void ViewWillDisappear (bool animated)
{
weatherBot.StateChanged -= WeatherBot_StateChanged;
weatherBot.WeatherRequestUnderstood -= WeatherBot_WeatherRequestUnderstood;
base.ViewWillDisappear (animated);
}
void WeatherBot_StateChanged (object sender, WeatherBotStateEventArgs e)
{
BeginInvokeOnMainThread (() =>
{
updateViewState (e.State);
if (!string.IsNullOrEmpty (e.Message))
{
updateFeedback (e.Message);
}
});
}
async void WeatherBot_WeatherRequestUnderstood (object sender, WeatherBotRequestEventArgs e)
{
await getLocationForecast (e.Location.entity, e.RequestDateTime, e.UseCurrentLocation);
}
int index = 2;
partial void containerDoubleTapped (NSObject sender)
{
if (index > 4) index = 1;
var state = (WeatherBotState)index;
updateViewState (state);
index++;
}
partial void cancelClicked (NSObject sender) => finish ();
partial void addLocationButtonClicked (NSObject sender)
{
//TODO: need to handle locations that are already added?
if (location != null)
{
WuClient.Shared.AddLocation (location);
finish ();
}
}
partial void tryAgainButtonClicked (NSObject sender)
{
if (weatherBot.CognitiveServicesEnabled)
{
weatherBot.Cancel ();
weatherBot.ListenForCommand ();
}
}
void updateViewState (WeatherBotState state)
{
System.Diagnostics.Debug.WriteLine ($"{state}");
if (currentState != state)
{
currentState = state;
var subview = getViewForState (state);
if (!subview?.IsDescendantOfView (containerView) ?? false)
{
var current = containerView.Subviews.FirstOrDefault (v => v.Tag > 0);
subview.Alpha = 0;
containerView.AddSubview (subview);
subview.ConstrainToFitParent (containerView);
if (current == null)
{
UIView.Animate (0.2, () =>
{
subview.Alpha = 1;
if (cancelButton.Alpha < 1) cancelButton.Alpha = 1;
}, () =>
{
subview.Alpha = 1;
});
}
else
{
UIView.Animate (0.2, () =>
{
current.Alpha = 0;
}, () =>
{
UIView.Animate (0.2, () =>
{
subview.Alpha = 1;
if (cancelButton.Alpha < 1) cancelButton.Alpha = 1;
}, () =>
{
current.RemoveFromSuperview ();
});
});
}
}
}
}
void updateFeedback (string feedback)
{
switch (currentState)
{
case WeatherBotState.Listening:
listeningFeedbackLabel.Text = feedback;
break;
case WeatherBotState.Working:
workingFeedbackLabel.Text = feedback;
break;
case WeatherBotState.Failure:
failureReasonLabel.Text = feedback;
break;
case WeatherBotState.Success:
successCalloutLabel.Text = feedback;
break;
}
}
UIView getViewForState (WeatherBotState state) => getViewForState ((int)state);
UIView getViewForState (nint state)
{
if (state < 1 || state > 4) return null;
return botStateViews.FirstOrDefault (v => v.Tag == state);
}
void finish ()
{
weatherBot.Cancel ();
DismissViewController (true, null);
}
// "entity": "Fort Thomas, KY"
// "entity": "Fort Thomas Kentucky"
// "entity": "Paris, France"
async Task getLocationForecast (string entity, DateTime? date = null, bool useCurrentLocation = false)
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
if (useCurrentLocation)
{
location = WuClient.Shared.Selected;
}
else
{
// this gets the location without adding it to the saved locations
location = await WuClient.Shared.SearchLocation (entity);
}
var forecastString = location?.ForecastString (Settings.UomTemperature, date);
BeginInvokeOnMainThread (() =>
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (string.IsNullOrEmpty (forecastString))
{
updateViewState (WeatherBotState.Failure);
weatherBot.Speak ($"Unable to find weather forecast for {entity}", true);
updateFeedback ($"Unable to find weather forecast for {entity}");
}
else
{
System.Diagnostics.Debug.WriteLine ($"{forecastString}");
updateViewState (WeatherBotState.Success);
updateFeedback ($"Would you like to add {location.Name} to your saved locations?");
weatherBot.Speak (forecastString, true);
}
});
}
void makePretty ()
{
foreach (var button in new UIButton [] { cancelButton, tryAgainButton, addLocationButton })
{
button.Layer.BorderWidth = 1;
button.Layer.BorderColor = button.TitleColor (UIControlState.Normal).CGColor;
button.Layer.CornerRadius = 3;
}
backgroundView.Layer.CornerRadius = 5;
backgroundView.Layer.MasksToBounds = true;
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using log4net;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Dream.Services {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch Dream Directory", "Copyright (c) 2006-2011 MindTouch, Inc.",
Info = "http://developer.mindtouch.com/Dream/Reference/Services/Directory",
SID = new string[] {
"sid://mindtouch.com/2007/03/dream/directory",
"http://services.mindtouch.com/dream/stable/2007/03/directory"
}
)]
[DreamServiceConfig("parent", "uri?", "Uri to parent directory service for hierarchical look-up.")]
[DreamServiceConfig("filestorage-path", "string?", "Parent directory on filesystem for storing directory records.")]
internal class DirectoryService : DreamService {
//--- Constants ---
public const string TIME_TO_LIVE = "ttl";
//--- Types ---
public class DirectoryRecord {
//--- Fields ---
public string Name;
public DateTime Expiration = DateTime.MaxValue;
public XDoc Value;
//--- Properties ---
public bool HasExpiration { get { return Expiration != DateTime.MaxValue; } }
//--- Methods ---
public XDoc ToXDoc() {
XDoc result = new XDoc("record");
result.Elem("name", Name);
if(Expiration != DateTime.MaxValue) {
result.Elem("expiration", Expiration);
}
result.Start("value").Add(Value).End();
return result;
}
}
// --- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private Plug _parent = null;
private Dictionary<string, DirectoryRecord> _directory = new Dictionary<string, DirectoryRecord>(StringComparer.OrdinalIgnoreCase);
private Plug _events;
//--- Features ---
[DreamFeature("GET:records", "Get list of all records.")]
public Yield GetAllRecords(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc result = new XDoc("list");
lock(_directory) {
foreach(KeyValuePair<string, DirectoryRecord> entry in _directory) {
result.Add(entry.Value.ToXDoc());
}
}
response.Return(DreamMessage.Ok(result));
yield break;
}
[DreamFeature("GET:records/{name}", "Get record from directory.")]
public Yield GetRecord(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc doc = null;
string name = context.GetSuffix(0, UriPathFormat.Normalized);
lock(_directory) {
DirectoryRecord record;
if(_directory.TryGetValue(name, out record)) {
doc = record.Value;
}
}
// check if we should look into a parent directory
if(doc == null) {
if(_parent != null) {
Result<DreamMessage> result;
yield return result = _parent.At("records", context.GetSuffix(0, UriPathFormat.Normalized)).Get(new Result<DreamMessage>(TimeSpan.MaxValue));
if(!result.Value.IsSuccessful) {
// respond with the error code we received
response.Return(result.Value);
yield break;
}
doc = result.Value.ToDocument();
} else {
response.Return(DreamMessage.NotFound("record not found"));
yield break;
}
}
response.Return(DreamMessage.Ok(doc));
yield break;
}
[DreamFeature("PUT:records/{name}", "Add record to directory.")]
[DreamFeatureParam("ttl", "int", "time-to-live in seconds for the added record")]
public Yield PutRecord(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
DirectoryRecord record = new DirectoryRecord();
record.Name = context.GetSuffix(0, UriPathFormat.Normalized);
record.Value = request.ToDocument();
int ttl = context.GetParam<int>(TIME_TO_LIVE, -1);
if(ttl >= 0) {
record.Expiration = DateTime.UtcNow.AddSeconds(ttl);
}
// add value to directory
InsertRecord(record);
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("DELETE:records/{name}", "Delete record from directory.")]
public Yield DeleteRecord(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
string name = context.GetSuffix(0, UriPathFormat.Normalized);
DeleteRecord(name);
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("POST:subscribe", "Subscribe to directory change notifications.")]
public Yield PostSubscribeEvents(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return context.Relay(_events.At("subscribe"), request, response);
}
[DreamFeature("POST:unsubscribe", "Unsubscribe from directory change notifications.")]
public Yield PostUnsubscribeEvents(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
yield return context.Relay(_events.At("unsubscribe"), request, response);
}
[DreamFeature("POST:update", "Process a directory change notification")]
public Yield Update(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
XDoc update = request.ToDocument();
switch(update.Name.ToLowerInvariant()) {
case "insert":
DirectoryRecord record = new DirectoryRecord();
record.Name = update["@name"].Contents;
record.Expiration = update["@expire"].AsDate ?? DateTime.MaxValue;
record.Value = update[0];
InsertRecord(record);
break;
case "delete":
string name = update["@name"].Contents;
DeleteRecord(name);
break;
}
response.Return(DreamMessage.Ok());
yield break;
}
//--- Methods ---
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
_parent = Plug.New(Config["parent"].AsUri);
yield return CreateService("events", "sid://mindtouch.com/2007/03/dream/events", null, new Result<Plug>()).Set(v => _events = v);
LoadRecordsFromFileSystem();
result.Return();
}
protected override Yield Stop(Result result) {
if(_events != null) {
yield return _events.Delete(new Result<DreamMessage>(TimeSpan.MaxValue)).CatchAndLog(_log);
_events = null;
}
yield return Coroutine.Invoke(base.Stop, new Result());
result.Return();
}
private void InsertRecord(DirectoryRecord record) {
// add value to directory
lock(_directory) {
_directory[record.Name] = record;
}
// check if value has an expiration time
if(record.HasExpiration) {
TimerFactory.New(record.Expiration, OnExpire, record.Name, TaskEnv.New());
}
SaveToFileSystem(record.Name, record.Value);
// notify event channel
XDoc notify = new XDoc("insert").Attr("name", record.Name);
if(record.HasExpiration) {
notify.Attr("expire", record.Expiration);
}
notify.Add(record.Value);
_events.Post(notify, new Result<DreamMessage>(TimeSpan.MaxValue));
}
private bool DeleteRecord(string name) {
bool result;
lock(_directory) {
result = _directory.Remove(name);
}
DeleteFromFileSystem(name);
// notify event channel
_events.Post(new XDoc("delete").Attr("name", name), new Result<DreamMessage>(TimeSpan.MaxValue));
return result;
}
private void OnExpire(TaskTimer timer) {
string name = (string)timer.State;
lock(_directory) {
// check if the record still exists
DirectoryRecord record;
if(_directory.TryGetValue(name, out record)) {
// verify if the record should still be deleted
if(record.Expiration <= timer.When) {
_directory.Remove(record.Name);
} else {
timer.Change(record.Expiration, TaskEnv.Clone());
}
}
}
}
private void LoadRecordsFromFileSystem() {
string storagePath = Config["filestorage-path"].AsText;
if (string.IsNullOrEmpty(storagePath))
return;
if (!System.IO.Directory.Exists(storagePath))
return;
string[] files =
System.IO.Directory.GetFiles(storagePath, "*.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files != null) {
foreach (string file in files) {
try {
DirectoryRecord record = new DirectoryRecord();
record.Name = System.IO.Path.GetFileNameWithoutExtension(file);
record.Value = XDocFactory.LoadFrom(file, MimeType.XML);
_directory[record.Name] = record;
}
catch (Exception) {
System.IO.File.Delete(file);
}
}
}
}
private XDoc RetrieveFromFileSystem(string key) {
string fullPath = BuildSavePath(key);
if (fullPath != null && System.IO.File.Exists(fullPath))
return XDocFactory.LoadFrom(fullPath, MimeType.XML);
else
return null;
}
private void SaveToFileSystem(string key, XDoc doc) {
string fullPath = BuildSavePath(key);
if (fullPath != null && doc != null)
doc.Save(fullPath);
}
private void DeleteFromFileSystem(string key) {
string fullPath = BuildSavePath(key);
if (fullPath != null && System.IO.File.Exists(fullPath))
System.IO.File.Delete(fullPath);
}
private string BuildSavePath(string key) {
if (string.IsNullOrEmpty(key))
return null;
string storagePath = Config["filestorage-path"].AsText;
if (string.IsNullOrEmpty(storagePath))
return null;
if (!System.IO.Directory.Exists(storagePath))
return null;
return System.IO.Path.Combine(storagePath, key + ".xml");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace HostMe.Sdk.Client
{
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend.
/// </summary>
public class ApiClient
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (http://hostme-services-dev.azurewebsites.net).
/// </summary>
public ApiClient()
{
Configuration = Configuration.Default;
RestClient = new RestClient("http://hostme-services-dev.azurewebsites.net");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (http://hostme-services-dev.azurewebsites.net).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
if (config == null)
Configuration = Configuration.Default;
else
Configuration = config;
RestClient = new RestClient("http://hostme-services-dev.azurewebsites.net");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath = "http://hostme-services-dev.azurewebsites.net")
{
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
RestClient = new RestClient(basePath);
Configuration = Configuration.Default;
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model or byte[]) parameter
{
if (postBody.GetType() == typeof(String))
{
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
}
else if (postBody.GetType() == typeof(byte[]))
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
}
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
// set timeout
RestClient.Timeout = Configuration.Timeout;
// set user agent
RestClient.UserAgent = Configuration.UserAgent;
var response = RestClient.Execute(request);
return (Object) response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
var response = await RestClient.ExecuteTaskAsync(request);
return (Object)response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
else if (obj is DateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
IList<Parameter> headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public String SelectHeaderAccept(String[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return String.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
}
}
| |
//
// AnimationManager.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 Aaron Bockover
//
// 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 Hyena.Gui.Theatrics;
namespace Hyena.Gui.Canvas
{
public abstract class Animation
{
private Stage<Animation> stage;
internal protected Stage<Animation> Stage {
get { return stage; }
set { stage = value; }
}
private Actor<Animation> actor;
internal protected Actor<Animation> Actor {
get { return actor; }
set { actor = value; }
}
private uint duration = 1000;
public uint Duration {
get { return duration; }
set {
duration = value;
if (Actor != null) {
Actor.Reset (duration);
}
}
}
private CanvasItem item;
public CanvasItem Item {
get { return item; }
set { item = value; }
}
private string property;
public string Property {
get { return property; }
set { property = value; }
}
private bool is_expired;
public bool IsExpired {
get { return is_expired; }
set {
is_expired = value;
iterations = 0;
}
}
private int iterations;
private int repeat_times;
public int RepeatTimes {
get { return repeat_times; }
set { repeat_times = value; }
}
public virtual void Start ()
{
if (Stage.Contains (this)) {
Actor.Reset (Duration);
return;
}
Actor = Stage.Add (this, Duration);
IsExpired = false;
Actor.CanExpire = false;
}
public virtual bool Step (Actor<Animation> actor)
{
if (RepeatTimes > 0 && actor.Percent == 1) {
if (++iterations >= RepeatTimes) {
IsExpired = true;
}
}
return !IsExpired;
}
}
public delegate T AnimationComposeHandler<T> (Animation<T> animation, double percent);
public abstract class Animation<T> : Animation
{
private AnimationComposeHandler<T> compose_handler;
protected AnimationComposeHandler<T> ComposeHandler {
get { return compose_handler; }
}
private Easing easing = Easing.Linear;
protected Easing Easing {
get { return easing; }
}
private bool from_set;
protected bool FromSet {
get { return from_set; }
}
private T from_value;
public T FromValue {
get { return from_value; }
set {
from_set = true;
from_value = value;
}
}
private T to_value;
public T ToValue {
get { return to_value; }
set { to_value = value; }
}
private T start_state;
public T StartState {
get { return start_state; }
protected set { start_state = value; }
}
public override void Start ()
{
T check_state = FromSet ? FromValue : (T)Item[Property];
if (!check_state.Equals (ToValue)) {
base.Start ();
}
}
public Animation<T> ClearFromValue ()
{
from_set = false;
from_value = default (T);
return this;
}
public Animation<T> Animate ()
{
StartState = FromSet ? FromValue : (T)Item[Property];
return this;
}
public Animation<T> Animate (T toValue)
{
ClearFromValue ();
ToValue = toValue;
return Animate ();
}
public Animation<T> Animate (T fromValue, T toValue)
{
FromValue = fromValue;
ToValue = toValue;
return Animate ();
}
public Animation<T> Animate (string property, T toValue)
{
Property = property;
return Animate (toValue);
}
public Animation<T> Animate (string property, T fromValue, T toValue)
{
Property = property;
return Animate (fromValue, toValue);
}
public Animation<T> Compose (AnimationComposeHandler<T> handler)
{
compose_handler = handler;
return this;
}
public Animation<T> ClearCompose ()
{
compose_handler = null;
return this;
}
public Animation<T> To (T toValue)
{
ToValue = toValue;
return Animate ();
}
public Animation<T> From (T fromValue)
{
FromValue = fromValue;
return Animate ();
}
public Animation<T> Reverse ()
{
T from = FromValue;
FromValue = ToValue;
ToValue = from;
return Animate ();
}
public Animation<T> Ease (Easing easing)
{
this.easing = easing;
return this;
}
public Animation<T> Throttle (uint duration)
{
Duration = duration;
return this;
}
public Animation<T> Repeat (int count)
{
RepeatTimes = count;
return this;
}
public Animation<T> Expire ()
{
IsExpired = true;
return this;
}
}
public class DoubleAnimation : Animation<double>
{
public DoubleAnimation ()
{
}
public DoubleAnimation (string property)
{
Property = property;
}
public override bool Step (Actor<Animation> actor)
{
double result = ComposeHandler == null
? StartState + (ToValue * actor.Percent)
: ComposeHandler (this, actor.Percent);
result = Easing == Easing.Linear
? result
: Choreographer.Compose (result, Easing);
Item.SetValue<double> (Property, result);
return base.Step (actor);
}
}
public class AnimationManager
{
private static AnimationManager instance;
public static AnimationManager Instance {
get { return instance ?? (instance = new AnimationManager ()); }
}
private Stage<Animation> stage = new Stage<Animation> ();
public AnimationManager ()
{
stage.Play ();
stage.ActorStep += (actor) => actor.Target.Step (actor);
}
public void Animate (Animation animation)
{
animation.Stage = stage;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Setup
{
partial class WebPage
{
/// <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.grpWebSiteSettings = new System.Windows.Forms.GroupBox();
this.lblHint = new System.Windows.Forms.Label();
this.cbWebSiteIP = new System.Windows.Forms.ComboBox();
this.lblWebSiteTcpPort = new System.Windows.Forms.Label();
this.txtWebSiteTcpPort = new System.Windows.Forms.TextBox();
this.lblWebSiteIP = new System.Windows.Forms.Label();
this.lblWebSiteDomain = new System.Windows.Forms.Label();
this.txtWebSiteDomain = new System.Windows.Forms.TextBox();
this.txtAddress = new System.Windows.Forms.TextBox();
this.lblWarning = new System.Windows.Forms.Label();
this.grpWebSiteSettings.SuspendLayout();
this.SuspendLayout();
//
// grpWebSiteSettings
//
this.grpWebSiteSettings.Controls.Add(this.lblHint);
this.grpWebSiteSettings.Controls.Add(this.cbWebSiteIP);
this.grpWebSiteSettings.Controls.Add(this.lblWebSiteTcpPort);
this.grpWebSiteSettings.Controls.Add(this.txtWebSiteTcpPort);
this.grpWebSiteSettings.Controls.Add(this.lblWebSiteIP);
this.grpWebSiteSettings.Controls.Add(this.lblWebSiteDomain);
this.grpWebSiteSettings.Controls.Add(this.txtWebSiteDomain);
this.grpWebSiteSettings.Location = new System.Drawing.Point(40, 33);
this.grpWebSiteSettings.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.grpWebSiteSettings.Name = "grpWebSiteSettings";
this.grpWebSiteSettings.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.grpWebSiteSettings.Size = new System.Drawing.Size(528, 174);
this.grpWebSiteSettings.TabIndex = 0;
this.grpWebSiteSettings.TabStop = false;
this.grpWebSiteSettings.Text = "Web Site Settings";
//
// lblHint
//
this.lblHint.Location = new System.Drawing.Point(40, 143);
this.lblHint.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblHint.Name = "lblHint";
this.lblHint.Size = new System.Drawing.Size(440, 20);
this.lblHint.TabIndex = 6;
this.lblHint.Text = "Example: www.contoso.com or panel.contoso.com";
//
// cbWebSiteIP
//
this.cbWebSiteIP.Location = new System.Drawing.Point(44, 50);
this.cbWebSiteIP.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.cbWebSiteIP.Name = "cbWebSiteIP";
this.cbWebSiteIP.Size = new System.Drawing.Size(292, 24);
this.cbWebSiteIP.TabIndex = 1;
this.cbWebSiteIP.TextChanged += new System.EventHandler(this.OnAddressChanged);
//
// lblWebSiteTcpPort
//
this.lblWebSiteTcpPort.Location = new System.Drawing.Point(352, 27);
this.lblWebSiteTcpPort.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblWebSiteTcpPort.Name = "lblWebSiteTcpPort";
this.lblWebSiteTcpPort.Size = new System.Drawing.Size(128, 20);
this.lblWebSiteTcpPort.TabIndex = 2;
this.lblWebSiteTcpPort.Text = "Port:";
//
// txtWebSiteTcpPort
//
this.txtWebSiteTcpPort.Location = new System.Drawing.Point(356, 50);
this.txtWebSiteTcpPort.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtWebSiteTcpPort.Name = "txtWebSiteTcpPort";
this.txtWebSiteTcpPort.Size = new System.Drawing.Size(63, 22);
this.txtWebSiteTcpPort.TabIndex = 3;
this.txtWebSiteTcpPort.TextChanged += new System.EventHandler(this.OnAddressChanged);
//
// lblWebSiteIP
//
this.lblWebSiteIP.Location = new System.Drawing.Point(40, 27);
this.lblWebSiteIP.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblWebSiteIP.Name = "lblWebSiteIP";
this.lblWebSiteIP.Size = new System.Drawing.Size(139, 20);
this.lblWebSiteIP.TabIndex = 0;
this.lblWebSiteIP.Text = "IP address:";
//
// lblWebSiteDomain
//
this.lblWebSiteDomain.Location = new System.Drawing.Point(40, 91);
this.lblWebSiteDomain.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblWebSiteDomain.Name = "lblWebSiteDomain";
this.lblWebSiteDomain.Size = new System.Drawing.Size(112, 20);
this.lblWebSiteDomain.TabIndex = 4;
this.lblWebSiteDomain.Text = "Host name:";
//
// txtWebSiteDomain
//
this.txtWebSiteDomain.Location = new System.Drawing.Point(44, 114);
this.txtWebSiteDomain.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtWebSiteDomain.Name = "txtWebSiteDomain";
this.txtWebSiteDomain.Size = new System.Drawing.Size(435, 22);
this.txtWebSiteDomain.TabIndex = 5;
this.txtWebSiteDomain.TextChanged += new System.EventHandler(this.OnAddressChanged);
//
// txtAddress
//
this.txtAddress.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtAddress.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.txtAddress.Location = new System.Drawing.Point(40, 10);
this.txtAddress.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtAddress.Name = "txtAddress";
this.txtAddress.ReadOnly = true;
this.txtAddress.Size = new System.Drawing.Size(528, 16);
this.txtAddress.TabIndex = 2;
//
// lblWarning
//
this.lblWarning.Location = new System.Drawing.Point(40, 210);
this.lblWarning.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblWarning.Name = "lblWarning";
this.lblWarning.Size = new System.Drawing.Size(528, 44);
this.lblWarning.TabIndex = 1;
this.lblWarning.Text = "Make sure the specified host name is pointed to this web site; otherwise y" +
"ou might not be able to access the application.\r\n";
//
// WebPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lblWarning);
this.Controls.Add(this.grpWebSiteSettings);
this.Controls.Add(this.txtAddress);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "WebPage";
this.Size = new System.Drawing.Size(609, 281);
this.grpWebSiteSettings.ResumeLayout(false);
this.grpWebSiteSettings.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox grpWebSiteSettings;
private System.Windows.Forms.Label lblWebSiteTcpPort;
private System.Windows.Forms.TextBox txtWebSiteTcpPort;
private System.Windows.Forms.Label lblWebSiteIP;
private System.Windows.Forms.Label lblWebSiteDomain;
private System.Windows.Forms.TextBox txtWebSiteDomain;
private System.Windows.Forms.TextBox txtAddress;
private System.Windows.Forms.Label lblWarning;
private System.Windows.Forms.ComboBox cbWebSiteIP;
private System.Windows.Forms.Label lblHint;
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
public sealed class BitwiseBinary : BinaryOp{
private Object metaData = null;
internal BitwiseBinary(Context context, AST operand1, AST operand2, JSToken operatorTok)
: base(context, operand1, operand2, operatorTok) {
}
public BitwiseBinary(int operatorTok)
: base(null, null, null, (JSToken)operatorTok){
}
internal override Object Evaluate(){
return this.EvaluateBitwiseBinary(this.operand1.Evaluate(), this.operand2.Evaluate());
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
public Object EvaluateBitwiseBinary(Object v1, Object v2){
if (v1 is Int32 && v2 is Int32)
return DoOp((Int32)v1, (Int32)v2, this.operatorTok);
else
return EvaluateBitwiseBinary(v1, v2, this.operatorTok);
}
#if !DEBUG
[DebuggerStepThroughAttribute]
[DebuggerHiddenAttribute]
#endif
private Object EvaluateBitwiseBinary(Object v1, Object v2, JSToken operatorTok){
IConvertible ic1 = Convert.GetIConvertible(v1);
IConvertible ic2 = Convert.GetIConvertible(v2);
TypeCode t1 = Convert.GetTypeCode(v1, ic1);
TypeCode t2 = Convert.GetTypeCode(v2, ic2);
switch (t1){
case TypeCode.Empty:
case TypeCode.DBNull:
return EvaluateBitwiseBinary(0, v2, operatorTok);
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
int i = ic1.ToInt32(null);
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
return DoOp(i, 0, operatorTok);
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
return DoOp(i, ic2.ToInt32(null), operatorTok);
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
return DoOp(i, (int)Runtime.DoubleToInt64(ic2.ToDouble(null)), operatorTok);
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
i = (int)Runtime.DoubleToInt64(ic1.ToDouble(null));
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
return DoOp(i, 0, operatorTok);
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
return DoOp(i, ic2.ToInt32(null), operatorTok);
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
return DoOp(i, (int)Runtime.DoubleToInt64(ic2.ToDouble(null)), operatorTok);
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
if (v2 == null) return DoOp(Convert.ToInt32(v1), 0, this.operatorTok);
MethodInfo oper = this.GetOperator(v1.GetType(), v2.GetType());
if (oper != null)
return oper.Invoke(null, (BindingFlags)0, JSBinder.ob, new Object[]{v1, v2}, null);
else
return DoOp(Convert.ToInt32(v1), Convert.ToInt32(v2), this.operatorTok);
}
internal static Object DoOp(int i, int j, JSToken operatorTok){
switch (operatorTok){
case JSToken.BitwiseAnd:
return i & j;
case JSToken.BitwiseOr:
return i | j;
case JSToken.BitwiseXor:
return i ^ j;
case JSToken.LeftShift:
return i << j;
case JSToken.RightShift:
return i >> j;
case JSToken.UnsignedRightShift:
return ((uint)i) >> j;
default:
throw new JScriptException(JSError.InternalError);
}
}
internal override IReflect InferType(JSField inference_target){
MethodInfo oper;
if (this.type1 == null || inference_target != null){
oper = this.GetOperator(this.operand1.InferType(inference_target), this.operand2.InferType(inference_target));
}else
oper = this.GetOperator(this.type1, this.type2);
if (oper != null){
this.metaData = oper;
return oper.ReturnType;
}
return BitwiseBinary.ResultType(this.type1, this.type2, this.operatorTok);
}
internal static Type Operand2Type(JSToken operatorTok, Type bbrType){
switch (operatorTok){
case JSToken.LeftShift:
case JSToken.RightShift:
case JSToken.UnsignedRightShift:
return Typeob.Int32;
}
return bbrType;
}
internal static Type ResultType(Type type1, Type type2, JSToken operatorTok){
switch (operatorTok){
case JSToken.LeftShift:
case JSToken.RightShift:
if (Convert.IsPrimitiveIntegerType(type1))
return type1;
else if (Typeob.JSObject.IsAssignableFrom(type1))
return Typeob.Int32;
else
return Typeob.Object;
case JSToken.UnsignedRightShift:
switch(Type.GetTypeCode(type1)){
case TypeCode.Byte:
case TypeCode.SByte: return Typeob.Byte;
case TypeCode.UInt16:
case TypeCode.Int16: return Typeob.UInt16;
case TypeCode.Int32:
case TypeCode.UInt32: return Typeob.UInt32;
case TypeCode.Int64:
case TypeCode.UInt64: return Typeob.UInt64;
default:
if (Typeob.JSObject.IsAssignableFrom(type1))
return Typeob.Int32;
else
return Typeob.Object;
}
}
TypeCode t1 = Type.GetTypeCode(type1);
TypeCode t2 = Type.GetTypeCode(type2);
switch (t1){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
switch (t2){
case TypeCode.SByte:
return Typeob.SByte;
case TypeCode.Byte:
return Typeob.Byte;
case TypeCode.Char:
case TypeCode.UInt16:
return Typeob.UInt16;
case TypeCode.Int16:
return Typeob.Int16;
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.Int32;
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
return Typeob.Int64;
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.Int32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.SByte:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.SByte:
return Typeob.SByte;
case TypeCode.Byte:
return Typeob.Byte;
case TypeCode.Char:
case TypeCode.Int16:
return Typeob.Int16;
case TypeCode.UInt16:
return Typeob.UInt16;
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.Int32;
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
return Typeob.Int64;
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.Int32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Byte:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.SByte:
return Typeob.Byte;
case TypeCode.Char:
case TypeCode.UInt16:
case TypeCode.Int16:
return Typeob.UInt16;
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.UInt32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Int16:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
return Typeob.Int16;
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
return Typeob.UInt16;
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.Int32;
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
return Typeob.Int64;
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.Int32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Char:
case TypeCode.UInt16:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
case TypeCode.SByte:
case TypeCode.Int16:
return Typeob.UInt16;
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.UInt32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.Int32;
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
case TypeCode.UInt32:
return Typeob.UInt32;
case TypeCode.Int64:
return Typeob.Int64;
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.Int32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.UInt32:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.Char:
case TypeCode.UInt32:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.UInt32;
case TypeCode.Int64:
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.UInt32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Int64:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
return Typeob.Int64;
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.Int64;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.UInt64:
switch (t2){
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Int64:
return Typeob.UInt64;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type2)) return Typeob.UInt64;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
break;
case TypeCode.Object:
if (Typeob.JSObject.IsAssignableFrom(type1)) return Typeob.Int32;
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.String:
break;
}
return Typeob.Object;
}
internal static void TranslateToBitCountMask(ILGenerator il, Type type, AST operand2){
int mask = 0;
switch (Type.GetTypeCode(type)){
case TypeCode.SByte:
case TypeCode.Byte:
mask = 7; break;
case TypeCode.UInt16:
case TypeCode.Int16:
mask = 15; break;
case TypeCode.Int32:
case TypeCode.UInt32:
mask = 31; break;
case TypeCode.Int64:
case TypeCode.UInt64:
mask = 63; break;
}
ConstantWrapper cw = operand2 as ConstantWrapper;
if (cw != null){
int m = Convert.ToInt32(cw.value);
if (m <= mask) return;
}
il.Emit(OpCodes.Ldc_I4_S, mask);
il.Emit(OpCodes.And);
}
internal override void TranslateToIL(ILGenerator il, Type rtype){
if (this.metaData == null){
Type bbrType = BitwiseBinary.ResultType(this.type1, this.type2, this.operatorTok);
if (Convert.IsPrimitiveNumericType(this.type1)){
this.operand1.TranslateToIL(il, this.type1);
Convert.Emit(this, il, this.type1, bbrType, true);
}else{
this.operand1.TranslateToIL(il, Typeob.Double);
Convert.Emit(this, il, Typeob.Double, bbrType, true);
}
Type op2type = BitwiseBinary.Operand2Type(this.operatorTok, bbrType);
if (Convert.IsPrimitiveNumericType(this.type2)){
this.operand2.TranslateToIL(il, this.type2);
Convert.Emit(this, il, this.type2, op2type, true);
}else{
this.operand2.TranslateToIL(il, Typeob.Double);
Convert.Emit(this, il, Typeob.Double, op2type, true);
}
switch (this.operatorTok){
case JSToken.BitwiseAnd:
il.Emit(OpCodes.And);
break;
case JSToken.BitwiseOr:
il.Emit(OpCodes.Or);
break;
case JSToken.BitwiseXor:
il.Emit(OpCodes.Xor);
break;
case JSToken.LeftShift:
BitwiseBinary.TranslateToBitCountMask(il, bbrType, this.operand2);
il.Emit(OpCodes.Shl);
break;
case JSToken.RightShift:
BitwiseBinary.TranslateToBitCountMask(il, bbrType, this.operand2);
il.Emit(OpCodes.Shr);
break;
case JSToken.UnsignedRightShift:
BitwiseBinary.TranslateToBitCountMask(il, bbrType, this.operand2);
il.Emit(OpCodes.Shr_Un);
break;
default:
throw new JScriptException(JSError.InternalError, this.context);
}
Convert.Emit(this, il, bbrType, rtype);
return;
}
if (this.metaData is MethodInfo){
MethodInfo oper = (MethodInfo)this.metaData;
ParameterInfo[] pars = oper.GetParameters();
this.operand1.TranslateToIL(il, pars[0].ParameterType);
this.operand2.TranslateToIL(il, pars[1].ParameterType);
il.Emit(OpCodes.Call, oper);
Convert.Emit(this, il, oper.ReturnType, rtype);
return;
}
//Getting here is just too bad. We do not know until the code runs whether or not to call an overloaded operator method.
//Compile operands to objects and devolve the decision making to run time thunks
il.Emit(OpCodes.Ldloc, (LocalBuilder)this.metaData);
this.operand1.TranslateToIL(il, Typeob.Object);
this.operand2.TranslateToIL(il, Typeob.Object);
il.Emit(OpCodes.Call, CompilerGlobals.evaluateBitwiseBinaryMethod);
Convert.Emit(this, il, Typeob.Object, rtype);
}
internal override void TranslateToILInitializer(ILGenerator il){
IReflect rtype = this.InferType(null);
this.operand1.TranslateToILInitializer(il);
this.operand2.TranslateToILInitializer(il);
if (rtype != Typeob.Object)
return;
this.metaData = il.DeclareLocal(Typeob.BitwiseBinary);
ConstantWrapper.TranslateToILInt(il, (int)this.operatorTok);
il.Emit(OpCodes.Newobj, CompilerGlobals.bitwiseBinaryConstructor);
il.Emit(OpCodes.Stloc, (LocalBuilder)this.metaData);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using BuildIt.ServiceLocation;
using BuildIt.States;
using BuildIt.States.Interfaces;
using BuildIt.States.Interfaces.StateData;
using BuildIt.States.Typed;
using BuildIt.States.Typed.Enum;
namespace BuildIt.Lifecycle.States.ViewModel
{
public interface IViewModelStateGroupDefinition<TState, TStateDefinition> : ITypedStateGroupDefinition<TState, TStateDefinition>
where TState : struct
where TStateDefinition : class, ITypedStateDefinition<TState>, new()
{
IViewModelStateDefinition<TState, TViewModel> DefineViewModelState<TViewModel>(TState state)
where TViewModel : INotifyPropertyChanged;
IViewModelStateDefinition<TState, TViewModel> DefineViewModelState<TViewModel>(
IViewModelStateDefinition<TState, TViewModel> stateDefinition)
where TViewModel : INotifyPropertyChanged;
}
public class ViewModelStateGroupDefinition<TState>
: EnumStateGroupDefinition<TState> //, IViewModelStateGroupDefinition<TState, TStateDefinition>
where TState : struct
//where TStateDefinition : EnumStateDefinition<TState>, new()
{
//private const string ErrorDontUseDefineState =
// "Use DefineViewModelState instead of DefineState for ViewModelStateManager";
//public override ITypedStateDefinition<TState> DefineTypedState(TState state)
//{
// throw new Exception(ErrorDontUseDefineState);
//}
//public override ITypedStateDefinition<TState> DefineTypedState(ITypedStateDefinition<TState> stateDefinition)
//{
// if (stateDefinition.GetType().GetGenericTypeDefinition() != typeof(ViewModelStateDefinition<,>)) throw new Exception(ErrorDontUseDefineState);
// return base.DefineTypedState(stateDefinition);
//}
public IViewModelStateDefinition<TState, TViewModel> DefineViewModelState<TViewModel>(TState state)
where TViewModel : INotifyPropertyChanged//, new()
{
var stateDefinition = new ViewModelStateDefinition<TState, TViewModel>(state);
return DefineViewModelState<TViewModel, ViewModelStateDefinition<TState, TViewModel>>(stateDefinition);
}
public IViewModelStateDefinition<TState, TViewModel> DefineViewModelState<TViewModel, TViewModelStateDefinition>(TViewModelStateDefinition stateDefinition)
where TViewModel : INotifyPropertyChanged//, new()
where TViewModelStateDefinition : EnumStateDefinition<TState>, IViewModelStateDefinition<TState, TViewModel>
{
$"Defining state for {typeof(TState).Name} with ViewModel type {typeof(TViewModel)}".Log();
base.DefineTypedState(stateDefinition);
return stateDefinition;
}
}
public class ViewModelStateGroup<TState> :
TypedStateGroup<TState, EnumStateDefinition<TState>, ViewModelStateGroupDefinition<TState>>,
ICanRegisterDependencies,
IRegisterForUIAccess,
IHasCurrentViewModel
where TState : struct
{
public ViewModelStateGroup() : base()
{
TrackHistory = true;
}
public ViewModelStateGroup(ViewModelStateGroupDefinition<TState> groupDefinition) : base(groupDefinition)
{
TrackHistory = true;
}
#region Migrated to StateGroup
private IDictionary<Type, INotifyPropertyChanged> ViewModels { get; } =
new Dictionary<Type, INotifyPropertyChanged>();
public INotifyPropertyChanged CurrentViewModel { get; set; }
public INotifyPropertyChanged Existing(Type viewModelType)
{
if (viewModelType == null) return null;
INotifyPropertyChanged existing;
ViewModels.TryGetValue(viewModelType, out existing);
return existing;
}
public override bool GoToPreviousStateIsBlocked
{
get
{
var isBlocked = base.GoToPreviousStateIsBlocked;
if (isBlocked) return true;
// ReSharper disable once SuspiciousTypeConversion.Global
var isBlockable = CurrentViewModel as IIsAbleToBeBlocked;
return isBlockable?.IsBlocked ?? false;
}
}
//protected override async Task<bool> AboutToChangeFrom(string newState, string data, bool isNewState, bool useTransitions)
//{
// var oldState = CurrentStateName;
// // ReSharper disable once SuspiciousTypeConversion.Global - NOT HELPFUL
// var aboutVM = CurrentViewModel as IAboutToLeaveViewModelState;
// var cancel = new CancelEventArgs();
// if (aboutVM != null)
// {
// "Invoking AboutToLeave".Log();
// await aboutVM.AboutToLeave(cancel);
// if (cancel.Cancel)
// {
// "ChangeToState cancelled by AboutToLeave".Log();
// return false;
// }
// }
// "Retrieving current state definition".Log();
// var currentVMStates = !oldState.Equals(default(TState)) ? TypedGroupDefinition.States[oldState] as IGenerateViewModel : null;
// if (currentVMStates != null)
// {
// "Invoking AboutToChangeFrom for existing state definition".Log();
// await currentVMStates.InvokeAboutToChangeFromViewModel(CurrentViewModel, cancel);
// if (cancel.Cancel)
// {
// "ChangeToState cancelled by existing state definition".Log();
// return false;
// }
// }
// var basecancel = await base.AboutToChangeFrom(newState, data, isNewState, useTransitions);
// return basecancel;
//}
//protected override async Task ChangingFrom(string newState, string dataAsJson, bool isNewState, bool useTransitions)
//{
// var oldState = CurrentStateName;
// // ReSharper disable once SuspiciousTypeConversion.Global // NOT HELPFUL
// var leaving = CurrentViewModel as ILeavingViewModelState;
// if (leaving != null)
// {
// "Invoking Leaving on current view model".Log();
// await leaving.Leaving();
// }
// // ReSharper disable once SuspiciousTypeConversion.Global // NOT HELPFUL
// var isBlockable = CurrentViewModel as IIsAbleToBeBlocked;
// if (isBlockable != null)
// {
// "Detaching event handlers for isblocked on current view model".Log();
// isBlockable.IsBlockedChanged -= IsBlockable_IsBlockedChanged;
// }
// "Retrieving current state definition".Log();
// var currentVMStates = !oldState.Equals(default(TState)) ? TypedGroupDefinition.States[oldState] as IGenerateViewModel : null;
// if (currentVMStates != null)
// {
// "Invoking ChangingFrom on current state definition".Log();
// await currentVMStates.InvokeChangingFromViewModel(CurrentViewModel);
// }
// await base.ChangingFrom(newState, dataAsJson, isNewState, useTransitions);
//}
//protected override async Task ChangeCurrentState(string newState, bool isNewState, bool useTransitions)
//{
// var oldState = CurrentStateName;
// "Invoking ChangeToState to invoke state change".Log();
// await base.ChangeCurrentState(newState, isNewState, useTransitions);
// INotifyPropertyChanged vm = null;
// if (!newState.Equals(default(TState)))
// {
// var current = TypedGroupDefinition.States[newState] as IGenerateViewModel;
// var genType = current?.ViewModelType;
// "Retrieving existing ViewModel for new state".Log();
// vm = Existing(genType);
// }
// if (vm == null)
// {
// var newGen = TypedGroupDefinition.States[newState] as IGenerateViewModel;
// if (newGen == null) return;
// "Generating ViewModel for new state".Log();
// vm = newGen.Generate();
// "Registering dependencies".Log();
// (vm as ICanRegisterDependencies)?.RegisterDependencies(DependencyContainer);
// await newGen.InvokeInitialiseViewModel(vm);
// //if (vm.InitialiseViewModel != null)
// //{
// // "Initialising ViewModel".Log();
// // await InitialiseViewModel(vm);
// //}
// }
// var requireUI = vm as IRegisterForUIAccess;
// requireUI?.RegisterForUIAccess(UIContext);
// ViewModels[vm.GetType()] = vm;
// CurrentViewModel = vm;
// var isBlockable = CurrentViewModel as IIsAbleToBeBlocked;
// if (isBlockable != null)
// {
// isBlockable.IsBlockedChanged += IsBlockable_IsBlockedChanged;
// }
//}
private void IsBlockable_IsBlockedChanged(object sender, EventArgs e)
{
OnGoToPreviousStateIsBlockedChanged();
}
protected override async Task NotifyStateChanged(string newState, bool useTransitions, bool isNewState)
{
await UIContext.RunAsync(async () =>
{
await base.NotifyStateChanged(newState, useTransitions, isNewState);
});
}
//protected override async Task ChangedToState(string oldState, string dataAsJson, bool isNewState, bool useTransitions)
//{
// await base.ChangedToState(oldState, dataAsJson, isNewState, useTransitions);
// // ReSharper disable once SuspiciousTypeConversion.Global // NOT HELPFUL
// var arrived = CurrentViewModel as IArrivingViewModelState;
// if (arrived != null)
// {
// "Invoking Arriving on new ViewModel".Log();
// await arrived.Arriving();
// }
// var currentVMStates = TypedGroupDefinition.States[CurrentStateName] as IGenerateViewModel;
// if (currentVMStates != null)
// {
// "Invoking ChangedTo on new state definition".Log();
// await currentVMStates.InvokeChangedToViewModel(CurrentViewModel);
// await currentVMStates.InvokeChangedToWithDataViewModel(CurrentViewModel, dataAsJson);
// }
//}
//protected override async Task ChangeToStateByNameWithData(string newState, string dataAsJson)
//{
// await base.ChangeToStateByNameWithData(newState,dataAsJson);
// // ReSharper disable once SuspiciousTypeConversion.Global // NOT HELPFUL
// var arrived = CurrentViewModel as IArrivingViewModelState;
// if (arrived != null)
// {
// "Invoking Arriving on new ViewModel".Log();
// await arrived.Arriving();
// }
// var currentVMStates = States[CurrentStateName] as IGenerateViewModel;
// if (currentVMStates != null)
// {
// "Invoking ChangedTo on new state definition".Log();
// await currentVMStates.InvokeChangedToViewModel(CurrentViewModel);
// await currentVMStates.InvokeChangedToWithDataViewModel(CurrentViewModel, dataAsJson);
// }
//}
//protected override async Task ArrivedState(ITransitionDefinition<TState> transition, TState currentState)
//{
// await base.ArrivedState(transition, currentState);
// var trans = transition as ViewModelTransitionDefinition<TState>;
// if (trans?.ArrivedStateViewModel != null)
// {
// await trans.ArrivedStateViewModel(currentState, CurrentViewModel);
// }
//}
//protected override async Task LeavingState(ITransitionDefinition<TState> transition, TState currentState, CancelEventArgs cancel)
//{
// await base.LeavingState(transition, currentState, cancel);
// if (cancel.Cancel) return;
// var trans = transition as ViewModelTransitionDefinition<TState>;
// if (trans?.LeavingStateViewModel != null)
// {
// await trans.LeavingStateViewModel(currentState, CurrentViewModel, cancel);
// }
//}
#endregion
//protected IContainer DependencyContainer { get; private set; }
public void RegisterDependencies(IDependencyContainer container)
{
DependencyContainer = container;
using (DependencyContainer.StartUpdate())
{
//var cb = new ContainerBuilder();
foreach (var state in TypedGroupDefinition.States.Values.OfType<IGenerateViewModel>())
{
DependencyContainer.RegisterType(state.ViewModelType);
//cb.RegisterType(state.ViewModelType);
}
//cb.Update(container);
}
}
public IUIExecutionContext UIContext { get; private set; }
public virtual void RegisterForUIAccess(IUIExecutionContext context)
{
UIContext = context;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
/// <summary>
/// Static class that helps evaluate expressions. This class cannot be inherited.
/// </summary>
public static class ViewDataEvaluator
{
/// <summary>
/// Gets <see cref="ViewDataInfo"/> for named <paramref name="expression"/> in given
/// <paramref name="viewData"/>.
/// </summary>
/// <param name="viewData">
/// The <see cref="ViewDataDictionary"/> that may contain the <paramref name="expression"/> value.
/// </param>
/// <param name="expression">Expression name, relative to <c>viewData.Model</c>.</param>
/// <returns>
/// <see cref="ViewDataInfo"/> for named <paramref name="expression"/> in given <paramref name="viewData"/>.
/// </returns>
public static ViewDataInfo Eval(ViewDataDictionary viewData, string expression)
{
if (viewData == null)
{
throw new ArgumentNullException(nameof(viewData));
}
// While it is not valid to generate a field for the top-level model itself because the result is an
// unnamed input element, do not throw here if full name is null or empty. Support is needed for cases
// such as Html.Label() and Html.Value(), where the user's code is not creating a name attribute. Checks
// are in place at higher levels for the invalid cases.
var fullName = viewData.TemplateInfo.GetFullHtmlFieldName(expression);
// Given an expression "one.two.three.four" we look up the following (pseudo-code):
// this["one.two.three.four"]
// this["one.two.three"]["four"]
// this["one.two"]["three.four]
// this["one.two"]["three"]["four"]
// this["one"]["two.three.four"]
// this["one"]["two.three"]["four"]
// this["one"]["two"]["three.four"]
// this["one"]["two"]["three"]["four"]
// Try to find a matching ViewData entry using the full expression name. If that fails, fall back to
// ViewData.Model using the expression's relative name.
var result = EvalComplexExpression(viewData, fullName);
if (result == null)
{
if (string.IsNullOrEmpty(expression))
{
// Null or empty expression name means current model even if that model is null.
result = new ViewDataInfo(container: viewData, value: viewData.Model);
}
else
{
result = EvalComplexExpression(viewData.Model, expression);
}
}
return result;
}
/// <summary>
/// Gets <see cref="ViewDataInfo"/> for named <paramref name="expression"/> in given
/// <paramref name="indexableObject"/>.
/// </summary>
/// <param name="indexableObject">
/// The <see cref="object"/> that may contain the <paramref name="expression"/> value.
/// </param>
/// <param name="expression">Expression name, relative to <paramref name="indexableObject"/>.</param>
/// <returns>
/// <see cref="ViewDataInfo"/> for named <paramref name="expression"/> in given
/// <paramref name="indexableObject"/>.
/// </returns>
public static ViewDataInfo Eval(object indexableObject, string expression)
{
// Run through many of the same cases as other Eval() overload.
return EvalComplexExpression(indexableObject, expression);
}
private static ViewDataInfo EvalComplexExpression(object indexableObject, string expression)
{
if (indexableObject == null)
{
return null;
}
if (expression == null)
{
// In case a Dictionary indexableObject contains a "" entry, don't short-circuit the logic below.
expression = string.Empty;
}
return InnerEvalComplexExpression(indexableObject, expression);
}
private static ViewDataInfo InnerEvalComplexExpression(object indexableObject, string expression)
{
Debug.Assert(expression != null);
var leftExpression = expression;
do
{
var targetInfo = GetPropertyValue(indexableObject, leftExpression);
if (targetInfo != null)
{
if (leftExpression.Length == expression.Length)
{
// Nothing remaining in expression after leftExpression.
return targetInfo;
}
if (targetInfo.Value != null)
{
var rightExpression = expression.Substring(leftExpression.Length + 1);
targetInfo = InnerEvalComplexExpression(targetInfo.Value, rightExpression);
if (targetInfo != null)
{
return targetInfo;
}
}
}
leftExpression = GetNextShorterExpression(leftExpression);
}
while (!string.IsNullOrEmpty(leftExpression));
return null;
}
// Given "one.two.three.four" initially, calls return
// "one.two.three"
// "one.two"
// "one"
// ""
// Recursion of InnerEvalComplexExpression() further sub-divides these cases to cover the full set of
// combinations shown in Eval(ViewDataDictionary, string) comments.
private static string GetNextShorterExpression(string expression)
{
if (string.IsNullOrEmpty(expression))
{
return string.Empty;
}
var lastDot = expression.LastIndexOf('.');
if (lastDot == -1)
{
return string.Empty;
}
return expression.Substring(startIndex: 0, length: lastDot);
}
private static ViewDataInfo GetIndexedPropertyValue(object indexableObject, string key)
{
var dict = indexableObject as IDictionary<string, object>;
object value = null;
var success = false;
if (dict != null)
{
success = dict.TryGetValue(key, out value);
}
else
{
// Fall back to TryGetValue() calls for other Dictionary types.
var tryDelegate = TryGetValueProvider.CreateInstance(indexableObject.GetType());
if (tryDelegate != null)
{
success = tryDelegate(indexableObject, key, out value);
}
}
if (success)
{
return new ViewDataInfo(indexableObject, value);
}
return null;
}
// This method handles one "segment" of a complex property expression
private static ViewDataInfo GetPropertyValue(object container, string propertyName)
{
// First, try to evaluate the property based on its indexer.
var value = GetIndexedPropertyValue(container, propertyName);
if (value != null)
{
return value;
}
// Do not attempt to find a property with an empty name and or of a ViewDataDictionary.
if (string.IsNullOrEmpty(propertyName) || container is ViewDataDictionary)
{
return null;
}
// If the indexer didn't return anything useful, try to use PropertyInfo and treat the expression
// as a property name.
var propertyInfo = container.GetType().GetRuntimeProperty(propertyName);
if (propertyInfo == null)
{
return null;
}
return new ViewDataInfo(container, propertyInfo);
}
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class VDISizeLocationPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VDISizeLocationPage));
this.SizeLabel = new System.Windows.Forms.Label();
this.locationLabel = new System.Windows.Forms.Label();
this.sizeNUD = new System.Windows.Forms.NumericUpDown();
this.sizeValue = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.sizeValueROLabel = new System.Windows.Forms.Label();
this.labelLocationValueRO = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.labelError = new System.Windows.Forms.Label();
this.initial_allocation_label = new System.Windows.Forms.Label();
this.incremental_allocation_label = new System.Windows.Forms.Label();
this.initial_alloc_value = new System.Windows.Forms.Label();
this.incr_alloc_value = new System.Windows.Forms.Label();
this.panelShutDownHint = new System.Windows.Forms.Panel();
this.labelShutDownWarning = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
((System.ComponentModel.ISupportInitialize)(this.sizeNUD)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
this.panelShutDownHint.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// SizeLabel
//
resources.ApplyResources(this.SizeLabel, "SizeLabel");
this.SizeLabel.Name = "SizeLabel";
//
// locationLabel
//
resources.ApplyResources(this.locationLabel, "locationLabel");
this.locationLabel.Name = "locationLabel";
//
// sizeNUD
//
this.sizeNUD.DecimalPlaces = 3;
resources.ApplyResources(this.sizeNUD, "sizeNUD");
this.sizeNUD.Increment = new decimal(new int[] {
5,
0,
0,
65536});
this.sizeNUD.Maximum = new decimal(new int[] {
-1,
1,
0,
0});
this.sizeNUD.Name = "sizeNUD";
this.sizeNUD.ValueChanged += new System.EventHandler(this.sizeNUD_ValueChanged);
//
// sizeValue
//
resources.ApplyResources(this.sizeValue, "sizeValue");
this.sizeValue.Name = "sizeValue";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.sizeValue, 3, 0);
this.tableLayoutPanel1.Controls.Add(this.locationLabel, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.SizeLabel, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.sizeNUD, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.sizeValueROLabel, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.labelLocationValueRO, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.pictureBoxError, 4, 0);
this.tableLayoutPanel1.Controls.Add(this.labelError, 5, 0);
this.tableLayoutPanel1.Controls.Add(this.initial_allocation_label, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.incremental_allocation_label, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.initial_alloc_value, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.incr_alloc_value, 2, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// sizeValueROLabel
//
resources.ApplyResources(this.sizeValueROLabel, "sizeValueROLabel");
this.sizeValueROLabel.Name = "sizeValueROLabel";
//
// labelLocationValueRO
//
resources.ApplyResources(this.labelLocationValueRO, "labelLocationValueRO");
this.tableLayoutPanel1.SetColumnSpan(this.labelLocationValueRO, 5);
this.labelLocationValueRO.Name = "labelLocationValueRO";
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Image = global::XenAdmin.Properties.Resources._000_error_h32bit_16;
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.ForeColor = System.Drawing.Color.Red;
this.labelError.Name = "labelError";
//
// initial_allocation_label
//
resources.ApplyResources(this.initial_allocation_label, "initial_allocation_label");
this.initial_allocation_label.Name = "initial_allocation_label";
//
// incremental_allocation_label
//
resources.ApplyResources(this.incremental_allocation_label, "incremental_allocation_label");
this.incremental_allocation_label.Name = "incremental_allocation_label";
//
// initial_alloc_value
//
resources.ApplyResources(this.initial_alloc_value, "initial_alloc_value");
this.initial_alloc_value.Name = "initial_alloc_value";
//
// incr_alloc_value
//
resources.ApplyResources(this.incr_alloc_value, "incr_alloc_value");
this.incr_alloc_value.Name = "incr_alloc_value";
//
// panelShutDownHint
//
this.panelShutDownHint.Controls.Add(this.labelShutDownWarning);
this.panelShutDownHint.Controls.Add(this.pictureBox1);
resources.ApplyResources(this.panelShutDownHint, "panelShutDownHint");
this.panelShutDownHint.Name = "panelShutDownHint";
//
// labelShutDownWarning
//
resources.ApplyResources(this.labelShutDownWarning, "labelShutDownWarning");
this.labelShutDownWarning.Name = "labelShutDownWarning";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// VDISizeLocationPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.panelShutDownHint);
this.Controls.Add(this.tableLayoutPanel2);
this.DoubleBuffered = true;
this.Name = "VDISizeLocationPage";
((System.ComponentModel.ISupportInitialize)(this.sizeNUD)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
this.panelShutDownHint.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label SizeLabel;
private System.Windows.Forms.Label locationLabel;
private System.Windows.Forms.NumericUpDown sizeNUD;
private System.Windows.Forms.Label sizeValue;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label sizeValueROLabel;
private System.Windows.Forms.Panel panelShutDownHint;
private System.Windows.Forms.Label labelShutDownWarning;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label labelLocationValueRO;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.PictureBox pictureBoxError;
private System.Windows.Forms.Label labelError;
private System.Windows.Forms.Label initial_allocation_label;
private System.Windows.Forms.Label incremental_allocation_label;
private System.Windows.Forms.Label initial_alloc_value;
private System.Windows.Forms.Label incr_alloc_value;
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class DockContent : Form, IDockContent
{
public DockContent()
{
m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString));
m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged);
//Suggested as a fix by bensty regarding form resize
this.ParentChanged += new EventHandler(DockContent_ParentChanged);
}
//Suggested as a fix by bensty regarding form resize
private void DockContent_ParentChanged(object Sender, EventArgs e)
{
if (this.Parent != null)
this.Font = this.Parent.Font;
}
private DockContentHandler m_dockHandler = null;
[Browsable(false)]
public DockContentHandler DockHandler
{
get { return m_dockHandler; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get { return DockHandler.AllowEndUserDocking; }
set { DockHandler.AllowEndUserDocking = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_DockAreas_Description")]
[DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)]
public DockAreas DockAreas
{
get { return DockHandler.DockAreas; }
set { DockHandler.DockAreas = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AutoHidePortion_Description")]
[DefaultValue(0.25)]
public double AutoHidePortion
{
get { return DockHandler.AutoHidePortion; }
set { DockHandler.AutoHidePortion = value; }
}
private string m_tabText = null;
[Localizable(true)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabText_Description")]
[DefaultValue(null)]
public string TabText
{
get { return m_tabText; }
set { DockHandler.TabText = m_tabText = value; }
}
private bool ShouldSerializeTabText()
{
return (m_tabText != null);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButton_Description")]
[DefaultValue(true)]
public bool CloseButton
{
get { return DockHandler.CloseButton; }
set { DockHandler.CloseButton = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButtonVisible_Description")]
[DefaultValue(true)]
public bool CloseButtonVisible
{
get { return DockHandler.CloseButtonVisible; }
set { DockHandler.CloseButtonVisible = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPanel DockPanel
{
get { return DockHandler.DockPanel; }
set { DockHandler.DockPanel = value; }
}
private ThemeBase m_Theme;
[Localizable(true)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_Theme")]
[DefaultValue(null)]
public ThemeBase Theme
{
get { return m_Theme; }
set
{
if (m_Theme != value && value != null)
{
m_Theme = value;
m_Theme.Apply(this);
}
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState DockState
{
get { return DockHandler.DockState; }
set { DockHandler.DockState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane Pane
{
get { return DockHandler.Pane; }
set { DockHandler.Pane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsHidden
{
get { return DockHandler.IsHidden; }
set { DockHandler.IsHidden = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState VisibleState
{
get { return DockHandler.VisibleState; }
set { DockHandler.VisibleState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFloat
{
get { return DockHandler.IsFloat; }
set { DockHandler.IsFloat = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane PanelPane
{
get { return DockHandler.PanelPane; }
set { DockHandler.PanelPane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane FloatPane
{
get { return DockHandler.FloatPane; }
set { DockHandler.FloatPane = value; }
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
protected virtual string GetPersistString()
{
return GetType().ToString();
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_HideOnClose_Description")]
[DefaultValue(false)]
public bool HideOnClose
{
get { return DockHandler.HideOnClose; }
set { DockHandler.HideOnClose = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_ShowHint_Description")]
[DefaultValue(DockState.Unknown)]
public DockState ShowHint
{
get { return DockHandler.ShowHint; }
set { DockHandler.ShowHint = value; }
}
[Browsable(false)]
public bool IsActivated
{
get { return DockHandler.IsActivated; }
}
public bool IsDockStateValid(DockState dockState)
{
return DockHandler.IsDockStateValid(dockState);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenu_Description")]
[DefaultValue(null)]
public ContextMenu TabPageContextMenu
{
get { return DockHandler.TabPageContextMenu; }
set { DockHandler.TabPageContextMenu = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")]
[DefaultValue(null)]
public ContextMenuStrip TabPageContextMenuStrip
{
get { return DockHandler.TabPageContextMenuStrip; }
set { DockHandler.TabPageContextMenuStrip = value; }
}
[Localizable(true)]
[Category("Appearance")]
[LocalizedDescription("DockContent_ToolTipText_Description")]
[DefaultValue(null)]
public string ToolTipText
{
get { return DockHandler.ToolTipText; }
set { DockHandler.ToolTipText = value; }
}
public new void Activate()
{
DockHandler.Activate();
}
public new void Hide()
{
DockHandler.Hide();
}
public new void Show()
{
DockHandler.Show();
}
public void Show(DockPanel dockPanel)
{
DockHandler.Show(dockPanel);
}
public void Show(DockPanel dockPanel, DockState dockState)
{
DockHandler.Show(dockPanel, dockState);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void Show(DockPanel dockPanel, Rectangle floatWindowBounds)
{
DockHandler.Show(dockPanel, floatWindowBounds);
}
public void Show(DockPane pane, IDockContent beforeContent)
{
DockHandler.Show(pane, beforeContent);
}
public void Show(DockPane previousPane, DockAlignment alignment, double proportion)
{
DockHandler.Show(previousPane, alignment, proportion);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void FloatAt(Rectangle floatWindowBounds)
{
DockHandler.FloatAt(floatWindowBounds);
}
public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex)
{
DockHandler.DockTo(paneTo, dockStyle, contentIndex);
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
DockHandler.DockTo(panel, dockStyle);
}
#region IDockContent Members
void IDockContent.OnActivated(EventArgs e)
{
this.OnActivated(e);
}
void IDockContent.OnDeactivate(EventArgs e)
{
this.OnDeactivate(e);
}
#endregion
#region Events
private void DockHandler_DockStateChanged(object sender, EventArgs e)
{
OnDockStateChanged(e);
}
private static readonly object DockStateChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("Pane_DockStateChanged_Description")]
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
#endregion
/// <summary>
/// Overridden to avoid resize issues with nested controls
/// </summary>
/// <remarks>
/// http://blogs.msdn.com/b/alejacma/archive/2008/11/20/controls-won-t-get-resized-once-the-nesting-hierarchy-of-windows-exceeds-a-certain-depth-x64.aspx
/// http://support.microsoft.com/kb/953934
/// </remarks>
protected override void OnSizeChanged(EventArgs e)
{
if (DockPanel != null && DockPanel.SupportDeeplyNestedContent && IsHandleCreated)
{
BeginInvoke((MethodInvoker)delegate
{
base.OnSizeChanged(e);
});
}
else
{
base.OnSizeChanged(e);
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Globalization;
using System.IO;
using System.Text;
using NLog.MessageTemplates;
namespace NLog.Internal
{
/// <summary>
/// Helpers for <see cref="StringBuilder"/>, which is used in e.g. layout renderers.
/// </summary>
internal static class StringBuilderExt
{
/// <summary>
/// Renders the specified log event context item and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">append to this</param>
/// <param name="value">value to be appended</param>
/// <param name="format">format string. If @, then serialize the value with the Default JsonConverter.</param>
/// <param name="formatProvider">provider, for example culture</param>
public static void AppendFormattedValue(this StringBuilder builder, object value, string format, IFormatProvider formatProvider)
{
string stringValue = value as string;
if (stringValue != null && string.IsNullOrEmpty(format))
{
builder.Append(value); // Avoid automatic quotes
}
else if (format == MessageTemplates.ValueFormatter.FormatAsJson)
{
ValueFormatter.Instance.FormatValue(value, null, CaptureType.Serialize, formatProvider, builder);
}
else if (value != null)
{
ValueFormatter.Instance.FormatValue(value, format, CaptureType.Normal, formatProvider, builder);
}
}
/// <summary>
/// Appends int without using culture, and most importantly without garbage
/// </summary>
/// <param name="builder"></param>
/// <param name="value">value to append</param>
public static void AppendInvariant(this StringBuilder builder, int value)
{
// Deal with negative numbers
if (value < 0)
{
builder.Append('-');
uint uint_value = uint.MaxValue - ((uint)value) + 1; //< This is to deal with Int32.MinValue
AppendInvariant(builder, uint_value);
}
else
{
AppendInvariant(builder, (uint)value);
}
}
/// <summary>
/// Appends uint without using culture, and most importantly without garbage
///
/// Credits Gavin Pugh - https://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/
/// </summary>
/// <param name="builder"></param>
/// <param name="value">value to append</param>
public static void AppendInvariant(this StringBuilder builder, uint value)
{
if (value == 0)
{
builder.Append('0');
return;
}
int digitCount = CalculateDigitCount(value);
ApppendValueWithDigitCount(builder, value, digitCount);
}
private static int CalculateDigitCount(uint value)
{
// Calculate length of integer when written out
int length = 0;
uint length_calc = value;
do
{
length_calc /= 10;
length++;
}
while (length_calc > 0);
return length;
}
private static void ApppendValueWithDigitCount(StringBuilder builder, uint value, int digitCount)
{
// Pad out space for writing.
builder.Append('0', digitCount);
int strpos = builder.Length;
// We're writing backwards, one character at a time.
while (digitCount > 0)
{
strpos--;
// Lookup from static char array, to cover hex values too
builder[strpos] = charToInt[value % 10];
value /= 10;
digitCount--;
}
}
private static readonly char[] charToInt = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/// <summary>
/// Convert DateTime into UTC and format to yyyy-MM-ddTHH:mm:ss.fffffffZ - ISO 6801 date (Round-Trip-Time)
/// </summary>
public static void AppendXmlDateTimeRoundTrip(this StringBuilder builder, DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Unspecified)
dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc);
else
dateTime = dateTime.ToUniversalTime();
builder.Append4DigitsZeroPadded(dateTime.Year);
builder.Append('-');
builder.Append2DigitsZeroPadded(dateTime.Month);
builder.Append('-');
builder.Append2DigitsZeroPadded(dateTime.Day);
builder.Append('T');
builder.Append2DigitsZeroPadded(dateTime.Hour);
builder.Append(':');
builder.Append2DigitsZeroPadded(dateTime.Minute);
builder.Append(':');
builder.Append2DigitsZeroPadded(dateTime.Second);
int fraction = (int)(dateTime.Ticks % 10000000);
if (fraction > 0)
{
builder.Append('.');
// Remove trailing zeros
int max_digit_count = 7;
while (fraction % 10 == 0)
{
--max_digit_count;
fraction /= 10;
}
// Append the remaining fraction
int digitCount = CalculateDigitCount((uint)fraction);
if (max_digit_count > digitCount)
builder.Append('0', max_digit_count - digitCount);
ApppendValueWithDigitCount(builder, (uint)fraction, digitCount);
}
builder.Append('Z');
}
/// <summary>
/// Clears the provider StringBuilder
/// </summary>
/// <param name="builder"></param>
public static void ClearBuilder(this StringBuilder builder)
{
try
{
#if !SILVERLIGHT && !NET3_5
builder.Clear();
#else
builder.Length = 0;
#endif
}
catch
{
// Default StringBuilder Clear() can cause the StringBuilder to re-allocate new internal char-array
// This can fail in low memory conditions when StringBuilder is big, so instead try to clear the StringBuilder "gently"
if (builder.Length > 1)
builder.Remove(0, builder.Length - 1);
builder.Remove(0, builder.Length);
}
}
/// <summary>
/// Copies the contents of the StringBuilder to the MemoryStream using the specified encoding (Without BOM/Preamble)
/// </summary>
/// <param name="builder">StringBuilder source</param>
/// <param name="ms">MemoryStream destination</param>
/// <param name="encoding">Encoding used for converter string into byte-stream</param>
/// <param name="transformBuffer">Helper char-buffer to minimize memory allocations</param>
public static void CopyToStream(this StringBuilder builder, MemoryStream ms, Encoding encoding, char[] transformBuffer)
{
#if !SILVERLIGHT || WINDOWS_PHONE
if (transformBuffer != null)
{
int charCount;
int byteCount = encoding.GetMaxByteCount(builder.Length);
ms.SetLength(ms.Position + byteCount);
for (int i = 0; i < builder.Length; i += transformBuffer.Length)
{
charCount = Math.Min(builder.Length - i, transformBuffer.Length);
builder.CopyTo(i, transformBuffer, 0, charCount);
byteCount = encoding.GetBytes(transformBuffer, 0, charCount, ms.GetBuffer(), (int)ms.Position);
ms.Position += byteCount;
}
if (ms.Position != ms.Length)
{
ms.SetLength(ms.Position);
}
}
else
#endif
{
// Faster than MemoryStream, but generates garbage
var str = builder.ToString();
byte[] bytes = encoding.GetBytes(str);
ms.Write(bytes, 0, bytes.Length);
}
}
public static void CopyToBuffer(this StringBuilder builder, char[] destination, int destinationIndex)
{
#if !SILVERLIGHT || WINDOWS_PHONE
builder.CopyTo(0, destination, destinationIndex, builder.Length);
#else
builder.ToString().CopyTo(0, destination, destinationIndex, builder.Length);
#endif
}
/// <summary>
/// Copies the contents of the StringBuilder to the destination StringBuilder
/// </summary>
/// <param name="builder">StringBuilder source</param>
/// <param name="destination">StringBuilder destination</param>
public static void CopyTo(this StringBuilder builder, StringBuilder destination)
{
int sourceLength = builder.Length;
if (sourceLength > 0)
{
destination.EnsureCapacity(sourceLength + destination.Length);
if (sourceLength < 8)
{
// Skip char-buffer allocation for small strings
for (int i = 0; i < sourceLength; ++i)
destination.Append(builder[i]);
}
else if (sourceLength < 512)
{
// Single char-buffer allocation through string-object
destination.Append(builder.ToString());
}
else
{
#if !SILVERLIGHT || WINDOWS_PHONE
// Reuse single char-buffer allocation for large StringBuilders
char[] buffer = new char[256];
for (int i = 0; i < sourceLength; i += buffer.Length)
{
int charCount = Math.Min(sourceLength - i, buffer.Length);
builder.CopyTo(i, buffer, 0, charCount);
destination.Append(buffer, 0, charCount);
}
#else
destination.Append(builder.ToString());
#endif
}
}
}
/// <summary>
/// Scans the StringBuilder for the position of needle character
/// </summary>
/// <param name="builder">StringBuilder source</param>
/// <param name="needle">needle character to search for</param>
/// <param name="startPos"></param>
/// <returns>Index of the first occurrence (Else -1)</returns>
public static int IndexOf(this StringBuilder builder, char needle, int startPos = 0)
{
for (int i = startPos; i < builder.Length; ++i)
if (builder[i] == needle)
return i;
return -1;
}
/// <summary>
/// Scans the StringBuilder for the position of needle character
/// </summary>
/// <param name="builder">StringBuilder source</param>
/// <param name="needles">needle characters to search for</param>
/// <param name="startPos"></param>
/// <returns>Index of the first occurrence (Else -1)</returns>
public static int IndexOfAny(this StringBuilder builder, char[] needles, int startPos = 0)
{
for (int i = startPos; i < builder.Length; ++i)
{
if (CharArrayContains(builder[i], needles))
return i;
}
return -1;
}
private static bool CharArrayContains(char searchChar, char[] needles)
{
for (int i = 0; i < needles.Length; ++i)
{
if (needles[i] == searchChar)
return true;
}
return false;
}
/// <summary>
/// Compares the contents of two StringBuilders
/// </summary>
/// <remarks>
/// Correct implementation of <see cref="StringBuilder.Equals(StringBuilder)" /> that also works when <see cref="StringBuilder.Capacity"/> is not the same
/// </remarks>
/// <returns>True when content is the same</returns>
public static bool EqualTo(this StringBuilder builder, StringBuilder other)
{
if (builder.Length != other.Length)
return false;
for (int x = 0; x < builder.Length; ++x)
{
if (builder[x] != other[x])
{
return false;
}
}
return true;
}
/// <summary>
/// Compares the contents of a StringBuilder and a String
/// </summary>
/// <returns>True when content is the same</returns>
public static bool EqualTo(this StringBuilder builder, string other)
{
if (builder.Length != other.Length)
return false;
for (int i = 0; i < other.Length; ++i)
{
if (builder[i] != other[i])
return false;
}
return true;
}
/// <summary>
/// Append a number and pad with 0 to 2 digits
/// </summary>
/// <param name="builder">append to this</param>
/// <param name="number">the number</param>
internal static void Append2DigitsZeroPadded(this StringBuilder builder, int number)
{
builder.Append((char)((number / 10) + '0'));
builder.Append((char)((number % 10) + '0'));
}
/// <summary>
/// Append a number and pad with 0 to 4 digits
/// </summary>
/// <param name="builder">append to this</param>
/// <param name="number">the number</param>
internal static void Append4DigitsZeroPadded(this StringBuilder builder, int number)
{
builder.Append((char)(((number / 1000) % 10) + '0'));
builder.Append((char)(((number / 100) % 10) + '0'));
builder.Append((char)(((number / 10) % 10) + '0'));
builder.Append((char)(((number / 1) % 10) + '0'));
}
/// <summary>
/// Append a int type (byte, int) as string
/// </summary>
internal static void AppendIntegerAsString(this StringBuilder sb, IConvertible value, TypeCode objTypeCode)
{
switch (objTypeCode)
{
case TypeCode.Byte: sb.AppendInvariant(value.ToByte(CultureInfo.InvariantCulture)); break;
case TypeCode.SByte: sb.AppendInvariant(value.ToSByte(CultureInfo.InvariantCulture)); break;
case TypeCode.Int16: sb.AppendInvariant(value.ToInt16(CultureInfo.InvariantCulture)); break;
case TypeCode.Int32: sb.AppendInvariant(value.ToInt32(CultureInfo.InvariantCulture)); break;
case TypeCode.Int64:
{
long int64 = value.ToInt64(CultureInfo.InvariantCulture);
if (int64 < int.MaxValue && int64 > int.MinValue)
sb.AppendInvariant((int)int64);
else
sb.Append(int64);
}
break;
case TypeCode.UInt16: sb.AppendInvariant(value.ToUInt16(CultureInfo.InvariantCulture)); break;
case TypeCode.UInt32: sb.AppendInvariant(value.ToUInt32(CultureInfo.InvariantCulture)); break;
case TypeCode.UInt64:
{
ulong uint64 = value.ToUInt64(CultureInfo.InvariantCulture);
if (uint64 < uint.MaxValue)
sb.AppendInvariant((uint)uint64);
else
sb.Append(uint64);
}
break;
default:
sb.Append(XmlHelper.XmlConvertToString(value, objTypeCode));
break;
}
}
public static void TrimRight(this StringBuilder sb, int startPos = 0)
{
int i = sb.Length - 1;
for (; i >= startPos; i--)
if (!char.IsWhiteSpace(sb[i]))
break;
if (i < sb.Length - 1)
sb.Length = i + 1;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2012LightDockPaneStrip : DockPaneStripBase
{
private class TabVS2012Light : Tab
{
public TabVS2012Light(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override Tab CreateTab(IDockContent content)
{
return new TabVS2012Light(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
}
#region Constants
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 0;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 3;
private const int _DocumentButtonGapBottom = 3;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 0;//3;
private const int _DocumentTabGapLeft = 0;//3;
private const int _DocumentTabGapRight = 0;//3;
private const int _DocumentIconGapBottom = 2;//2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 6;
private static readonly Pen _PenToolWindowActivedTabBorder = new Pen( Color.FromArgb( 245, 245, 245 ) );
#endregion
#region Members
private ContextMenuStrip m_selectMenu;
private static Bitmap m_imageButtonClose;
private InertButton m_buttonClose;
private static Bitmap m_imageButtonWindowList;
private static Bitmap m_imageButtonWindowListOverflow;
private InertButton m_buttonWindowList;
private IContainer m_components;
private ToolTip m_toolTip;
private Font m_font;
private Font m_boldFont;
private int m_startDisplayingTab = 0;
private int m_endDisplayingTab = 0;
private int m_firstDisplayingTab = 0;
private bool m_documentTabsOverflow = false;
private static string m_toolTipSelect;
private static string m_toolTipClose;
private bool m_closeButtonVisible = false;
private Rectangle _activeClose;
private int _selectMenuMargin = 5;
#endregion
#region Properties
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
public int SelectMenuMargin
{
get { return _selectMenuMargin; }
set { _selectMenuMargin = value; }
}
private static Bitmap ImageButtonClose
{
get
{
if (m_imageButtonClose == null)
m_imageButtonClose = Resources.DockPane_Close;
return m_imageButtonClose;
}
}
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap ImageButtonWindowList
{
get
{
if (m_imageButtonWindowList == null)
m_imageButtonWindowList = Resources.DockPane_Option;
return m_imageButtonWindowList;
}
}
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (m_imageButtonWindowListOverflow == null)
m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return m_imageButtonWindowListOverflow;
}
}
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer Components
{
get { return m_components; }
}
public Font TextFont
{
get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; }
}
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string ToolTipClose
{
get
{
if (m_toolTipClose == null)
m_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return m_toolTipClose;
}
}
private static string ToolTipSelect
{
get
{
if (m_toolTipSelect == null)
m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return m_toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.ControlDark; }
}
private static Pen PenToolWindowActivedTabBorder {
get { return _PenToolWindowActivedTabBorder; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
#endregion
public VS2012LightDockPaneStrip(DockPane pane)
: base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose(disposing);
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
if (rect.Width > 0 && rect.Height > 0)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
base.OnPaint(e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
protected internal override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2012Light tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; )
{
anyWidthWithinAverage = false;
foreach (TabVS2012Light tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2012Light tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth--;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2012Light tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
var tab = Tabs[index] as TabVS2012Light;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X; //+ rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
var tab = Tabs[m_startDisplayingTab] as TabVS2012Light;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X;// +rectTabStrip.Height / 2;
foreach (TabVS2012Light tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
try {
var tab = Tabs[index] as TabVS2012Light;
if ( tab.TabWidth != 0 )
return false;
} catch {
return false;
}
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private const int TAB_CLOSE_BUTTON_WIDTH = 30;
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
int width;
if (DockPane.DockPanel.ShowDocumentIcon)
width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
width += TAB_CLOSE_BUTTON_WIDTH;
return width;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
rectTabStrip.Height += 1;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2012Light tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i = 0; i < count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2012Light;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2012Light, rectTab);
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
{
Color tabUnderLineColor;
if (tabActive != null && DockPane.IsActiveDocumentPane)
tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
else
tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom);
}
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
{
rectTab.Intersect(rectTabOnly);
DrawTab(g, tabActive, rectTab);
}
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine( PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top );
for ( int i = 0; i < Tabs.Count; i++ ) {
var rectTab = GetTabRectangle( i );
if ( Tabs[i].Content == DockPane.ActiveContent ) {
g.DrawLine( PenToolWindowActivedTabBorder, rectTab.Left, rectTabStrip.Top, rectTab.Right - 2, rectTabStrip.Top );
}
DrawTab( g, Tabs[i] as TabVS2012Light, GetTabRectangle( i ) );
}
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2012Light tab = (TabVS2012Light)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
var tab = (TabVS2012Light)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
// Shorten TabOutline so it doesn't get overdrawn by icons next to it
rect.Intersect(TabsRectangle);
rect.Width--;
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
GraphicsPath.AddRectangle(rect);
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect)
{
rect.Y += 1;
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
if (DockPane.ActiveContent == tab.Content) // && ((DockContent)tab.Content).IsActivated)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
g.FillRectangle( new LinearGradientBrush( rectTab, startColor, endColor, gradientMode ), rect );
Color textColor;
if (tab.Content == DockPane.MouseOverTab)
textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
else
textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height);
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
var rectCloseButton = GetCloseButtonRect(rect);
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += rect.X;
rectBack.X = 0;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
Color lostFocusText = SystemColors.GrayText;
if (DockPane.ActiveContent == tab.Content)
{
if (DockPane.IsActiveDocumentPane)
{
g.FillRectangle(new SolidBrush(activeColor), rect);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat);
g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton);
}
else
{
g.FillRectangle(new SolidBrush(lostFocusColor), rect);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat);
g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton);
}
}
else
{
if (tab.Content == DockPane.MouseOverTab)
{
g.FillRectangle(new SolidBrush(mouseHoverColor), rect);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat);
g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton);
}
else
{
g.FillRectangle(new SolidBrush(inactiveColor), rect);
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat);
}
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document)
return;
var indexHit = HitTest();
if (indexHit > -1 && DockPane.CanClose)
TabCloseButtonHit(indexHit);
}
private void TabCloseButtonHit(int index)
{
var mousePos = PointToClient(MousePosition);
var tabRect = GetTabRectangle(index);
var closeButtonRect = GetCloseButtonRect(tabRect);
var mouseRect = new Rectangle(mousePos, new Size(1, 1));
if (closeButtonRect.IntersectsWith(mouseRect))
DockPane.CloseActiveContent();
}
private Rectangle GetCloseButtonRect(Rectangle rectTab)
{
if (Appearance != Docking.DockPane.AppearanceStyle.Document)
{
return Rectangle.Empty;
}
const int gap = 3;
const int imageSize = 15;
return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize);
}
private void WindowList_Click(object sender, EventArgs e)
{
SelectMenu.Items.Clear();
foreach (TabVS2012Light tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2)));
var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size);
var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin);
if (workingArea.Contains(menuMargined))
{
SelectMenu.Show(menu.Location);
}
else
{
var newPoint = menu.Location;
newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right);
newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom);
var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height));
if (newPoint.Y < button.Y)
{
// flip the menu up to be above the button.
newPoint.Y = button.Y - ButtonWindowList.Height;
SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight);
}
else
{
SelectMenu.Show(newPoint);
}
}
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
ButtonClose.Enabled = false;
m_closeButtonVisible = false;
ButtonClose.Visible = m_closeButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance == DockPane.AppearanceStyle.Document)
{
LayoutButtons();
OnRefreshChanges();
}
base.OnLayout(levent);
}
private void LayoutButtons()
{
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (m_closeButtonVisible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
}
private void Close_Click(object sender, EventArgs e)
{
if (DockPane.CanClose)
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
return -1;
}
private Rectangle ActiveClose
{
get { return _activeClose; }
}
private bool SetActiveClose(Rectangle rectangle)
{
if (_activeClose == rectangle)
return false;
_activeClose = rectangle;
return true;
}
private bool SetMouseOverTab(IDockContent content)
{
if (DockPane.MouseOverTab == content)
return false;
DockPane.MouseOverTab = content;
return true;
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
bool tabUpdate = false;
bool buttonUpdate = false;
if (index != -1)
{
var tab = Tabs[index] as TabVS2012Light;
if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document)
{
tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content);
}
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
var mousePos = PointToClient(MousePosition);
var tabRect = GetTabRectangle(index);
var closeButtonRect = GetCloseButtonRect(tabRect);
var mouseRect = new Rectangle(mousePos, new Size(1, 1));
buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty);
}
else
{
tabUpdate = SetMouseOverTab(null);
buttonUpdate = SetActiveClose(Rectangle.Empty);
}
if (tabUpdate || buttonUpdate)
Invalidate();
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnMouseLeave(EventArgs e)
{
var tabUpdate = SetMouseOverTab(null);
var buttonUpdate = SetActiveClose(Rectangle.Empty);
if (tabUpdate || buttonUpdate)
Invalidate();
base.OnMouseLeave(e);
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
namespace Ioke.Math {
using System;
using System.Text;
public abstract class RealNum : Complex {
public override RealNum re() { return this; }
public override RealNum im() { return IntNum.zero(); }
public abstract bool isNegative ();
/** Return 1 if >0; 0 if ==0; -1 if <0; -2 if NaN. */
public abstract int sign ();
public RealNum max (RealNum x)
{
RealNum result = grt (x) ? this : x;
return result;
}
public RealNum min (RealNum x)
{
RealNum result = grt (x) ? x : this;
return result;
}
public static RealNum add (RealNum x, RealNum y, int k)
{
return (RealNum)(x.add(y, k));
}
public static RealNum times(RealNum x, RealNum y)
{
return (RealNum)(x.mul(y));
}
public static RealNum divide (RealNum x, RealNum y)
{
return (RealNum)(x.div(y));
}
/* These are defined in Complex, but have to be overridden. */
public override abstract Numeric add (object obj, int k);
public override abstract Numeric mul (object obj);
public override abstract Numeric div (object obj);
public override Numeric abs ()
{
return isNegative () ? neg () : this;
}
public RealNum rneg() { return (RealNum) neg(); }
public override bool isZero ()
{
return sign () == 0;
}
/** Converts a real to an integer, according to a specified rounding mode.
* Note an inexact argument gives an inexact result, following Scheme.
* See also RatNum.toExactInt. */
public static double toInt (double d, int rounding_mode)
{
switch (rounding_mode)
{
case FLOOR:
return Math.Floor(d);
case CEILING:
return Math.Ceiling(d);
case TRUNCATE:
return d < 0.0 ? Math.Ceiling (d) : Math.Floor (d);
case ROUND:
return Math.Round(d);
default: // Illegal rounding_mode
return d;
}
}
/** Converts to an exact integer, with specified rounding mode. */
public virtual IntNum toExactInt (int rounding_mode)
{
return toExactInt(doubleValue(), rounding_mode);
}
public virtual RealNum toInt(int rounding_mode) {
return new DFloNum(toInt(doubleValue(), rounding_mode));
}
/** Converts real to an exact integer, with specified rounding mode. */
public static IntNum toExactInt (double value, int rounding_mode)
{
return toExactInt(toInt(value, rounding_mode));
}
/** Converts an integral double (such as a toInt result) to an IntNum. */
public static IntNum toExactInt (double value)
{
if (Double.IsInfinity (value) || Double.IsNaN (value))
throw new ArithmeticException ("cannot convert "+value+" to exact integer");
long bits = BitConverter.DoubleToInt64Bits(value);
bool neg = bits < 0;
int exp = (int) (bits >> 52) & 0x7FF;
bits &= 0xfffffffffffffL;
if (exp == 0)
bits <<= 1;
else
bits |= 0x10000000000000L;
if (exp <= 1075)
{
int rshift = 1075 - exp;
if (rshift > 53)
return IntNum.zero();
bits >>= rshift;
return IntNum.make (neg ? -bits : bits);
}
return IntNum.shift (IntNum.make (neg ? -bits : bits), exp - 1075);
}
/** Convert rational to (rounded) integer, after multiplying by 10**k. */
public static IntNum toScaledInt (RatNum r, int k)
{
if (k != 0)
{
IntNum power = IntNum.power(IntNum.ten(), k < 0 ? -k : k);
IntNum num = r.numerator();
IntNum den = r.denominator();
if (k >= 0)
num = IntNum.times(num, power);
else
den = IntNum.times(den, power);
r = RatNum.make(num, den);
}
return r.toExactInt(ROUND);
}
public static string toStringScientific (float d)
{
return toStringScientific(d.ToString());
}
public static string toStringScientific (double d)
{
return toStringScientific(d.ToString());
}
/** Convert result of Double.toString or Float.toString to
* scientific notation.
* Does not validate the input.
*/
public static string toStringScientific (string dstr)
{
int indexE = dstr.IndexOf('E');
if (indexE >= 0)
return dstr;
int len = dstr.Length;
// Check for "Infinity" or "NaN".
char ch = dstr[len-1];
if (ch == 'y' || ch == 'N')
return dstr;
StringBuilder sbuf = new StringBuilder(len+10);
int exp = toStringScientific(dstr, sbuf);
sbuf.Append('E');
sbuf.Append(exp);
return sbuf.ToString();
}
public static int toStringScientific (string dstr, StringBuilder sbuf)
{
bool neg = dstr[0] == '-';
if (neg)
sbuf.Append('-');
int pos = neg ? 1 : 0;
int exp;
int len = dstr.Length;
if (dstr[pos] == '0')
{ // Value is < 1.0.
int start = pos;
for (;;)
{
if (pos == len)
{
sbuf.Append("0");
exp = 0;
break;
}
char ch = dstr[pos++];
if (ch >= '0' && ch <= '9' && (ch != '0' || pos == len))
{
sbuf.Append(ch);
sbuf.Append('.');
exp = ch == '0' ? 0 : start - pos + 2;
if (pos == len)
sbuf.Append('0');
else
{
while (pos < len)
sbuf.Append(dstr[pos++]);
}
break;
}
}
}
else
{
// Number of significant digits in string.
int ndigits = len - (neg ? 2 : 1);
int dot = dstr.IndexOf('.');
// Number of fractional digits is len-dot-1.
// We want ndigits-1 fractional digits. Hence we need to move the
// decimal point ndigits-1-(len-dot-1) == ndigits-len+dot positions
// to the left. This becomes the exponent we need.
exp = ndigits - len + dot;
sbuf.Append(dstr[pos++]); // Copy initial digit before point.
sbuf.Append('.');
while (pos < len)
{
char ch = dstr[pos++];
if (ch != '.')
sbuf.Append(ch);
}
}
// Remove excess zeros.
pos = sbuf.Length;
int slen = -1;
for (;;)
{
char ch = sbuf[--pos];
if (ch == '0')
slen = pos;
else
{
if (ch == '.')
slen = pos + 2;
break;
}
}
if (slen >= 0)
sbuf.Length = slen;
return exp;
}
public static string toStringDecimal (string dstr)
{
int indexE = dstr.IndexOf('E');
if (indexE < 0)
return dstr;
int len = dstr.Length;
// Check for "Infinity" or "NaN".
char ch = dstr[len-1];
if (ch == 'y' || ch == 'N')
return dstr;
StringBuilder sbuf = new StringBuilder(len+10);
bool neg = dstr[0] == '-';
if (dstr[indexE+1] != '-')
{
throw new Exception("not implemented: toStringDecimal given non-negative exponent: "+dstr);
}
else
{
int pos = indexE+2; // skip "E-".
int exp = 0;
while (pos < len)
exp = 10 * exp + (dstr[pos++] - '0');
if (neg)
sbuf.Append('-');
sbuf.Append("0.");
while (--exp > 0) sbuf.Append('0');
for (pos = 0; (ch = dstr[pos++]) != 'E'; )
{
if (ch != '-' & ch != '.'
&& (ch != '0' || pos < indexE))
sbuf.Append(ch);
}
return sbuf.ToString();
}
}
public virtual decimal AsDecimal() {
return System.Convert.ToDecimal(doubleValue());
}
public virtual BigDecimal AsBigDecimal() {
return new BigDecimal(doubleValue().ToString(System.Globalization.CultureInfo.InvariantCulture));
}
}
}
| |
//
// MultipartReader.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using Couchbase.Lite.Support;
using Sharpen;
using System.Linq;
namespace Couchbase.Lite.Support
{
internal class MultipartReader
{
private enum MultipartReaderState
{
Uninitialized,
AtStart,
InPrologue,
InBody,
InHeaders,
AtEnd,
kFailed
}
private static readonly Byte[] kCRLFCRLF;
static MultipartReader()
{
kCRLFCRLF = Encoding.UTF8.GetBytes("\r\n\r\n");
}
private MultipartReader.MultipartReaderState state;
private List<Byte> buffer;
private readonly String contentType;
private byte[] boundary;
private IMultipartReaderDelegate readerDelegate;
public IDictionary<String, String> headers;
public MultipartReader(string contentType, IMultipartReaderDelegate readerDelegate)
{
this.contentType = contentType;
this.readerDelegate = readerDelegate;
this.buffer = new List<Byte>(1024);
this.state = MultipartReader.MultipartReaderState.AtStart;
ParseContentType();
}
public byte[] GetBoundary()
{
return boundary;
}
public IEnumerable<byte> GetBoundaryWithoutLeadingCRLF()
{
var rawBoundary = GetBoundary();
var result = new Couchbase.Lite.Util.ArraySegment<Byte>(rawBoundary, 2, rawBoundary.Length - 2);
return result;
}
public bool Finished()
{
return state == MultipartReader.MultipartReaderState.AtEnd;
}
private static Byte[] EOMBytes()
{
return Encoding.UTF8.GetBytes("--");
}
private bool Memcmp(byte[] array1, byte[] array2, int len)
{
bool equals = true;
for (int i = 0; i < len; i++)
{
if (array1[i] != array2[i])
{
equals = false;
}
}
return equals;
}
public Range SearchFor(byte[] pattern, int start)
{
var searcher = new KMPMatch();
var matchIndex = searcher.IndexOf(buffer.ToArray(), pattern, start);
return matchIndex != -1
? new Range (matchIndex, pattern.Length)
: new Range (matchIndex, 0);
}
public void ParseHeaders(string headersStr)
{
headers = new Dictionary<String, String>();
if (!string.IsNullOrEmpty (headersStr)) {
headersStr = headersStr.Trim ();
var tokenizer = headersStr.Split(new[] { "\r\n" }, StringSplitOptions.None);
foreach (var header in tokenizer) {
if (!header.Contains (":")) {
throw new ArgumentException ("Missing ':' in header line: " + header);
}
var headerTokenizer = header.Split(':');
var key = headerTokenizer[0].Trim ();
var value = headerTokenizer[1].Trim ();
headers.Put (key, value);
}
}
}
private void DeleteUpThrough(int location)
{
var srcBuffer = buffer.ToArray();
var newBuffer = new byte[srcBuffer.Length - location];
Array.Copy(srcBuffer, location, newBuffer, 0, newBuffer.Length);
buffer.Clear();
buffer.AddRange(newBuffer);
}
private void TrimBuffer()
{
int bufLen = buffer.Count;
int boundaryLen = GetBoundary().Length;
if (bufLen > boundaryLen)
{
// Leave enough bytes in _buffer that we can find an incomplete boundary string
var dataToAppend = new byte[bufLen - boundaryLen];
Array.Copy(buffer.ToArray(), 0, dataToAppend, 0, dataToAppend.Length);
readerDelegate.AppendToPart(dataToAppend);
DeleteUpThrough(bufLen - boundaryLen);
}
}
public void AppendData(IEnumerable<byte> newData)
{
var data = newData.ToArray();
if (buffer == null)
{
return;
}
if (data.Length == 0)
{
return;
}
buffer.AddRange(data);
MultipartReader.MultipartReaderState nextState;
do
{
nextState = MultipartReader.MultipartReaderState.Uninitialized;
var bufLen = buffer.Count;
switch (state)
{
case MultipartReader.MultipartReaderState.AtStart:
{
// Log.d(Database.TAG, "appendData. bufLen: " + bufLen);
// The entire message might start with a boundary without a leading CRLF.
var boundaryWithoutLeadingCRLF = GetBoundaryWithoutLeadingCRLF().ToArray();
if (bufLen >= boundaryWithoutLeadingCRLF.Length)
{
// if (Arrays.equals(buffer.toByteArray(), boundaryWithoutLeadingCRLF)) {
if (Memcmp(buffer.ToArray(), boundaryWithoutLeadingCRLF, boundaryWithoutLeadingCRLF.Length))
{
DeleteUpThrough(boundaryWithoutLeadingCRLF.Length);
nextState = MultipartReader.MultipartReaderState.InHeaders;
}
else
{
nextState = MultipartReader.MultipartReaderState.InPrologue;
}
}
break;
}
case MultipartReader.MultipartReaderState.InPrologue:
case MultipartReader.MultipartReaderState.InBody:
{
// Look for the next part boundary in the data we just added and the ending bytes of
// the previous data (in case the boundary string is split across calls)
if (bufLen < boundary.Length)
{
break;
}
var start = Math.Max(0, bufLen - data.Length - boundary.Length);
var r = SearchFor(boundary, start);
if (r.GetLength() > 0)
{
if (state == MultipartReader.MultipartReaderState.InBody)
{
var dataToAppend = new byte[r.GetLocation()];
Array.Copy(buffer.ToArray(), 0, dataToAppend, 0, dataToAppend.Length);
readerDelegate.AppendToPart(dataToAppend);
readerDelegate.FinishedPart();
}
DeleteUpThrough(r.GetLocation() + r.GetLength());
nextState = MultipartReader.MultipartReaderState.InHeaders;
}
else
{
TrimBuffer();
}
break;
}
case MultipartReader.MultipartReaderState.InHeaders:
{
// First check for the end-of-message string ("--" after separator):
if (bufLen >= 2 && Memcmp(buffer.ToArray(), EOMBytes(), 2))
{
state = MultipartReader.MultipartReaderState.AtEnd;
Close();
return;
}
// Otherwise look for two CRLFs that delimit the end of the headers:
var r = SearchFor(kCRLFCRLF, 0);
if (r.GetLength() > 0)
{
var headersBytes = new Couchbase.Lite.Util.ArraySegment<Byte>(buffer.ToArray(), 0, r.GetLocation()); // <-- better?
var headersString = Encoding.UTF8.GetString(headersBytes.ToArray());
ParseHeaders(headersString);
DeleteUpThrough(r.GetLocation() + r.GetLength());
readerDelegate.StartedPart(headers);
nextState = MultipartReader.MultipartReaderState.InBody;
}
break;
}
default:
{
throw new InvalidOperationException("Unexpected data after end of MIME body");
}
}
if (nextState != MultipartReader.MultipartReaderState.Uninitialized)
{
state = nextState;
}
}
while (nextState != MultipartReader.MultipartReaderState.Uninitialized && buffer.Count > 0);
}
private void Close()
{
buffer = null;
boundary = null;
}
private void ParseContentType()
{
var tokenizer = contentType.Split(';');
bool first = true;
foreach (var token in tokenizer)
{
string param = token.Trim();
if (first)
{
if (!param.StartsWith("multipart/", StringComparison.InvariantCultureIgnoreCase))
{
throw new ArgumentException(contentType + " does not start with multipart/");
}
first = false;
}
else
{
if (param.StartsWith("boundary=", StringComparison.InvariantCultureIgnoreCase))
{
var tempBoundary = param.Substring(9);
if (tempBoundary.StartsWith ("\"", StringComparison.InvariantCultureIgnoreCase))
{
if (tempBoundary.Length < 2 || !tempBoundary.EndsWith ("\"", StringComparison.InvariantCultureIgnoreCase)) {
throw new ArgumentException (contentType + " is not valid");
}
tempBoundary = tempBoundary.Substring(1, tempBoundary.Length - 2);
}
if (tempBoundary.Length < 1)
{
throw new ArgumentException(contentType + " has zero-length boundary");
}
tempBoundary = string.Format("\r\n--{0}", tempBoundary);
boundary = Encoding.UTF8.GetBytes(tempBoundary);
break;
}
}
}
}
}
/// <summary>Knuth-Morris-Pratt Algorithm for Pattern Matching</summary>
internal class KMPMatch
{
/// <summary>Finds the first occurrence of the pattern in the text.</summary>
/// <remarks>Finds the first occurrence of the pattern in the text.</remarks>
public int IndexOf(byte[] data, byte[] pattern, int dataOffset)
{
int[] failure = ComputeFailure(pattern);
int j = 0;
if (data.Length == 0)
{
return -1;
}
int dataLength = data.Length;
int patternLength = pattern.Length;
for (int i = dataOffset; i < dataLength; i++)
{
while (j > 0 && pattern[j] != data[i])
{
j = failure[j - 1];
}
if (pattern[j] == data[i])
{
j++;
}
if (j == patternLength)
{
return i - patternLength + 1;
}
}
return -1;
}
/// <summary>
/// Computes the failure function using a boot-strapping process,
/// where the pattern is matched against itself.
/// </summary>
/// <remarks>
/// Computes the failure function using a boot-strapping process,
/// where the pattern is matched against itself.
/// </remarks>
private int[] ComputeFailure(byte[] pattern)
{
int[] failure = new int[pattern.Length];
int j = 0;
for (int i = 1; i < pattern.Length; i++)
{
while (j > 0 && pattern[j] != pattern[i])
{
j = failure[j - 1];
}
if (pattern[j] == pattern[i])
{
j++;
}
failure[i] = j;
}
return failure;
}
}
}
| |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using Google.Protobuf;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Google.Iam.V1;
namespace Google.Pubsub.V1.Snippets
{
[Collection(nameof(PubsubSnippetFixture))]
public class PublisherClientSnippets
{
private readonly PubsubSnippetFixture _fixture;
public PublisherClientSnippets(PubsubSnippetFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ListTopics()
{
string projectId = _fixture.ProjectId;
// Snippet: ListTopics
PublisherClient client = PublisherClient.Create();
// Alternative: use a known project resource name:
// "projects/{PROJECT_ID}"
string projectName = PublisherClient.FormatProjectName(projectId);
foreach (Topic topic in client.ListTopics(projectName))
{
Console.WriteLine(topic.Name);
}
// End snippet
}
[Fact]
public async Task ListTopicsAsync()
{
string projectId = _fixture.ProjectId;
// Snippet: ListTopicsAsync
PublisherClient client = PublisherClient.Create();
// Alternative: use a known project resource name:
// "projects/{PROJECT_ID}"
string projectName = PublisherClient.FormatProjectName(projectId);
IAsyncEnumerable<Topic> topics = client.ListTopicsAsync(projectName);
await topics.ForEachAsync(topic =>
{
Console.WriteLine(topic.Name);
});
// End snippet
}
[Fact]
public void CreateTopic()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
// Snippet: CreateTopic
PublisherClient client = PublisherClient.Create();
// Alternative: use a known topic resource name
// "projects/{PROJECT_ID}/topics/{TOPIC_ID}"
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
Topic topic = client.CreateTopic(topicName);
Console.WriteLine($"Created {topic.Name}");
// End snippet
}
[Fact]
public async Task CreateTopicAsync()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
// Snippet: CreateTopicAsync(string,CallSettings)
// Additional: CreateTopicAsync(string,CancellationToken)
PublisherClient client = PublisherClient.Create();
// Alternative: use a known topic resource name
// "projects/{PROJECT_ID}/topics/{TOPIC_ID}"
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
Topic topic = await client.CreateTopicAsync(topicName);
Console.WriteLine($"Created {topic.Name}");
// End snippet
}
[Fact]
public void Publish()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
// Snippet: Publish
PublisherClient client = PublisherClient.Create();
// Make sure we have a topic to publish to
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
client.CreateTopic(topicName);
PubsubMessage message = new PubsubMessage
{
// The data is any arbitrary ByteString. Here, we're using text.
Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
// The attributes provide metadata in a string-to-string dictionary.
Attributes =
{
{ "description", "Simple text message" }
}
};
client.Publish(topicName, new[] { message });
// End snippet
}
[Fact]
public async Task PublishAsync()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
// Snippet: PublishAsync(*,*,CallSettings)
// Additional: PublishAsync(*,*,CancellationToken)
PublisherClient client = PublisherClient.Create();
// Make sure we have a topic to publish to
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
await client.CreateTopicAsync(topicName);
PubsubMessage message = new PubsubMessage
{
// The data is any arbitrary ByteString. Here, we're using text.
Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
// The attributes provide metadata in a string-to-string dictionary.
Attributes =
{
{ "description", "Simple text message" }
}
};
await client.PublishAsync(topicName, new[] { message });
// End snippet
}
[Fact]
public void DeleteTopic()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
PublisherClient.Create().CreateTopic(PublisherClient.FormatTopicName(projectId, topicId));
// Snippet: DeleteTopic
PublisherClient client = PublisherClient.Create();
// Alternative: use a known topic resource name
// "projects/{PROJECT_ID}/topics/{TOPIC_ID}"
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
client.DeleteTopic(topicName);
Console.WriteLine($"Deleted {topicName}");
// End snippet
}
[Fact]
public async Task DeleteTopicAsync()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
await PublisherClient.Create().CreateTopicAsync(PublisherClient.FormatTopicName(projectId, topicId));
// Snippet: DeleteTopicAsync(string,CallSettings)
// Additional: DeleteTopicAsync(string,CancellationToken)
PublisherClient client = PublisherClient.Create();
// Alternative: use a known topic resource name
// "projects/{PROJECT_ID}/topics/{TOPIC_ID}"
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
await client.DeleteTopicAsync(topicName);
Console.WriteLine($"Deleted {topicName}");
// End snippet
}
[Fact]
public void GetIamPolicy()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
PublisherClient.Create().CreateTopic(PublisherClient.FormatTopicName(projectId, topicId));
// Snippet: GetIamPolicy
PublisherClient client = PublisherClient.Create();
string topicName = PublisherClient.FormatTopicName(projectId, topicId);
Policy policy = client.GetIamPolicy(topicName);
Console.WriteLine($"Policy for {topicName}: {policy}");
// End snippet
}
}
}
| |
/**
* Repairs missing pb_Object and pb_Entity references. It is based
* on this article by Unity Gems: http://unitygems.com/lateral1/
*/
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using ProBuilder2.Common;
namespace ProBuilder2.EditorCommon
{
/**
* Extends MonoBehaviour Inspector, automatically fixing missing script
* references (typically caused by ProBuilder upgrade process).
*/
[CustomEditor(typeof(MonoBehaviour))]
public class pb_MissingScriptEditor : Editor
{
#region Members
static bool applyDummyScript = true; ///< If true, any null components that can't be set will have this script applied to their reference, allowing us to later remove them.
static float index = 0; ///< general idea of where we are in terms of processing this scene.
static float total; ///< general idea of how many missing script references are in this scene.
static bool doFix = false; ///< while true, the inspector will attempt to cycle to broken gameobjects until none are found.
static List<GameObject> unfixable = new List<GameObject>(); ///< if a non-pb missing reference is encountered, need to let the iterator know not to bother,
static MonoScript _mono_pb; ///< MonoScript assets
static MonoScript _mono_pe; ///< MonoScript assets
static MonoScript _mono_dummy; ///< MonoScript assets
/**
* Load the pb_Object and pb_Entity classes to MonoScript assets. Saves us from having to fall back on Reflection.
*/
static void LoadMonoScript()
{
GameObject go = new GameObject();
pb_Object pb = go.AddComponent<pb_Object>();
pb_Entity pe = go.GetComponent<pb_Entity>();
if(pe == null)
pe = go.AddComponent<pb_Entity>();
pb_DummyScript du = go.AddComponent<pb_DummyScript>();
_mono_pb = MonoScript.FromMonoBehaviour( pb );
_mono_pe = MonoScript.FromMonoBehaviour( pe );
_mono_dummy = MonoScript.FromMonoBehaviour( du );
DestroyImmediate(go);
}
public MonoScript pb_monoscript
{
get
{
if(_mono_pb == null) LoadMonoScript();
return _mono_pb;
}
}
public MonoScript pe_monoscript
{
get
{
if(_mono_pe == null) LoadMonoScript();
return _mono_pe;
}
}
public MonoScript dummy_monoscript
{
get
{
if(_mono_dummy == null) LoadMonoScript();
return _mono_dummy;
}
}
#endregion
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Repair/Repair Missing Script References")]
public static void MenuRepairMissingScriptReferences()
{
FixAllScriptReferencesInScene();
}
static void FixAllScriptReferencesInScene()
{
EditorApplication.ExecuteMenuItem("Window/Inspector");
Object[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject)).Where(x => ((GameObject)x).GetComponents<Component>().Any(n => n == null) ).ToArray();
total = all.Length;
unfixable.Clear();
if(total > 1)
{
Undo.RecordObjects(all, "Fix missing script references");
index = 0;
doFix = true;
Next();
}
else
{
if( applyDummyScript )
DeleteDummyScripts();
EditorUtility.DisplayDialog("Success", "No missing ProBuilder script references found.", "Okay");
}
}
/**
* Advance to the next gameobject with missing components. If none are found, display dialog and exit.
*/
static void Next()
{
bool earlyExit = false;
if( EditorUtility.DisplayCancelableProgressBar("Repair ProBuilder Script References", "Fixing " + (int)Mathf.Floor(index+1) + " out of " + total + " objects in scene.", ((float)index/total) ) )
{
earlyExit = true;
doFix = false;
}
if(!earlyExit)
{
// Cycle through FindObjectsOfType on every Next() because using a static list didn't work for some reason.
foreach(GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)))
{
if(go.GetComponents<Component>().Any(x => x == null) && !unfixable.Contains(go))
{
if( (PrefabUtility.GetPrefabType(go) == PrefabType.PrefabInstance ||
PrefabUtility.GetPrefabType(go) == PrefabType.Prefab ) )
{
GameObject pref = (GameObject)PrefabUtility.GetPrefabParent(go);
if(pref && (pref.GetComponent<pb_Object>() || pref.GetComponent<pb_Entity>()))
{
unfixable.Add(go);
continue;
}
}
if(go.hideFlags != HideFlags.None)
{
unfixable.Add(go);
continue;
}
Selection.activeObject = go;
return;
}
}
}
pb_Object[] pbs = (pb_Object[])Resources.FindObjectsOfTypeAll(typeof(pb_Object));
for(int i = 0; i < pbs.Length; i++)
{
EditorUtility.DisplayProgressBar("Checking ProBuilder Meshes", "Refresh " + (i+1) + " out of " + total + " objects in scene.", ((float)i/pbs.Length) );
try
{
pbs[i].ToMesh();
pbs[i].Refresh();
pbs[i].Optimize();
} catch (System.Exception e)
{
Debug.LogWarning("Failed reconstituting " + pbs[i].name + ". Proceeding with upgrade anyways. Usually this means a prefab is already fixed, and just needs to be instantiated to take effect.\n" + e.ToString());
}
}
EditorUtility.ClearProgressBar();
if( applyDummyScript )
DeleteDummyScripts();
EditorUtility.DisplayDialog("Success", "Successfully repaired " + total + " ProBuilder objects.", "Okay");
if(!pb_EditorSceneUtility.SaveCurrentSceneIfUserWantsTo())
Debug.LogWarning("Repaired script references will be lost on exit if this scene is not saved!");
doFix = false;
skipEvent = true;
}
/**
* SerializedProperty names found in pb_Entity.
*/
List<string> PB_OBJECT_SCRIPT_PROPERTIES = new List<string>()
{
"_sharedIndices",
"_vertices",
"_uv",
"_sharedIndicesUV",
"_quads"
};
/**
* SerializedProperty names found in pb_Object.
*/
List<string> PB_ENTITY_SCRIPT_PROPERTIES = new List<string>()
{
"pb",
"userSetDimensions",
"_entityType",
"forceConvex"
};
// Prevents ArgumentException after displaying 'Done' dialog. For some reason the Event loop skips layout phase after DisplayDialog.
private static bool skipEvent = false;
public override void OnInspectorGUI()
{
if(skipEvent && Event.current.type == EventType.Repaint)
{
skipEvent = false;
return;
}
SerializedProperty scriptProperty = this.serializedObject.FindProperty("m_Script");
if(scriptProperty == null || scriptProperty.objectReferenceValue != null)
{
if(doFix)
{
if(Event.current.type == EventType.Repaint)
{
Next();
}
}
else
{
base.OnInspectorGUI();
}
return;
}
int pbObjectMatches = 0, pbEntityMatches = 0;
// Shows a detailed tree view of all the properties in this serializedobject.
// GUILayout.Label( SerializedObjectToString(this.serializedObject) );
SerializedProperty iterator = this.serializedObject.GetIterator();
iterator.Next(true);
while( iterator.Next(true) )
{
if( PB_OBJECT_SCRIPT_PROPERTIES.Contains(iterator.name) )
pbObjectMatches++;
if( PB_ENTITY_SCRIPT_PROPERTIES.Contains(iterator.name) )
pbEntityMatches++;
}
// If we can fix it, show the help box, otherwise just default inspector it up.
if(pbObjectMatches >= 3 || pbEntityMatches >= 3)
{
EditorGUILayout.HelpBox("Missing Script Reference\n\nProBuilder can automatically fix this missing reference. To fix all references in the scene, click \"Fix All in Scene\". To fix just this one, click \"Reconnect\".", MessageType.Warning);
}
else
{
if(doFix)
{
if( applyDummyScript )
{
index += .5f;
scriptProperty.objectReferenceValue = dummy_monoscript;
scriptProperty.serializedObject.ApplyModifiedProperties();
scriptProperty = this.serializedObject.FindProperty("m_Script");
scriptProperty.serializedObject.Update();
}
else
{
unfixable.Add( ((Component)target).gameObject );
}
Next();
GUIUtility.ExitGUI();
return;
}
else
{
base.OnInspectorGUI();
}
return;
}
GUI.backgroundColor = Color.green;
if(!doFix)
{
if(GUILayout.Button("Fix All in Scene"))
{
FixAllScriptReferencesInScene();
return;
}
}
GUI.backgroundColor = Color.cyan;
if((doFix && Event.current.type == EventType.Repaint) || GUILayout.Button("Reconnect"))
{
if(pbObjectMatches >= 3) // only increment for pb_Object otherwise the progress bar will fill 2x faster than it should
{
index++;
}
else
{
// Make sure that pb_Object is fixed first if we're automatically cycling objects.
if(doFix && ((Component)target).gameObject.GetComponent<pb_Object>() == null)
return;
}
if(!doFix)
{
Undo.RegisterCompleteObjectUndo(target, "Fix missing reference.");
}
// Debug.Log("Fix: " + (pbObjectMatches > 2 ? "pb_Object" : "pb_Entity") + " " + ((Component)target).gameObject.name);
scriptProperty.objectReferenceValue = pbObjectMatches >= 3 ? pb_monoscript : pe_monoscript;
scriptProperty.serializedObject.ApplyModifiedProperties();
scriptProperty = this.serializedObject.FindProperty("m_Script");
scriptProperty.serializedObject.Update();
if(doFix)
Next();
GUIUtility.ExitGUI();
}
GUI.backgroundColor = Color.white;
}
/**
* Scan the scene for gameObjects referencing `pb_DummyScript` and delete them.
*/
static void DeleteDummyScripts()
{
pb_DummyScript[] dummies = (pb_DummyScript[])Resources.FindObjectsOfTypeAll(typeof(pb_DummyScript));
dummies = dummies.Where(x => x.hideFlags == HideFlags.None).ToArray();
if(dummies.Length > 0)
{
int ret = EditorUtility.DisplayDialogComplex("Found Unrepairable Objects", "Repair script found " + dummies.Length + " missing components that could not be repaired. Would you like to delete those components now, or attempt to rebuild (ProBuilderize) them?", "Delete", "Cancel", "ProBuilderize");
switch(ret)
{
case 1: // cancel
{}
break;
default:
{
// Delete and ProBuilderize
if(ret == 2)
{
// Only interested in objects that have 2 null components (pb_Object and pb_Entity)
Object[] broken = (Object[])Resources.FindObjectsOfTypeAll(typeof(GameObject))
.Where(x => !x.Equals(null) &&
x is GameObject &&
((GameObject)x).GetComponents<pb_DummyScript>().Length == 2 &&
((GameObject)x).GetComponent<MeshRenderer>() != null &&
((GameObject)x).GetComponent<MeshFilter>() != null &&
((GameObject)x).GetComponent<MeshFilter>().sharedMesh != null
).ToArray();
broken = broken.Distinct().ToArray();
ProBuilder2.Actions.ProBuilderize.DoProBuilderize(System.Array.ConvertAll(broken, x => (GameObject)x).Select(x => x.GetComponent<MeshFilter>()), true);
}
// Always delete components
Undo.RecordObjects(dummies.Select(x=>x.gameObject).ToArray(), "Delete Broken Scripts");
for(int i = 0; i < dummies.Length; i++)
GameObject.DestroyImmediate( dummies[i] );
}
break;
}
}
}
/**
* Returns a formatted string with all properties in serialized object.
*/
static string SerializedObjectToString(SerializedObject serializedObject)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if(serializedObject == null)
{
sb.Append("NULL");
return sb.ToString();
}
SerializedProperty iterator = serializedObject.GetIterator();
iterator.Next(true);
while( iterator.Next(true) )
{
string tabs = "";
for(int i = 0; i < iterator.depth; i++) tabs += "\t";
sb.AppendLine(tabs + iterator.name + (iterator.propertyType == SerializedPropertyType.ObjectReference && iterator.type.Contains("Component") && iterator.objectReferenceValue == null ? " -> NULL" : "") );
tabs += " - ";
sb.AppendLine(tabs + "Type: (" + iterator.type + " / " + iterator.propertyType + " / " + " / " + iterator.name + ")");
sb.AppendLine(tabs + iterator.propertyPath);
sb.AppendLine(tabs + "Value: " + SerializedPropertyValue(iterator));
}
return sb.ToString();
}
/**
* Return a string from the value of a SerializedProperty.
*/
static string SerializedPropertyValue(SerializedProperty sp)
{
switch(sp.propertyType)
{
case SerializedPropertyType.Integer:
return sp.intValue.ToString();
case SerializedPropertyType.Boolean:
return sp.boolValue.ToString();
case SerializedPropertyType.Float:
return sp.floatValue.ToString();
case SerializedPropertyType.String:
return sp.stringValue.ToString();
case SerializedPropertyType.Color:
return sp.colorValue.ToString();
case SerializedPropertyType.ObjectReference:
return (sp.objectReferenceValue == null ? "null" : sp.objectReferenceValue.name);
case SerializedPropertyType.LayerMask:
return sp.intValue.ToString();
case SerializedPropertyType.Enum:
return sp.enumValueIndex.ToString();
case SerializedPropertyType.Vector2:
return sp.vector2Value.ToString();
case SerializedPropertyType.Vector3:
return sp.vector3Value.ToString();
// Not public api as of 4.3?
// case SerializedPropertyType.Vector4:
// return sp.vector4Value.ToString();
case SerializedPropertyType.Rect:
return sp.rectValue.ToString();
case SerializedPropertyType.ArraySize:
return sp.intValue.ToString();
case SerializedPropertyType.Character:
return "Character";
case SerializedPropertyType.AnimationCurve:
return sp.animationCurveValue.ToString();
case SerializedPropertyType.Bounds:
return sp.boundsValue.ToString();
case SerializedPropertyType.Gradient:
return "Gradient";
default:
return "Unknown type";
}
}
}
}
| |
// 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.Security.Cryptography.X509Certificates;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests.Pkcs12
{
[PlatformSpecific(TestPlatforms.Windows)]
public static class WriteToWindows
{
private static readonly PbeParameters s_win7Pbe = new PbeParameters(
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
HashAlgorithmName.SHA1,
2068);
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(999)]
[InlineData(1000)]
[InlineData(1024)]
[InlineData(2048)]
[InlineData(10000)]
[InlineData(123321)]
public static void WriteEmpty(int iterationCount)
{
Pkcs12Builder builder = new Pkcs12Builder();
string password = $"Password{iterationCount}IsMyVoice";
// Windows 7 through 10-1709 only support SHA-1 as the MAC PRF
builder.SealWithMac(password, HashAlgorithmName.SHA1, iterationCount);
byte[] emptyPfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(emptyPfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(0, coll.Collection.Count);
}
}
[Fact]
public static void WriteOneCertNoKeys_NoEncryption()
{
Pkcs12SafeContents contents = new Pkcs12SafeContents();
byte[] rawData;
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
{
contents.AddCertificate(cert);
rawData = cert.RawData;
}
Pkcs12Builder builder = new Pkcs12Builder();
builder.AddSafeContentsUnencrypted(contents);
const string password = nameof(WriteOneCertNoKeys_NoEncryption);
builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
byte[] pfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(rawData, coll.Collection[0].RawData);
Assert.False(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
}
}
[Fact]
public static void WriteOneCertNoKeys_Encrypted()
{
Pkcs12SafeContents contents = new Pkcs12SafeContents();
byte[] rawData;
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
{
contents.AddCertificate(cert);
rawData = cert.RawData;
}
const string password = nameof(WriteOneCertNoKeys_NoEncryption);
Pkcs12Builder builder = new Pkcs12Builder();
builder.AddSafeContentsEncrypted(
contents,
password,
s_win7Pbe);
builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
byte[] pfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(rawData, coll.Collection[0].RawData);
Assert.False(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
}
}
[Fact]
public static void WriteOneCertWithKey_Encrypted_SameSafe()
{
Pkcs12SafeContents contents = new Pkcs12SafeContents();
byte[] rawData;
Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(new byte[] { 1 });
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey(true))
using (RSA certKey = cert.GetRSAPrivateKey())
using (RSA exportableKey = certKey.MakeExportable())
{
Pkcs12CertBag certBag = contents.AddCertificate(cert);
certBag.Attributes.Add(localKeyId);
rawData = cert.RawData;
Pkcs12KeyBag keyBag = contents.AddKeyUnencrypted(exportableKey);
keyBag.Attributes.Add(localKeyId);
}
const string password = nameof(WriteOneCertWithKey_Encrypted_SameSafe);
Pkcs12Builder builder = new Pkcs12Builder();
builder.AddSafeContentsEncrypted(
contents,
password,
s_win7Pbe);
builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
byte[] pfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(rawData, coll.Collection[0].RawData);
Assert.True(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
}
}
[Fact]
public static void WriteOneCertWithKey_LikeWindows()
{
Pkcs12SafeContents safe1 = new Pkcs12SafeContents();
Pkcs12SafeContents safe2 = new Pkcs12SafeContents();
byte[] rawData;
Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(new byte[] { 1 });
const string password = nameof(WriteOneCertWithKey_LikeWindows);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey(true))
{
Pkcs12CertBag certBag = safe1.AddCertificate(cert);
certBag.Attributes.Add(localKeyId);
rawData = cert.RawData;
Pkcs12ShroudedKeyBag keyBag;
using (RSA rsa = cert.GetRSAPrivateKey())
{
keyBag = safe2.AddShroudedKey(
rsa,
password,
s_win7Pbe);
}
keyBag.Attributes.Add(localKeyId);
}
Pkcs12Builder builder = new Pkcs12Builder();
builder.AddSafeContentsEncrypted(
safe1,
password,
s_win7Pbe);
builder.AddSafeContentsUnencrypted(safe2);
builder.SealWithMac(password, HashAlgorithmName.SHA1, 2068);
byte[] pfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(1, coll.Collection.Count);
Assert.Equal(rawData, coll.Collection[0].RawData);
Assert.True(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
}
}
[Fact]
public static void WriteTwoCertsNoKeys_NoEncryption()
{
Pkcs12SafeContents contents = new Pkcs12SafeContents();
byte[] rawData1;
byte[] rawData2;
using (X509Certificate2 cert1 = Certificates.RSAKeyTransferCapi1.GetCertificate())
using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.GetCertificate())
{
// Windows seems to treat these as a stack. (LIFO)
contents.AddCertificate(cert2);
contents.AddCertificate(cert1);
rawData1 = cert1.RawData;
rawData2 = cert2.RawData;
}
Pkcs12Builder builder = new Pkcs12Builder();
builder.AddSafeContentsUnencrypted(contents);
const string password = nameof(WriteOneCertNoKeys_NoEncryption);
builder.SealWithMac(password, HashAlgorithmName.SHA1, 1024);
byte[] pfx = builder.Encode();
ImportedCollection coll =
ImportedCollection.Import(pfx, password, X509KeyStorageFlags.EphemeralKeySet);
using (coll)
{
Assert.Equal(2, coll.Collection.Count);
Assert.Equal(rawData1, coll.Collection[0].RawData);
Assert.Equal(rawData2, coll.Collection[1].RawData);
Assert.False(coll.Collection[0].HasPrivateKey, "coll.Collection[0].HasPrivateKey");
Assert.False(coll.Collection[1].HasPrivateKey, "coll.Collection[1].HasPrivateKey");
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075DeserializeCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Deserialize");
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetCA3075DeserializeBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Deserialize");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseXmlSerializerDeserializeShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace TestNamespace
{
public class UseXmlReaderForDeserialize
{
public void TestMethod(Stream stream)
{
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
}
}
}",
GetCA3075DeserializeCSharpResultAt(13, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Namespace TestNamespace
Public Class UseXmlReaderForDeserialize
Public Sub TestMethod(stream As Stream)
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
End Sub
End Class
End Namespace",
GetCA3075DeserializeBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInGetShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
public class UseXmlReaderForDeserialize
{
Stream stream;
public XmlSerializer Test
{
get
{
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
return serializer;
}
}
}",
GetCA3075DeserializeCSharpResultAt(13, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private stream As Stream
Public ReadOnly Property Test() As XmlSerializer
Get
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
Return serializer
End Get
End Property
End Class",
GetCA3075DeserializeBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInSetShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
public class UseXmlReaderForDeserialize
{
Stream stream;
XmlSerializer privateDoc;
public XmlSerializer SetDoc
{
set
{
if (value == null)
{
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
privateDoc = serializer;
}
else
privateDoc = value;
}
}
}",
GetCA3075DeserializeCSharpResultAt(16, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private stream As Stream
Private privateDoc As XmlSerializer
Public WriteOnly Property SetDoc() As XmlSerializer
Set
If value Is Nothing Then
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
privateDoc = serializer
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075DeserializeBasicResultAt(12, 17)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInTryShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
using System;
public class UseXmlReaderForDeserialize
{
Stream stream;
private void TestMethod()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075DeserializeCSharpResultAt(14, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private stream As Stream
Private Sub TestMethod()
Try
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075DeserializeBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInCatchShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
using System;
public class UseXmlReaderForDeserialize
{
Stream stream;
private void TestMethod()
{
try { }
catch (Exception) {
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
}
finally { }
}
}",
GetCA3075DeserializeCSharpResultAt(14, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private stream As Stream
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
Finally
End Try
End Sub
End Class",
GetCA3075DeserializeBasicResultAt(12, 13)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInFinallyShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
using System;
public class UseXmlReaderForDeserialize
{
Stream stream;
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally {
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
}
}
}",
GetCA3075DeserializeCSharpResultAt(15, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private stream As Stream
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
End Try
End Sub
End Class",
GetCA3075DeserializeBasicResultAt(14, 13)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInDelegateShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml.Serialization;
public class UseXmlReaderForDeserialize
{
delegate void Del();
Del d = delegate ()
{
Stream stream = null;
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
};
}",
GetCA3075DeserializeCSharpResultAt(13, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml.Serialization
Public Class UseXmlReaderForDeserialize
Private Delegate Sub Del()
Private d As Del = Sub()
Dim stream As Stream = Nothing
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
End Sub
End Class",
GetCA3075DeserializeBasicResultAt(11, 5)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeInAsyncAwaitShouldGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
class UseXmlReaderForDeserialize
{
private async Task TestMethod(Stream stream)
{
await Task.Run(() => {
XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(stream);
});
}
private async void TestMethod2()
{
await TestMethod(null);
}
}",
GetCA3075DeserializeCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Threading.Tasks
Imports System.Xml.Serialization
Class UseXmlReaderForDeserialize
Private Async Function TestMethod(stream As Stream) As Task
Await Task.Run(Function()
Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(stream)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod(Nothing)
End Sub
End Class",
GetCA3075DeserializeBasicResultAt(10, 9)
);
}
[Fact]
public async Task UseXmlSerializerDeserializeWithXmlReaderShouldNoGenerateDiagnosticAsync()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace TestNamespace
{
public class UseXmlReaderForDeserialize
{
public void TestMethod(XmlTextReader reader)
{
System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize));
serializer.Deserialize(reader);
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Namespace TestNamespace
Public Class UseXmlReaderForDeserialize
Public Sub TestMethod(reader As XmlTextReader)
Dim serializer As System.Xml.Serialization.XmlSerializer = New XmlSerializer(GetType(UseXmlReaderForDeserialize))
serializer.Deserialize(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using DemoSite.Areas.HelpPage.ModelDescriptions;
using DemoSite.Areas.HelpPage.Models;
namespace DemoSite.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TransformManyBlock.cs
//
//
// A propagator block that runs a function on each input to produce zero or more outputs.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks.Dataflow.Internal;
using System.Collections.ObjectModel;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>Provides a dataflow block that invokes a provided <see cref="System.Func{T,TResult}"/> delegate for every data element received.</summary>
/// <typeparam name="TInput">Specifies the type of data received and operated on by this <see cref="TransformManyBlock{TInput,TOutput}"/>.</typeparam>
/// <typeparam name="TOutput">Specifies the type of data output by this <see cref="TransformManyBlock{TInput,TOutput}"/>.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(TransformManyBlock<,>.DebugView))]
public sealed class TransformManyBlock<TInput, TOutput> : IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>, IDebuggerDisplay
{
/// <summary>The target side.</summary>
private readonly TargetCore<TInput> _target;
/// <summary>
/// Buffer used to reorder output sets that may have completed out-of-order between the target half and the source half.
/// This specialized reordering buffer supports streaming out enumerables if the message is the next in line.
/// </summary>
private readonly ReorderingBuffer<IEnumerable<TOutput>> _reorderingBuffer;
/// <summary>The source side.</summary>
private readonly SourceCore<TOutput> _source;
/// <summary>Gets the object to use for writing to the source when multiple threads may be involved.</summary>
/// <remarks>
/// If a reordering buffer is used, it is safe for multiple threads to write to concurrently and handles safe
/// access to the source. If there's no reordering buffer because no parallelism is used, then only one thread at
/// a time will try to access the source, anyway. But, if there's no reordering buffer and parallelism is being
/// employed, then multiple threads may try to access the source concurrently, in which case we need to manually
/// synchronize all such access, and this lock is used for that purpose.
/// </remarks>
private object ParallelSourceLock { get { return _source; } }
/// <summary>Initializes the <see cref="TransformManyBlock{TInput,TOutput}"/> with the specified function.</summary>
/// <param name="transform">
/// The function to invoke with each data element received. All of the data from the returned <see cref="System.Collections.Generic.IEnumerable{TOutput}"/>
/// will be made available as output from this <see cref="TransformManyBlock{TInput,TOutput}"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public TransformManyBlock(Func<TInput, IEnumerable<TOutput>> transform) :
this(transform, null, ExecutionDataflowBlockOptions.Default)
{ }
/// <summary>Initializes the <see cref="TransformManyBlock{TInput,TOutput}"/> with the specified function and <see cref="ExecutionDataflowBlockOptions"/>.</summary>
/// <param name="transform">
/// The function to invoke with each data element received. All of the data from the returned in the <see cref="System.Collections.Generic.IEnumerable{TOutput}"/>
/// will be made available as output from this <see cref="TransformManyBlock{TInput,TOutput}"/>.
/// </param>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformManyBlock{TInput,TOutput}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public TransformManyBlock(Func<TInput, IEnumerable<TOutput>> transform, ExecutionDataflowBlockOptions dataflowBlockOptions) :
this(transform, null, dataflowBlockOptions)
{ }
/// <summary>Initializes the <see cref="TransformManyBlock{TInput,TOutput}"/> with the specified function.</summary>
/// <param name="transform">
/// The function to invoke with each data element received. All of the data asynchronously returned in the <see cref="System.Collections.Generic.IEnumerable{TOutput}"/>
/// will be made available as output from this <see cref="TransformManyBlock{TInput,TOutput}"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public TransformManyBlock(Func<TInput, Task<IEnumerable<TOutput>>> transform) :
this(null, transform, ExecutionDataflowBlockOptions.Default)
{ }
/// <summary>Initializes the <see cref="TransformManyBlock{TInput,TOutput}"/> with the specified function and <see cref="ExecutionDataflowBlockOptions"/>.</summary>
/// <param name="transform">
/// The function to invoke with each data element received. All of the data asynchronously returned in the <see cref="System.Collections.Generic.IEnumerable{TOutput}"/>
/// will be made available as output from this <see cref="TransformManyBlock{TInput,TOutput}"/>.
/// </param>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformManyBlock{TInput,TOutput}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public TransformManyBlock(Func<TInput, Task<IEnumerable<TOutput>>> transform, ExecutionDataflowBlockOptions dataflowBlockOptions) :
this(null, transform, dataflowBlockOptions)
{ }
/// <summary>Initializes the <see cref="TransformManyBlock{TInput,TOutput}"/> with the specified function and <see cref="ExecutionDataflowBlockOptions"/>.</summary>
/// <param name="transformSync">The synchronous function to invoke with each data element received.</param>
/// <param name="transformAsync">The asynchronous function to invoke with each data element received.</param>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformManyBlock{TInput,TOutput}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="transformSync"/> and <paramref name="transformAsync"/> are both null (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
private TransformManyBlock(Func<TInput, IEnumerable<TOutput>> transformSync, Func<TInput, Task<IEnumerable<TOutput>>> transformAsync, ExecutionDataflowBlockOptions dataflowBlockOptions)
{
// Validate arguments. It's ok for the filterFunction to be null, but not the other parameters.
if (transformSync == null && transformAsync == null) throw new ArgumentNullException("transform");
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
Debug.Assert(transformSync == null ^ transformAsync == null, "Exactly one of transformSync and transformAsync must be null.");
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
// Initialize onItemsRemoved delegate if necessary
Action<ISourceBlock<TOutput>, int> onItemsRemoved = null;
if (dataflowBlockOptions.BoundedCapacity > 0)
onItemsRemoved = (owningSource, count) => ((TransformManyBlock<TInput, TOutput>)owningSource)._target.ChangeBoundingCount(-count);
// Initialize source component
_source = new SourceCore<TOutput>(this, dataflowBlockOptions,
owningSource => ((TransformManyBlock<TInput, TOutput>)owningSource)._target.Complete(exception: null, dropPendingMessages: true),
onItemsRemoved);
// If parallelism is employed, we will need to support reordering messages that complete out-of-order.
// However, a developer can override this with EnsureOrdered == false.
if (dataflowBlockOptions.SupportsParallelExecution && dataflowBlockOptions.EnsureOrdered)
{
_reorderingBuffer = new ReorderingBuffer<IEnumerable<TOutput>>(
this, (source, messages) => ((TransformManyBlock<TInput, TOutput>)source)._source.AddMessages(messages));
}
// Create the underlying target and source
if (transformSync != null) // sync
{
// If an enumerable function was provided, we can use synchronous completion, meaning
// that the target will consider a message fully processed as soon as the
// delegate returns.
_target = new TargetCore<TInput>(this,
messageWithId => ProcessMessage(transformSync, messageWithId),
_reorderingBuffer, dataflowBlockOptions, TargetCoreOptions.None);
}
else // async
{
Debug.Assert(transformAsync != null, "Incorrect delegate type.");
// If a task-based function was provided, we need to use asynchronous completion, meaning
// that the target won't consider a message completed until the task
// returned from that delegate has completed.
_target = new TargetCore<TInput>(this,
messageWithId => ProcessMessageWithTask(transformAsync, messageWithId),
_reorderingBuffer, dataflowBlockOptions, TargetCoreOptions.UsesAsyncCompletion);
}
// Link up the target half with the source half. In doing so,
// ensure exceptions are propagated, and let the source know no more messages will arrive.
// As the target has completed, and as the target synchronously pushes work
// through the reordering buffer when async processing completes,
// we know for certain that no more messages will need to be sent to the source.
_target.Completion.ContinueWith((completed, state) =>
{
var sourceCore = (SourceCore<TOutput>)state;
if (completed.IsFaulted) sourceCore.AddAndUnwrapAggregateException(completed.Exception);
sourceCore.Complete();
}, _source, CancellationToken.None, Common.GetContinuationOptions(), TaskScheduler.Default);
// It is possible that the source half may fault on its own, e.g. due to a task scheduler exception.
// In those cases we need to fault the target half to drop its buffered messages and to release its
// reservations. This should not create an infinite loop, because all our implementations are designed
// to handle multiple completion requests and to carry over only one.
_source.Completion.ContinueWith((completed, state) =>
{
var thisBlock = ((TransformManyBlock<TInput, TOutput>)state) as IDataflowBlock;
Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion.");
thisBlock.Fault(completed.Exception);
}, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
// Handle async cancellation requests by declining on the target
Common.WireCancellationToComplete(
dataflowBlockOptions.CancellationToken, Completion, state => ((TargetCore<TInput>)state).Complete(exception: null, dropPendingMessages: true), _target);
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
}
#endif
}
/// <summary>Processes the message with a user-provided transform function that returns an enumerable.</summary>
/// <param name="transformFunction">The transform function to use to process the message.</param>
/// <param name="messageWithId">The message to be processed.</param>
private void ProcessMessage(Func<TInput, IEnumerable<TOutput>> transformFunction, KeyValuePair<TInput, long> messageWithId)
{
Debug.Assert(transformFunction != null, "Function to invoke is required.");
bool userDelegateSucceeded = false;
try
{
// Run the user transform and store the results.
IEnumerable<TOutput> outputItems = transformFunction(messageWithId.Key);
userDelegateSucceeded = true;
StoreOutputItems(messageWithId, outputItems);
}
catch (Exception exc)
{
// If this exception represents cancellation, swallow it rather than shutting down the block.
if (!Common.IsCooperativeCancellation(exc)) throw;
}
finally
{
// If the user delegate failed, store an empty set in order
// to update the bounding count and reordering buffer.
if (!userDelegateSucceeded) StoreOutputItems(messageWithId, null);
}
}
/// <summary>Processes the message with a user-provided transform function that returns an observable.</summary>
/// <param name="function">The transform function to use to process the message.</param>
/// <param name="messageWithId">The message to be processed.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ProcessMessageWithTask(Func<TInput, Task<IEnumerable<TOutput>>> function, KeyValuePair<TInput, long> messageWithId)
{
Debug.Assert(function != null, "Function to invoke is required.");
// Run the transform function to get the resulting task
Task<IEnumerable<TOutput>> task = null;
Exception caughtException = null;
try
{
task = function(messageWithId.Key);
}
catch (Exception exc) { caughtException = exc; }
// If no task is available, either because null was returned or an exception was thrown, we're done.
if (task == null)
{
// If we didn't get a task because an exception occurred, store it
// (or if the exception was cancellation, just ignore it).
if (caughtException != null && !Common.IsCooperativeCancellation(caughtException))
{
Common.StoreDataflowMessageValueIntoExceptionData(caughtException, messageWithId.Key);
_target.Complete(caughtException, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false);
}
// Notify that we're done with this input and that we got no output for the input.
if (_reorderingBuffer != null)
{
// If there's a reordering buffer, "store" an empty output. This will
// internally both update the output buffer and decrement the bounding count
// accordingly.
StoreOutputItems(messageWithId, null);
_target.SignalOneAsyncMessageCompleted();
}
else
{
// As a fast path if we're not reordering, decrement the bounding
// count as part of our signaling that we're done, since this will
// internally take the lock only once, whereas the above path will
// take the lock twice.
_target.SignalOneAsyncMessageCompleted(boundingCountChange: -1);
}
return;
}
// We got back a task. Now wait for it to complete and store its results.
// Unlike with TransformBlock and ActionBlock, We run the continuation on the user-provided
// scheduler as we'll be running user code through enumerating the returned enumerable.
task.ContinueWith((completed, state) =>
{
var tuple = (Tuple<TransformManyBlock<TInput, TOutput>, KeyValuePair<TInput, long>>)state;
tuple.Item1.AsyncCompleteProcessMessageWithTask(completed, tuple.Item2);
}, Tuple.Create(this, messageWithId),
CancellationToken.None,
Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously),
_source.DataflowBlockOptions.TaskScheduler);
}
/// <summary>Completes the processing of an asynchronous message.</summary>
/// <param name="completed">The completed task storing the output data generated for an input message.</param>
/// <param name="messageWithId">The originating message</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void AsyncCompleteProcessMessageWithTask(
Task<IEnumerable<TOutput>> completed, KeyValuePair<TInput, long> messageWithId)
{
Debug.Assert(completed != null, "A task should have been provided.");
Debug.Assert(completed.IsCompleted, "The task should have been in a final state.");
switch (completed.Status)
{
case TaskStatus.RanToCompletion:
IEnumerable<TOutput> outputItems = completed.Result;
try
{
// Get the resulting enumerable and persist it.
StoreOutputItems(messageWithId, outputItems);
}
catch (Exception exc)
{
// Enumerating the user's collection failed. If this exception represents cancellation,
// swallow it rather than shutting down the block.
if (!Common.IsCooperativeCancellation(exc))
{
// The exception was not for cancellation. We must add the exception before declining
// and signaling completion, as the exception is part of the operation, and the completion
// conditions depend on this.
Common.StoreDataflowMessageValueIntoExceptionData(exc, messageWithId.Key);
_target.Complete(exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false);
}
}
break;
case TaskStatus.Faulted:
// We must add the exception before declining and signaling completion, as the exception
// is part of the operation, and the completion conditions depend on this.
AggregateException aggregate = completed.Exception;
Common.StoreDataflowMessageValueIntoExceptionData(aggregate, messageWithId.Key, targetInnerExceptions: true);
_target.Complete(aggregate, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: true);
goto case TaskStatus.Canceled;
case TaskStatus.Canceled:
StoreOutputItems(messageWithId, null); // notify the reordering buffer and decrement the bounding count
break;
default:
Debug.Assert(false, "The task should have been in a final state.");
break;
}
// Let the target know that one of the asynchronous operations it launched has completed.
_target.SignalOneAsyncMessageCompleted();
}
/// <summary>
/// Stores the output items, either into the reordering buffer or into the source half.
/// Ensures that the bounding count is correctly updated.
/// </summary>
/// <param name="messageWithId">The message with id.</param>
/// <param name="outputItems">The output items to be persisted.</param>
private void StoreOutputItems(
KeyValuePair<TInput, long> messageWithId, IEnumerable<TOutput> outputItems)
{
// If there's a reordering buffer, pass the data along to it.
// The reordering buffer will handle all details, including bounding.
if (_reorderingBuffer != null)
{
StoreOutputItemsReordered(messageWithId.Value, outputItems);
}
// Otherwise, output the data directly.
else if (outputItems != null)
{
// If this is a trusted type, output the data en mass.
if (outputItems is TOutput[] || outputItems is List<TOutput>)
{
StoreOutputItemsNonReorderedAtomic(outputItems);
}
else
{
// Otherwise, we need to take the slow path of enumerating
// each individual item.
StoreOutputItemsNonReorderedWithIteration(outputItems);
}
}
else if (_target.IsBounded)
{
// outputItems is null and there's no reordering buffer
// and we're bounding, so decrement the bounding count to
// signify that the input element we already accounted for
// produced no output
_target.ChangeBoundingCount(count: -1);
}
// else there's no reordering buffer, there are no output items, and we're not bounded,
// so there's nothing more to be done.
}
/// <summary>Stores the next item using the reordering buffer.</summary>
/// <param name="id">The ID of the item.</param>
/// <param name="item">The completed item.</param>
private void StoreOutputItemsReordered(long id, IEnumerable<TOutput> item)
{
Debug.Assert(_reorderingBuffer != null, "Expected a reordering buffer");
Debug.Assert(id != Common.INVALID_REORDERING_ID, "This ID should never have been handed out.");
// Grab info about the transform
TargetCore<TInput> target = _target;
bool isBounded = target.IsBounded;
// Handle invalid items (null enumerables) by delegating to the base
if (item == null)
{
_reorderingBuffer.AddItem(id, null, false);
if (isBounded) target.ChangeBoundingCount(count: -1);
return;
}
// If we can eagerly get the number of items in the collection, update the bounding count.
// This avoids the cost of updating it once per output item (since each update requires synchronization).
// Even if we're not bounding, we still want to determine whether the item is trusted so that we
// can immediately dump it out once we take the lock if we're the next item.
IList<TOutput> itemAsTrustedList = item as TOutput[];
if (itemAsTrustedList == null) itemAsTrustedList = item as List<TOutput>;
if (itemAsTrustedList != null && isBounded)
{
UpdateBoundingCountWithOutputCount(count: itemAsTrustedList.Count);
}
// Determine whether this id is the next item, and if it is and if we have a trusted list,
// try to output it immediately on the fast path. If it can be output, we're done.
// Otherwise, make forward progress based on whether we're next in line.
bool? isNextNullable = _reorderingBuffer.AddItemIfNextAndTrusted(id, itemAsTrustedList, itemAsTrustedList != null);
if (!isNextNullable.HasValue) return; // data was successfully output
bool isNextItem = isNextNullable.Value;
// By this point, either we're not the next item, in which case we need to make a copy of the
// data and store it, or we are the next item and can store it immediately but we need to enumerate
// the items and store them individually because we don't want to enumerate while holding a lock.
List<TOutput> itemCopy = null;
try
{
// If this is the next item, we can output it now.
if (isNextItem)
{
StoreOutputItemsNonReorderedWithIteration(item);
// here itemCopy remains null, so that base.AddItem will finish our interactions with the reordering buffer
}
else if (itemAsTrustedList != null)
{
itemCopy = itemAsTrustedList.ToList();
// we already got the count and updated the bounding count previously
}
else
{
// We're not the next item, and we're not trusted, so copy the data into a list.
// We need to enumerate outside of the lock in the base class.
int itemCount = 0;
try
{
itemCopy = item.ToList(); // itemCopy will remain null in the case of exception
itemCount = itemCopy.Count;
}
finally
{
// If we're here successfully, then itemCount is the number of output items
// we actually received, and we should update the bounding count with it.
// If we're here because ToList threw an exception, then itemCount will be 0,
// and we still need to update the bounding count with this in order to counteract
// the increased bounding count for the corresponding input.
if (isBounded) UpdateBoundingCountWithOutputCount(count: itemCount);
}
}
// else if the item isn't valid, the finally block will see itemCopy as null and output invalid
}
finally
{
// Tell the base reordering buffer that we're done. If we already output
// all of the data, itemCopy will be null, and we just pass down the invalid item.
// If we haven't, pass down the real thing. We do this even in the case of an exception,
// in which case this will be a dummy element.
_reorderingBuffer.AddItem(id, itemCopy, itemIsValid: itemCopy != null);
}
}
/// <summary>
/// Stores the trusted enumerable en mass into the source core.
/// This method does not go through the reordering buffer.
/// </summary>
/// <param name="outputItems"></param>
private void StoreOutputItemsNonReorderedAtomic(IEnumerable<TOutput> outputItems)
{
Debug.Assert(_reorderingBuffer == null, "Expected not to have a reordering buffer");
Debug.Assert(outputItems is TOutput[] || outputItems is List<TOutput>, "outputItems must be a list we've already vetted as trusted");
if (_target.IsBounded) UpdateBoundingCountWithOutputCount(count: ((ICollection<TOutput>)outputItems).Count);
if (_target.DataflowBlockOptions.MaxDegreeOfParallelism == 1)
{
_source.AddMessages(outputItems);
}
else
{
lock (ParallelSourceLock)
{
_source.AddMessages(outputItems);
}
}
}
/// <summary>
/// Stores the untrusted enumerable into the source core.
/// This method does not go through the reordering buffer.
/// </summary>
/// <param name="outputItems">The untrusted enumerable.</param>
private void StoreOutputItemsNonReorderedWithIteration(IEnumerable<TOutput> outputItems)
{
// The _source we're adding to isn't thread-safe, so we need to determine
// whether we need to lock. If the block is configured with a max degree
// of parallelism of 1, then only one transform can run at a time, and so
// we don't need to lock. Similarly, if there's a reordering buffer, then
// it guarantees that we're invoked serially, and we don't need to lock.
bool isSerial =
_target.DataflowBlockOptions.MaxDegreeOfParallelism == 1 ||
_reorderingBuffer != null;
// If we're bounding, we need to increment the bounded count
// for each individual item as we enumerate it.
if (_target.IsBounded)
{
// When the input item that generated this
// output was loaded, we incremented the bounding count. If it only
// output a single a item, then we don't need to touch the bounding count.
// Otherwise, we need to adjust the bounding count accordingly.
bool outputFirstItem = false;
try
{
foreach (TOutput item in outputItems)
{
if (outputFirstItem) _target.ChangeBoundingCount(count: 1);
else outputFirstItem = true;
if (isSerial)
{
_source.AddMessage(item);
}
else
{
lock (ParallelSourceLock) // don't hold lock while enumerating
{
_source.AddMessage(item);
}
}
}
}
finally
{
if (!outputFirstItem) _target.ChangeBoundingCount(count: -1);
}
}
// If we're not bounding, just output each individual item.
else
{
if (isSerial)
{
foreach (TOutput item in outputItems)
_source.AddMessage(item);
}
else
{
foreach (TOutput item in outputItems)
{
lock (ParallelSourceLock) // don't hold lock while enumerating
{
_source.AddMessage(item);
}
}
}
}
}
/// <summary>
/// Updates the bounding count based on the number of output items
/// generated for a single input.
/// </summary>
/// <param name="count">The number of output items.</param>
private void UpdateBoundingCountWithOutputCount(int count)
{
// We already incremented the count for a single input item, and
// that input spawned 0 or more outputs. Take the input tracking
// into account when figuring out how much to increment or decrement
// the bounding count.
Debug.Assert(_target.IsBounded, "Expected to be in bounding mode.");
if (count > 1) _target.ChangeBoundingCount(count - 1);
else if (count == 0) _target.ChangeBoundingCount(-1);
else Debug.Assert(count == 1, "Count shouldn't be negative.");
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
public void Complete() { _target.Complete(exception: null, dropPendingMessages: false); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
_target.Complete(exception, dropPendingMessages: true);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
public bool TryReceive(Predicate<TOutput> filter, out TOutput item) { return _source.TryReceive(filter, out item); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
public bool TryReceiveAll(out IList<TOutput> items) { return _source.TryReceiveAll(out items); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
public Task Completion { get { return _source.Completion; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="InputCount"]/*' />
public int InputCount { get { return _target.InputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' />
public int OutputCount { get { return _source.OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
return _target.OfferMessage(messageHeader, messageValue, source, consumeToAccept);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
TOutput ISourceBlock<TOutput>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out bool messageConsumed)
{
return _source.ConsumeMessage(messageHeader, target, out messageConsumed);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
bool ISourceBlock<TOutput>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
return _source.ReserveMessage(messageHeader, target);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
void ISourceBlock<TOutput>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
_source.ReleaseReservation(messageHeader, target);
}
/// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary>
private int InputCountForDebugger { get { return _target.GetDebuggingInformation().InputCount; } }
/// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary>
private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' />
public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0}, InputCount={1}, OutputCount={2}",
Common.GetNameForDebugger(this, _source.DataflowBlockOptions),
InputCountForDebugger,
OutputCountForDebugger);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for the TransformManyBlock.</summary>
private sealed class DebugView
{
/// <summary>The transform many block being viewed.</summary>
private readonly TransformManyBlock<TInput, TOutput> _transformManyBlock;
/// <summary>The target half of the block being viewed.</summary>
private readonly TargetCore<TInput>.DebuggingInformation _targetDebuggingInformation;
/// <summary>The source half of the block being viewed.</summary>
private readonly SourceCore<TOutput>.DebuggingInformation _sourceDebuggingInformation;
/// <summary>Initializes the debug view.</summary>
/// <param name="transformManyBlock">The transform being viewed.</param>
public DebugView(TransformManyBlock<TInput, TOutput> transformManyBlock)
{
Debug.Assert(transformManyBlock != null, "Need a block with which to construct the debug view.");
_transformManyBlock = transformManyBlock;
_targetDebuggingInformation = transformManyBlock._target.GetDebuggingInformation();
_sourceDebuggingInformation = transformManyBlock._source.GetDebuggingInformation();
}
/// <summary>Gets the messages waiting to be processed.</summary>
public IEnumerable<TInput> InputQueue { get { return _targetDebuggingInformation.InputQueue; } }
/// <summary>Gets any postponed messages.</summary>
public QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _targetDebuggingInformation.PostponedMessages; } }
/// <summary>Gets the messages waiting to be received.</summary>
public IEnumerable<TOutput> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } }
/// <summary>Gets the number of input operations currently in flight.</summary>
public int CurrentDegreeOfParallelism { get { return _targetDebuggingInformation.CurrentDegreeOfParallelism; } }
/// <summary>Gets the task being used for output processing.</summary>
public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
public ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _targetDebuggingInformation.DataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
public bool IsDecliningPermanently { get { return _targetDebuggingInformation.IsDecliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } }
/// <summary>Gets the block's Id.</summary>
public int Id { get { return Common.GetBlockId(_transformManyBlock); } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public TargetRegistry<TOutput> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public ITargetBlock<TOutput> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } }
}
}
}
| |
/* ====================================================================
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.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
using NPOI.HSSF.Record;
/**
* Title: Sup Book (EXTERNALBOOK)
* Description: A External Workbook Description (Suplemental Book)
* Its only a dummy record for making new ExternSheet Record
* REFERENCE: 5.38
* @author Libin Roman (Vista Portal LDT. Developer)
* @author Andrew C. Oliver (acoliver@apache.org)
*
*/
public class SupBookRecord : StandardRecord
{
private static POILogger logger = POILogFactory.GetLogger(typeof(SupBookRecord));
public const short sid = 0x1AE;
private const short SMALL_RECORD_SIZE = 4;
private const short TAG_INTERNAL_REFERENCES = 0x0401;
private const short TAG_ADD_IN_FUNCTIONS = 0x3A01;
private short field_1_number_of_sheets;
private String field_2_encoded_url;
private String[] field_3_sheet_names;
private bool _isAddInFunctions;
public const char CH_VOLUME = (char)1;
public const char CH_SAME_VOLUME = (char)2;
public const char CH_DOWN_DIR = (char)3;
public const char CH_UP_DIR = (char)4;
public const char CH_LONG_VOLUME = (char)5;
public const char CH_STARTUP_DIR = (char)6;
public const char CH_ALT_STARTUP_DIR = (char)7;
public const char CH_LIB_DIR = (char)8;
public static readonly char PATH_SEPERATOR = System.IO.Path.DirectorySeparatorChar;
public static SupBookRecord CreateInternalReferences(short numberOfSheets)
{
return new SupBookRecord(false, numberOfSheets);
}
public static SupBookRecord CreateAddInFunctions()
{
return new SupBookRecord(true, (short)1);
}
public static SupBookRecord CreateExternalReferences(String url, String[] sheetNames)
{
return new SupBookRecord(url, sheetNames);
}
private SupBookRecord(bool IsAddInFuncs, short numberOfSheets)
{
// else not 'External References'
field_1_number_of_sheets = numberOfSheets;
field_2_encoded_url = null;
field_3_sheet_names = null;
_isAddInFunctions = IsAddInFuncs;
}
public SupBookRecord(String url, String[] sheetNames)
{
field_1_number_of_sheets = (short)sheetNames.Length;
field_2_encoded_url = url;
field_3_sheet_names = sheetNames;
_isAddInFunctions = false;
}
/**
* Constructs a Extern Sheet record and Sets its fields appropriately.
*
* @param id id must be 0x16 or an exception will be throw upon validation
* @param size the size of the data area of the record
* @param data data of the record (should not contain sid/len)
*/
public SupBookRecord(RecordInputStream in1)
{
int recLen = in1.Remaining;
field_1_number_of_sheets = in1.ReadShort();
if (recLen > SMALL_RECORD_SIZE)
{
// 5.38.1 External References
_isAddInFunctions = false;
field_2_encoded_url = in1.ReadString();
String[] sheetNames = new String[field_1_number_of_sheets];
for (int i = 0; i < sheetNames.Length; i++)
{
sheetNames[i] = in1.ReadString();
}
field_3_sheet_names = sheetNames;
return;
}
// else not 'External References'
field_2_encoded_url = null;
field_3_sheet_names = null;
short nextShort = in1.ReadShort();
if (nextShort == TAG_INTERNAL_REFERENCES)
{
// 5.38.2 'Internal References'
_isAddInFunctions = false;
}
else if (nextShort == TAG_ADD_IN_FUNCTIONS)
{
// 5.38.3 'Add-In Functions'
_isAddInFunctions = true;
if (field_1_number_of_sheets != 1)
{
throw new Exception("Expected 0x0001 for number of sheets field in 'Add-In Functions' but got ("
+ field_1_number_of_sheets + ")");
}
}
else
{
throw new Exception("invalid EXTERNALBOOK code ("
+ StringUtil.ToHexString(nextShort) + ")");
}
}
public bool IsExternalReferences
{
get { return field_3_sheet_names != null; }
}
public bool IsInternalReferences
{
get
{
return field_3_sheet_names == null && !_isAddInFunctions;
}
}
public bool IsAddInFunctions
{
get
{
return field_3_sheet_names == null && _isAddInFunctions;
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(GetType().Name).Append(" [SUPBOOK ");
if (IsExternalReferences)
{
sb.Append("External References");
sb.Append(" nSheets=").Append(field_1_number_of_sheets);
sb.Append(" url=").Append(field_2_encoded_url);
}
else if (_isAddInFunctions)
{
sb.Append("Add-In Functions");
}
else
{
sb.Append("Internal References ");
sb.Append(" nSheets= ").Append(field_1_number_of_sheets);
}
return sb.ToString();
}
protected override int DataSize
{
get
{
if (!IsExternalReferences)
{
return SMALL_RECORD_SIZE;
}
int sum = 2; // u16 number of sheets
sum += StringUtil.GetEncodedSize(field_2_encoded_url);
for (int i = 0; i < field_3_sheet_names.Length; i++)
{
sum += StringUtil.GetEncodedSize(field_3_sheet_names[i]);
}
return sum;
}
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_number_of_sheets);
if (IsExternalReferences)
{
StringUtil.WriteUnicodeString(out1, field_2_encoded_url);
for (int i = 0; i < field_3_sheet_names.Length; i++)
{
StringUtil.WriteUnicodeString(out1, field_3_sheet_names[i]);
}
}
else
{
int field2val = _isAddInFunctions ? TAG_ADD_IN_FUNCTIONS : TAG_INTERNAL_REFERENCES;
out1.WriteShort(field2val);
}
}
public short NumberOfSheets
{
get { return field_1_number_of_sheets; }
set { field_1_number_of_sheets = value; }
}
public override short Sid
{
get { return sid; }
}
public String URL
{
get
{
String encodedUrl = field_2_encoded_url;
switch ((int)encodedUrl[0])
{
case 0: // Reference to an empty workbook name
return encodedUrl.Substring(1); // will this just be empty string?
case 1: // encoded file name
return DecodeFileName(encodedUrl);
case 2: // Self-referential external reference
return encodedUrl.Substring(1);
}
return encodedUrl;
}
set
{
//Keep the first marker character!
field_2_encoded_url = field_2_encoded_url.Substring(0, 1) + value;
}
}
private static String DecodeFileName(String encodedUrl)
{
/* see "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" */
StringBuilder sb = new StringBuilder();
for (int i = 1; i < encodedUrl.Length; i++)
{
char c = encodedUrl[i];
switch (c)
{
case CH_VOLUME:
char driveLetter = encodedUrl[(++i)];
if (driveLetter == '@')
{
sb.Append("\\\\");
}
else
{
//Windows notation for drive letters
sb.Append(driveLetter).Append(":");
}
break;
case CH_SAME_VOLUME:
sb.Append(PATH_SEPERATOR);
break;
case CH_DOWN_DIR:
sb.Append(PATH_SEPERATOR);
break;
case CH_UP_DIR:
sb.Append("..").Append(PATH_SEPERATOR);
break;
case CH_LONG_VOLUME:
//Don't known to handle...
logger.Log(POILogger.WARN, "Found unexpected key: ChLongVolume - IGNORING");
break;
case CH_STARTUP_DIR:
case CH_ALT_STARTUP_DIR:
case CH_LIB_DIR:
logger.Log(POILogger.WARN, "EXCEL.EXE path unkown - using this directoy instead: .");
sb.Append(".").Append(PATH_SEPERATOR);
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
public String[] SheetNames
{
get
{
return (String[])field_3_sheet_names.Clone();
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter
// and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g.
//
// await nonGenericTask;
// =====================
// var $awaiter = nonGenericTask.GetAwaiter();
// if (!$awaiter.IsCompleted)
// {
// SPILL:
// $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this);
// return;
// Label:
// UNSPILL;
// }
// $awaiter.GetResult();
//
// result += await genericTask.ConfigureAwait(false);
// ===================================================================================
// var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter();
// if (!$awaiter.IsCompleted)
// {
// SPILL;
// $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this);
// return;
// Label:
// UNSPILL;
// }
// result += $awaiter.GetResult();
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
using System.Diagnostics.Tracing;
// NOTE: For performance reasons, initialization is not verified. If a developer
// incorrectly initializes a task awaiter, which should only be done by the compiler,
// NullReferenceExceptions may be generated (the alternative would be for us to detect
// this case and then throw a different exception instead). This is the same tradeoff
// that's made with other compiler-focused value types like List<T>.Enumerator.
namespace System.Runtime.CompilerServices
{
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task m_task;
/// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param>
internal TaskAwaiter(Task task)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public void GetResult()
{
ValidateEnd(m_task);
}
/// <summary>
/// Fast checks for the end of an await operation to determine whether more needs to be done
/// prior to completing the await.
/// </summary>
/// <param name="task">The awaited task.</param>
internal static void ValidateEnd(Task task)
{
// Fast checks that can be inlined.
if (task.IsWaitNotificationEnabledOrNotRanToCompletion)
{
// If either the end await bit is set or we're not completed successfully,
// fall back to the slower path.
HandleNonSuccessAndDebuggerNotification(task);
}
}
/// <summary>
/// Ensures the task is completed, triggers any necessary debugger breakpoints for completing
/// the await on the task, and throws an exception if the task did not complete successfully.
/// </summary>
/// <param name="task">The awaited task.</param>
private static void HandleNonSuccessAndDebuggerNotification(Task task)
{
// NOTE: The JIT refuses to inline ValidateEnd when it contains the contents
// of HandleNonSuccessAndDebuggerNotification, hence the separation.
// Synchronously wait for the task to complete. When used by the compiler,
// the task will already be complete. This code exists only for direct GetResult use,
// for cases where the same exception propagation semantics used by "await" are desired,
// but where for one reason or another synchronous rather than asynchronous waiting is needed.
if (!task.IsCompleted)
{
bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken));
Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
}
// Now that we're done, alert the debugger if so requested
task.NotifyDebuggerOfWaitCompletionIfNecessary();
// And throw an exception if the task is faulted or canceled.
if (!task.IsRanToCompletion) ThrowForNonSuccess(task);
}
/// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary>
private static void ThrowForNonSuccess(Task task)
{
Contract.Requires(task.IsCompleted, "Task must have been completed by now.");
Contract.Requires(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully.");
// Handle whether the task has been canceled or faulted
switch (task.Status)
{
// If the task completed in a canceled state, throw an OperationCanceledException.
// This will either be the OCE that actually caused the task to cancel, or it will be a new
// TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the
// completed task's CancellationToken if it has one, including that CT in the OCE.
case TaskStatus.Canceled:
var oceEdi = task.GetCancellationExceptionDispatchInfo();
if (oceEdi != null)
{
oceEdi.Throw();
Contract.Assert(false, "Throw() should have thrown");
}
throw new TaskCanceledException(task);
// If the task faulted, throw its first exception,
// even if it contained more than one.
case TaskStatus.Faulted:
var edis = task.GetExceptionDispatchInfos();
if (edis.Count > 0)
{
edis[0].Throw();
Contract.Assert(false, "Throw() should have thrown");
break; // Necessary to compile: non-reachable, but compiler can't determine that
}
else
{
Contract.Assert(false, "There should be exceptions if we're Faulted.");
throw task.Exception;
}
}
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="task">The task being awaited.</param>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
/// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
[SecurityCritical]
internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext)
{
if (continuation == null) throw new ArgumentNullException("continuation");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// If TaskWait* ETW events are enabled, trace a beginning event for this await
// and set up an ending event to be traced when the asynchronous await completes.
if ( TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled)
{
continuation = OutputWaitEtwEvents(task, continuation);
}
// Set the continuation onto the awaited task.
task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext, ref stackMark);
}
/// <summary>
/// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event.
/// </summary>
/// <param name="task">The task being awaited.</param>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <returns>The action to use as the actual continuation.</returns>
private static Action OutputWaitEtwEvents(Task task, Action continuation)
{
Contract.Requires(task != null, "Need a task to wait on");
Contract.Requires(continuation != null, "Need a continuation to invoke when the wait completes");
if (Task.s_asyncDebuggingEnabled)
{
Task.AddToActiveTasks(task);
}
var etwLog = TplEtwProvider.Log;
if (etwLog.IsEnabled())
{
// ETW event for Task Wait Begin
var currentTaskAtBegin = Task.InternalCurrent;
// If this task's continuation is another task, get it.
var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation);
etwLog.TaskWaitBegin(
(currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0),
task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous,
(continuationTask != null ? continuationTask.Id : 0), System.Threading.Thread.GetDomainID());
}
// Create a continuation action that outputs the end event and then invokes the user
// provided delegate. This incurs the allocations for the closure/delegate, but only if the event
// is enabled, and in doing so it allows us to pass the awaited task's information into the end event
// in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter
// just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred).
return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, () =>
{
if (Task.s_asyncDebuggingEnabled)
{
Task.RemoveFromActiveTasks(task.Id);
}
// ETW event for Task Wait End.
Guid prevActivityId = new Guid();
bool bEtwLogEnabled = etwLog.IsEnabled();
if (bEtwLogEnabled)
{
var currentTaskAtEnd = Task.InternalCurrent;
etwLog.TaskWaitEnd(
(currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0),
task.Id);
// Ensure the continuation runs under the activity ID of the task that completed for the
// case the antecendent is a promise (in the other cases this is already the case).
if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(task.Id), out prevActivityId);
}
// Invoke the original continuation provided to OnCompleted.
continuation();
if (bEtwLogEnabled)
{
etwLog.TaskWaitContinuationComplete(task.Id);
if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
EventSource.SetCurrentThreadActivityId(prevActivityId);
}
});
}
}
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task<TResult> m_task;
/// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param>
internal TaskAwaiter(Task<TResult> task)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public TResult GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
return m_task.ResultOnSuccess;
}
}
/// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
public struct ConfiguredTaskAwaitable
{
/// <summary>The task being awaited.</summary>
private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaitable requires a task to await.");
m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext);
}
/// <summary>Gets an awaiter for this awaitable.</summary>
/// <returns>The awaiter.</returns>
public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter()
{
return m_configuredTaskAwaiter;
}
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task m_task;
/// <summary>Whether to attempt marshaling back to the original context.</summary>
private readonly bool m_continueOnCapturedContext;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured
/// when BeginAwait is called; otherwise, false.
/// </param>
internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
m_continueOnCapturedContext = continueOnCapturedContext;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public void GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
}
}
}
/// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
public struct ConfiguredTaskAwaitable<TResult>
{
/// <summary>The underlying awaitable on whose logic this awaitable relies.</summary>
private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext)
{
m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext);
}
/// <summary>Gets an awaiter for this awaitable.</summary>
/// <returns>The awaiter.</returns>
public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter()
{
return m_configuredTaskAwaiter;
}
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task<TResult> m_task;
/// <summary>Whether to attempt marshaling back to the original context.</summary>
private readonly bool m_continueOnCapturedContext;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
m_continueOnCapturedContext = continueOnCapturedContext;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public TResult GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
return m_task.ResultOnSuccess;
}
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using IO;
using Nancy.Extensions;
using Session;
/// <summary>
/// Encapsulates HTTP-request information to an Nancy application.
/// </summary>
public class Request : IDisposable
{
private readonly List<HttpFile> files = new List<HttpFile>();
private dynamic form = new DynamicDictionary();
private IDictionary<string, string> cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="path">The path of the requested resource, relative to the "Nancy root". This shold not not include the scheme, host name, or query portion of the URI.</param>
/// <param name="scheme">The HTTP protocol that was used by the client.</param>
public Request(string method, string path, string scheme)
: this(method, new Url { Path = path, Scheme = scheme })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="url">The <see cref="Url"/>url of the requested resource</param>
/// <param name="headers">The headers that was passed in by the client.</param>
/// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
/// <param name="ip">The client's IP address</param>
/// <param name="certificate">The client's certificate when present.</param>
public Request(string method, Url url, RequestStream body = null, IDictionary<string, IEnumerable<string>> headers = null, string ip = null, byte[] certificate = null)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentOutOfRangeException("method");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Path == null)
{
throw new ArgumentNullException("url.Path");
}
if (String.IsNullOrEmpty(url.Scheme))
{
throw new ArgumentOutOfRangeException("url.Scheme");
}
this.UserHostAddress = ip;
this.Url = url;
this.Method = method;
this.Query = url.Query.AsQueryDictionary();
this.Body = body ?? RequestStream.FromStream(new MemoryStream());
this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());
this.Session = new NullSessionProvider();
if (certificate != null && certificate.Length != 0)
{
this.ClientCertificate = new X509Certificate2(certificate);
}
if (String.IsNullOrEmpty(this.Url.Path))
{
this.Url.Path = "/";
}
this.ParseFormData();
this.RewriteMethod();
}
/// <summary>
/// Gets the certificate sent by the client.
/// </summary>
public X509Certificate ClientCertificate { get; private set; }
/// <summary>
/// Gets the IP address of the client
/// </summary>
public string UserHostAddress { get; private set; }
/// <summary>
/// Gets or sets the HTTP data transfer method used by the client.
/// </summary>
/// <value>The method.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the url
/// </summary>
public Url Url { get; private set; }
/// <summary>
/// Gets the request path, relative to the base path.
/// Used for route matching etc.
/// </summary>
public string Path
{
get
{
return this.Url.Path;
}
}
/// <summary>
/// Gets the querystring data of the requested resource.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of querystring data.</value>
public dynamic Query { get; set; }
/// <summary>
/// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body
/// </summary>
/// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value>
public RequestStream Body { get; private set; }
/// <summary>
/// Gets the request cookies.
/// </summary>
public IDictionary<string, string> Cookies
{
get { return this.cookies ?? (this.cookies = this.GetCookieData()); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session { get; set; }
/// <summary>
/// Gets the cookie data from the request header if it exists
/// </summary>
/// <returns>Cookies dictionary</returns>
private IDictionary<string, string> GetCookieData()
{
var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!this.Headers.Cookie.Any())
{
return cookieDictionary;
}
var values = this.Headers["cookie"].First().TrimEnd(';').Split(';');
foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))
{
var cookieName = parts[0].Trim();
if (parts.Length == 1)
{
if (cookieName.Equals("HttpOnly", StringComparison.InvariantCulture) ||
cookieName.Equals("Secure", StringComparison.InvariantCulture))
{
continue;
}
}
cookieDictionary[cookieName] = parts[1];
}
return cookieDictionary;
}
/// <summary>
/// Gets a collection of files sent by the client-
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value>
public IEnumerable<HttpFile> Files
{
get { return this.files; }
}
/// <summary>
/// Gets the form data of the request.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value>
/// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>
public dynamic Form
{
get { return this.form; }
}
/// <summary>
/// Gets the HTTP headers sent by the client.
/// </summary>
/// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value>
/// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks>
public RequestHeaders Headers { get; private set; }
public void Dispose()
{
((IDisposable)this.Body).Dispose();
}
private void ParseFormData()
{
if (string.IsNullOrEmpty(this.Headers.ContentType))
{
return;
}
var contentType = this.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var reader = new StreamReader(this.Body);
this.form = reader.ReadToEnd().AsQueryDictionary();
this.Body.Position = 0;
}
if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
var multipart = new HttpMultipart(this.Body, boundary);
var formValues =
new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase);
foreach (var httpMultipartBoundary in multipart.GetBoundaries())
{
if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
{
var reader =
new StreamReader(httpMultipartBoundary.Value);
formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
}
else
{
this.files.Add(new HttpFile(httpMultipartBoundary));
}
}
foreach (var key in formValues.AllKeys.Where(key => key != null))
{
this.form[key] = formValues[key];
}
this.Body.Position = 0;
}
private void RewriteMethod()
{
if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return;
}
var overrides =
new List<Tuple<string, string>>
{
Tuple.Create("_method form input element", (string)this.Form["_method"]),
Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]),
Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault())
};
var providedOverride =
overrides.Where(x => !string.IsNullOrEmpty(x.Item2));
if (!providedOverride.Any())
{
return;
}
if (providedOverride.Count() > 1)
{
var overrideSources =
string.Join(", ", providedOverride);
var errorMessage =
string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources);
throw new InvalidOperationException(errorMessage);
}
this.Method = providedOverride.Single().Item2;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using DotSpatial.Data;
namespace DotSpatial.Symbology
{
/// <summary>
/// This is should not be instantiated because it cannot in itself perform the necessary functions.
/// Instead, most of the specified functionality must be implemented in the more specific classes.
/// This is also why there is no direct constructor for this class. You can use the static
/// "FromFile" or "FromFeatureLayer" to create FeatureLayers from a file.
/// </summary>
public interface IFeatureLayer : ILayer
{
#region Events
/// <summary>
/// Occurs after a new symbolic scheme has been applied to the layer.
/// </summary>
event EventHandler SchemeApplied;
/// <summary>
/// Occurs after a snapshot is taken, and contains an event argument with the bitmap
/// to be displayed.
/// </summary>
event EventHandler<SnapShotEventArgs> SnapShotTaken;
/// <summary>
/// Occurs before the attribute Table is displayed, also allowing this event to be handled.
/// </summary>
event HandledEventHandler ViewAttributes;
#endregion
#region Properties
/// <summary>
/// Gets or sets the base FeatureSet.
/// </summary>
new IFeatureSet DataSet { get; set; }
/// <summary>
/// Gets or sets the fast drawn states. Controls the drawn states according to a feature index. This is used if the EditMode is
/// false. When EditMode is true, then drawn states are tied to the features instead.
/// </summary>
FastDrawnState[] DrawnStates { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the DrawnStates are needed. If nothing is selected,
/// and there is only one category, and there is no filter expression on that category, then this should be false.
/// </summary>
bool DrawnStatesNeeded { get; set; }
/// <summary>
/// Gets or sets a value indicating whether feature index is ignored, and features
/// are assumed to be entirely loaded into ram. If edit mode is false, then index
/// is used instead and features are not assumed to be loaded into ram.
/// </summary>
bool EditMode { get; set; }
/// <summary>
/// Gets or sets the label layer
/// </summary>
[Category("General")]
[Description("Gets or sets the label layer associated with this feature layer.")]
ILabelLayer LabelLayer { get; set; }
/// <summary>
/// Gets a Selection class that is allows the user to cycle through all the unselected features with
/// a for each method, even if the features are in many categories.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
ISelection Selection { get; }
/// <summary>
/// Gets or sets the shared characteristics to use with the selected features.
/// </summary>
IFeatureSymbolizer SelectionSymbolizer { get; set; }
/// <summary>
/// Gets or sets a value indicating whether labels should be drawn.
/// </summary>
[Category("Behavior")]
[Description("Gets or sets whether labels should be drawn.")]
bool ShowLabels { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this layer can be used for snapping.
/// </summary>
[Category("Behavior")]
[Description("Gets or sets a value indicating whether this layer can be used for snapping.")]
bool Snappable { get; set; }
/// <summary>
/// Gets or sets and interface for the shared symbol characteristics between point, line and polygon features
/// </summary>
IFeatureSymbolizer Symbolizer { get; set; }
/// <summary>
/// Gets or sets the current feature scheme, but to change it ApplyScheme should be called, so that
/// feature categories are updated as well.
/// </summary>
IFeatureScheme Symbology { get; set; }
#endregion
#region Methods
/// <summary>
/// Applies the specified scheme to this layer, applying the filter constraints in the scheme.
/// It is at this time when features are grouped as a one-time operation into their symbol
/// categories, so that this doesn't have to happen independently each drawing cycle.
/// </summary>
/// <param name="inScheme">The scheme to be applied to this layer.</param>
void ApplyScheme(IFeatureScheme inScheme);
/// <summary>
/// Assigns the fast drawn states based on the latest feature setup.
/// </summary>
void AssignFastDrawnStates();
/// <summary>
/// This method actually draws the image to the snapshot using the graphics object. This should be
/// overridden in sub-classes because the drawing methods are very different.
/// </summary>
/// <param name="g">A graphics object to draw to</param>
/// <param name="p">A projection handling interface designed to translate geographic coordinates to screen
/// coordinates</param>
void DrawSnapShot(Graphics g, IProj p);
/// <summary>
/// Saves a featureset with only the selected features to the specified fileName.
/// </summary>
/// <param name="fileName">The string fileName to export features to.</param>
void ExportSelection(string fileName);
/// <summary>
/// Gets the visible characteristic for an individual feature, regardless of whether
/// this layer is in edit mode.
/// </summary>
/// <param name="index">Index of the feature.</param>
/// <returns>The category of the feature.</returns>
IFeatureCategory GetCategory(int index);
/// <summary>
/// Gets the visible characteristic for a given feature, rather than using the index,
/// regardless of whether this layer is in edit mode.
/// </summary>
/// <param name="feature">The feature whose category should be returned.</param>
/// <returns>The category of the feature.</returns>
IFeatureCategory GetCategory(IFeature feature);
/// <summary>
/// Gets the visible characteristic for an individual feature.
/// </summary>
/// <param name="index">Index of the feature.</param>
/// <returns>The visible state of the feature.</returns>
bool GetVisible(int index);
/// <summary>
/// Gets the visible characteristic for a given feature, rather than using the index.
/// </summary>
/// <param name="feature">Feature whose visible state should be returned.</param>
/// <returns>The visible state of the feature.</returns>
bool GetVisible(IFeature feature);
/// <summary>
/// This method will remove the in ram features from the underlying dataset.
/// This will not affect the data source. Beware! Removing features
/// without populating the DataTable first will almost assuredly mean
/// indexing failures if you choose to load it later.
/// </summary>
/// <param name="indexValues">The list or array of integer index values.</param>
void RemoveFeaturesAt(IEnumerable<int> indexValues);
/// <summary>
/// This forces the removal of all the selected features.
/// </summary>
void RemoveSelectedFeatures();
/// <summary>
/// Selects the specified list of features. If the specified feature is already selected,
/// this method will not alter it.
/// </summary>
/// <param name="featureIndices">A List of integers representing the zero-based feature index values</param>
void Select(IEnumerable<int> featureIndices);
/// <summary>
/// Selects a single feature specified by the integer index in the Features list.
/// </summary>
/// <param name="featureIndex">The zero-based integer index of the feature.</param>
void Select(int featureIndex);
/// <summary>
/// Selects the specified feature.
/// </summary>
/// <param name="feature">The feature.</param>
void Select(IFeature feature);
/// <summary>
/// Cycles through all the features and selects them
/// </summary>
void SelectAll();
/// <summary>
/// Selects all the features in this layer that are associated with the specified attribute, clearing the selection first.
/// </summary>
/// <param name="filterExpression">The string expression to identify based on attributes the features to select.</param>
void SelectByAttribute(string filterExpression);
/// <summary>
/// Modifies the features with a new selection based on the modifyMode.
/// </summary>
/// <param name="filterExpression">The string filter expression to use</param>
/// <param name="modifyMode">Determines how the newly chosen features should interact with the existing
/// selection</param>
void SelectByAttribute(string filterExpression, ModifySelectionMode modifyMode);
/// <summary>
/// Sets the category for the specified shape index regardless of whether this layer is in edit mode.
/// </summary>
/// <param name="index">The 0 based integer shape index</param>
/// <param name="category">The category for this feature. The exact kind of category depends on the
/// feature type.</param>
void SetCategory(int index, IFeatureCategory category);
/// <summary>
/// Sets the visible characteristic for a given feature, rather than using the index
/// regardless of whether this layer is in edit mode.
/// </summary>
/// <param name="feature">The actual reference to the feature object to update</param>
/// <param name="category">The new category to use for the specified feature</param>
void SetCategory(IFeature feature, IFeatureCategory category);
/// <summary>
/// This forces the creation of a category for the specified symbolizer, if it doesn't exist.
/// This will add the specified feature to the category. Be sure that the symbolizer type
/// matches the feature type.
/// </summary>
/// <param name="index">The integer index of the shape to control.</param>
/// <param name="symbolizer">The symbolizer to assign.</param>
void SetShapeSymbolizer(int index, IFeatureSymbolizer symbolizer);
/// <summary>
/// Sets the visible characteristic for an individual feature.
/// </summary>
/// <param name="index">Index of the feature.</param>
/// <param name="visible">The new visible state.</param>
void SetVisible(int index, bool visible);
/// <summary>
/// Sets the visible characteristic for a given feature, rather than using the index.
/// </summary>
/// <param name="feature">Feature whose visible state gets changed.</param>
/// <param name="visible">The new visible state.</param>
void SetVisible(IFeature feature, bool visible);
/// <summary>
/// Displays a form with the attributes for this shapefile.
/// </summary>
void ShowAttributes();
/// <summary>
/// Creates a bitmap of the requested size that covers the specified geographic extent using
/// the current symbolizer for this layer. This does not have any drawing optimizations,
/// or techniques to speed up performance and should only be used in special cases like
/// draping of vector content onto a texture. It also doesn't worry about selections.
/// </summary>
/// <param name="geographicExtent">The extent to use when computing the snapshot.</param>
/// <param name="width">The integer height of the bitmap</param>
/// <returns>A Bitmap object</returns>
Bitmap SnapShot(Extent geographicExtent, int width);
/// <summary>
/// Unselects the specified features. If any features already unselected, they are ignored.
/// </summary>
/// <param name="featureIndices">Indices of the features that get unselected.</param>
void UnSelect(IEnumerable<int> featureIndices);
/// <summary>
/// Unselects the specified feature.
/// </summary>
/// <param name="featureIndex">The integer representing the feature to unselect.</param>
void UnSelect(int featureIndex);
/// <summary>
/// Removes the specified feature from the selection.
/// </summary>
/// <param name="feature">The feature to remove</param>
void UnSelect(IFeature feature);
/// <summary>
/// Unselects all the features that are currently selected.
/// </summary>
void UnSelectAll();
/// <summary>
/// Zooms to the envelope of the selected features.
/// </summary>
void ZoomToSelectedFeatures();
#endregion
}
}
| |
using System;
using System.IO;
using System.Text;
namespace Nga
{
public class VM
{
/* Registers */
int sp, rsp, ip;
int[] data, address, memory;
string request;
static readonly int MAX_REQUEST_LENGTH = 1024;
/* Opcodes recognized by the VM */
enum OpCodes {
VM_NOP, VM_LIT, VM_DUP,
VM_DROP, VM_SWAP, VM_PUSH,
VM_POP, VM_JUMP, VM_CALL,
VM_CCALL, VM_RETURN, VM_EQ,
VM_NEQ, VM_LT, VM_GT,
VM_FETCH, VM_STORE, VM_ADD,
VM_SUB, VM_MUL, VM_DIVMOD,
VM_AND, VM_OR, VM_XOR,
VM_SHIFT, VM_ZRET, VM_END
}
void rxGetString(int starting)
{
int i = 0;
char[] requestTmp = new char[MAX_REQUEST_LENGTH];
while (memory[starting] > 0 && i < MAX_REQUEST_LENGTH)
{
requestTmp[i++] = (char)memory[starting++];
}
//requestTmp[i] = (char)0;
request = new string(requestTmp);
request = request.TrimEnd('\0');
}
/* Initialize the VM */
public VM() {
sp = 0;
rsp = 0;
ip = 0;
data = new int[128];
address = new int[1024];
memory = new int[1000000];
loadImage();
if (memory[0] == 0) {
Console.Write("Sorry, unable to find ngaImage\n");
Environment.Exit(0);
}
}
/* Load the 'ngaImage' into memory */
public void loadImage() {
int i = 0;
if (!File.Exists("ngaImage"))
return;
BinaryReader binReader = new BinaryReader(File.Open("ngaImage", FileMode.Open));
FileInfo f = new FileInfo("ngaImage");
long s = f.Length / 4;
try {
while (i < s) { memory[i] = binReader.ReadInt32(); i++; }
}
catch(EndOfStreamException e) {
Console.WriteLine("{0} caught and ignored." , e.GetType().Name);
}
finally {
binReader.Close();
}
}
/* Process the current opcode */
public void ngaProcessOpcode(int opcode) {
int x, y;
switch((OpCodes)opcode)
{
case OpCodes.VM_NOP:
break;
case OpCodes.VM_LIT:
Console.Write(ip + 1);
sp++; ip++; data[sp] = memory[ip];
break;
case OpCodes.VM_DUP:
sp++; data[sp] = data[sp-1];
break;
case OpCodes.VM_DROP:
data[sp] = 0; sp--;
break;
case OpCodes.VM_SWAP:
x = data[sp];
y = data[sp-1];
data[sp] = y;
data[sp-1] = x;
break;
case OpCodes.VM_PUSH:
rsp++;
address[rsp] = data[sp];
sp--;
break;
case OpCodes.VM_POP:
sp++;
data[sp] = address[rsp];
rsp--;
break;
case OpCodes.VM_CALL:
rsp++;
address[rsp] = ip;
ip = data[sp] - 1;
sp = sp - 1;
break;
case OpCodes.VM_CCALL:
if (data[sp - 1] == -1) {
rsp++;
address[rsp] = ip;
ip = data[sp] - 1;
}
sp = sp - 2;
break;
case OpCodes.VM_JUMP:
ip = data[sp] - 1;
sp = sp - 1;
break;
case OpCodes.VM_RETURN:
ip = address[rsp]; rsp--;
break;
case OpCodes.VM_GT:
if (data[sp-1] > data[sp])
data[sp-1] = -1;
else
data[sp-1] = 0;
sp = sp - 1;
break;
case OpCodes.VM_LT:
if (data[sp-1] < data[sp])
data[sp-1] = -1;
else
data[sp-1] = 0;
sp = sp - 1;
break;
case OpCodes.VM_NEQ:
if (data[sp-1] != data[sp])
data[sp-1] = -1;
else
data[sp-1] = 0;
sp = sp - 1;
break;
case OpCodes.VM_EQ:
if (data[sp-1] == data[sp])
data[sp-1] = -1;
else
data[sp-1] = 0;
sp = sp - 1;
break;
case OpCodes.VM_FETCH:
x = data[sp];
data[sp] = memory[x];
break;
case OpCodes.VM_STORE:
memory[data[sp]] = data[sp-1];
sp = sp - 2;
break;
case OpCodes.VM_ADD:
data[sp-1] += data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_SUB:
data[sp-1] -= data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_MUL:
data[sp-1] *= data[sp]; data[sp] = 0; sp--;
break;
case OpCodes.VM_DIVMOD:
x = data[sp];
y = data[sp-1];
data[sp] = y / x;
data[sp-1] = y % x;
break;
case OpCodes.VM_AND:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x & y;
break;
case OpCodes.VM_OR:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x | y;
break;
case OpCodes.VM_XOR:
x = data[sp];
y = data[sp-1];
sp--;
data[sp] = x ^ y;
break;
case OpCodes.VM_SHIFT:
x = data[sp];
y = data[sp-1];
sp--;
if (x < 0)
data[sp] = y << x;
else
data[sp] = y >>= x;
break;
case OpCodes.VM_ZRET:
if (data[sp] == 0) {
sp--;
ip = address[rsp]; rsp--;
}
break;
case OpCodes.VM_END:
ip = 1000000;
break;
default:
ip = 1000000;
break;
}
}
public int ngaValidatePackedOpcodes(int opcode) {
int raw = opcode;
int current;
int valid = -1;
for (int i = 0; i < 4; i++) {
current = raw & 0xFF;
if (!(current >= 0 && current <= 26))
valid = 0;
raw = raw >> 8;
}
return valid;
}
void ngaProcessPackedOpcodes(int opcode) {
int raw = opcode;
for (int i = 0; i < 4; i++) {
ngaProcessOpcode(raw & 0xFF);
raw = raw >> 8;
}
}
/* Process the image until the IP reaches the end of memory */
public void Execute() {
for (ip = 0; ip < 1000000; ip++) {
Console.Write(ip + ":" + memory[ip] + "\n");
ngaProcessPackedOpcodes(memory[ip]);
}
}
/* Main entry point */
/* Calls all the other stuff and process the command line */
public static void Main(string [] args) {
VM vm = new VM();
for (int i = 0; i < args.Length; i++) {
if (args[i] == "--about") {
Console.Write("Nga [VM: C#, .NET]\n\n");
Environment.Exit(0);
}
}
vm.Execute();
Console.Write(vm.data[vm.sp]);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using System.Collections;
using System.Runtime.Serialization;
using OpenSource.UPnP.AV;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// <para>
/// Maps to the CDS/UPNP-AV "upnp:createClass" element, which
/// describes the types of media that can be returned in a
/// Search request from the container. Search class is always a per container,
/// and no parent-child relationship is assumed.
/// </para>
///
/// <para>
/// This class maps to the "upnp:createClass" element in
/// the ContentDirectory content hierarchy XML schema.
/// </para>
/// </summary>
[Serializable()]
public class CreateClass : MediaClass
{
/// <summary>
/// Returns true if the other CreateClass has the same value and attribute values.
/// </summary>
/// <param name="cdsElement">a SearchClass instance; derived classes don't count</param>
/// <returns></returns>
public override bool Equals (object cdsElement)
{
CreateClass other = (CreateClass) cdsElement;
if (this.GetType() == other.GetType())
{
if (this.m_ClassName.Equals(other.m_ClassName))
{
if (this.m_DerivedFrom.Equals(other.m_DerivedFrom))
{
if (this.m_FriendlyName.Equals(other.m_FriendlyName))
{
if (this.m_IncludeDerived.Equals(other.m_IncludeDerived))
{
return true;
}
}
}
}
}
return false;
}
/// <summary>
/// Generates a hashcode using the hashcodes of the fields multiplied by prime numbers,
/// then summed together.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return
base.GetHashCode() +
(this.m_IncludeDerived.GetHashCode() * 11);
}
/// <summary>
/// Returns a static listing of attributes that can apply to the
/// xml form of this object.
/// </summary>
/// <returns></returns>
public new static IList GetPossibleAttributes()
{
string[] attributes = {T[_ATTRIB.name], T[_ATTRIB.includeDerived]};
return attributes;
}
/// <summary>
/// Returns the listing of attributes that can apply to the
/// xml form of this object.
/// </summary>
public override IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// Returns the list of attributes that would be present if
/// this object was cast to its xml form.
/// </summary>
public override IList ValidAttributes
{
get
{
ArrayList al = new ArrayList(2);
if (this.m_FriendlyName != "")
{
al.Add(T[_ATTRIB.name]);
}
al.Add(T[_ATTRIB.includeDerived]);
return al;
}
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the "upnp:createClass" element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown when the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public override void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData _d = (ToXmlData) data;
xmlWriter.WriteStartElement(Tags.PropertyAttributes.upnp_createClass);
if (this.m_AttributeNames == null)
{
this.PrintFriendlyName(_d.DesiredProperties, xmlWriter);
this.PrintIncludeDerived(_d.DesiredProperties, xmlWriter);
}
else
{
foreach (string attribName in this.m_AttributeNames)
{
if (string.Compare(attribName, T[_ATTRIB.name]) == 0)
{
this.PrintFriendlyName(_d.DesiredProperties, xmlWriter);
}
else if (string.Compare(attribName, T[_ATTRIB.includeDerived]) == 0)
{
this.PrintIncludeDerived(_d.DesiredProperties, xmlWriter);
}
}
}
}
private void PrintFriendlyName(ArrayList desiredProperties, XmlTextWriter xmlWriter)
{
if (desiredProperties != null)
{
if ((desiredProperties.Count == 0) || (desiredProperties.Contains(Tags.PropertyAttributes.upnp_createClassName)))
{
string val = this.FriendlyName;
if ((val != null) && (val != ""))
{
xmlWriter.WriteAttributeString(T[_ATTRIB.name], this.FriendlyName);
}
}
}
}
private void PrintIncludeDerived(ArrayList desiredProperties, XmlTextWriter xmlWriter)
{
if (desiredProperties != null)
{
if ((desiredProperties.Count == 0) || (desiredProperties.Contains(Tags.PropertyAttributes.upnp_createClassIncludeDerived)))
{
string val = this.IncludeDerived.ToString();
val = val.ToLower();
xmlWriter.WriteAttributeString(T[_ATTRIB.includeDerived], val);
}
}
}
/// <summary>
/// Creates a search class given the class name,
/// base class, optional friendly name, and an indication
/// if objects derived from this specified media class
/// are included when searching for the specified media class.
/// </summary>
/// <param name="className">class name (substring after the last dot "." character in full class name)</param>
/// <param name="derivedFrom">base class (substring before the last dot "." character in full class name)</param>
/// <param name="friendly">optional friendly name</param>
/// <param name="includeDerived">indication if a search request on the container for a particular type includes all derived types</param>
public CreateClass(string className, string derivedFrom, string friendly, bool includeDerived)
: base (className, derivedFrom, friendly)
{
this.m_IncludeDerived = includeDerived;
}
/// <summary>
/// Creates a search class given the full class name,
/// optional friendly name, and an indication
/// if objects derived from this specified media class
/// should be flagged
/// </summary>
/// <param name="fullName">full class name, in "[baseClass].[class name]" format</param>
/// <param name="friendly">optional friendly name</param>
/// <param name="includeDerived">indication if a search request on the container for a particular type includes all derived types</param>
public CreateClass (string fullName, string friendly, bool includeDerived)
: base (fullName, friendly)
{
this.m_IncludeDerived = includeDerived;
}
/// <summary>
/// The element.Name should be upnp:createClass
/// </summary>
/// <param name="element"></param>
public CreateClass (XmlElement element)
: base(element)
{
XmlAttribute attrib = element.Attributes[T[_ATTRIB.includeDerived]];
this.m_IncludeDerived = MediaObject.IsAttributeValueTrue(attrib, false);
}
/// <summary>
/// Extracts the value of an attribute.
/// Attribute list: name
/// </summary>
/// <param name="attribute">attribute name</param>
/// <returns>returns a comparable value</returns>
public override IComparable ExtractAttribute(string attribute)
{
if (attribute == T[_ATTRIB.name])
{
return this.m_FriendlyName;
}
else if (attribute == T[_ATTRIB.includeDerived])
{
return this.m_IncludeDerived;
}
return null;
}
/// <summary>
/// Indicates that the specfied search class is applicable for all derived classes.
/// </summary>
public bool IncludeDerived
{
get
{
return this.m_IncludeDerived;
}
}
/// <summary>
/// The value for the IncludeDerived property.
/// The variable was at one point internally accessible.
/// </summary>
private readonly bool m_IncludeDerived;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Microsoft.Samples.KMoore.WPFSamples.FolderPicker
{
public class LocalDrives : INotifyPropertyChanged
{
#region constructors
public LocalDrives()
{
_drives = new List<SelectableDirectory>();
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
if (d.DriveType == DriveType.Fixed && d.IsReady)
{
SelectableDirectory sd = new SelectableDirectory(d);
_drives.Add(sd);
sd.PropertyChanged += new PropertyChangedEventHandler(sd_PropertyChanged);
}
}
}
#endregion
public ReadOnlyCollection<SelectableDirectory> Drives
{
get
{
if (_roCache == null)
{
_roCache = new ReadOnlyCollection<SelectableDirectory>(_drives);
}
return _roCache;
}
}
public IEnumerable<SelectableDirectory> SelectedDirectories
{
get
{
foreach (SelectableDirectory sd in _drives)
{
if (sd.IsSelected)
{
yield return sd;
}
foreach (SelectableDirectory sd2 in sd.SelectedDirectories)
{
yield return sd2;
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
#region implementation
void sd_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == SelectableDirectory.SelectedDirectoriesPropertyName)
{
PropertyChanged(this, SelectableDirectory.SelectedDirectoriesChangedArgs);
}
}
List<SelectableDirectory> _drives;
ReadOnlyCollection<SelectableDirectory> _roCache = null;
#endregion
}
public class SelectableDirectory : INotifyPropertyChanged
{
#region constructors
public SelectableDirectory(string path) : this(new DirectoryInfo(path)) { }
public SelectableDirectory(DirectoryInfo di)
{
_di = di;
}
public SelectableDirectory(DriveInfo di)
{
_di = di.RootDirectory;
_isDrive = true;
}
#endregion
public ReadOnlyCollection<SelectableDirectory> SubDirectories
{
get
{
if (_directories == null)
{
_directories = new Collection<SelectableDirectory>();
try
{
foreach (DirectoryInfo di in _di.GetDirectories())
{
SelectableDirectory dir = new SelectableDirectory(di);
dir.PropertyChanged += new PropertyChangedEventHandler(dir_PropertyChanged);
_directories.Add(dir);
}
}
catch (System.UnauthorizedAccessException)
{
//the directory may be restricted
}
}
if (_roCache == null)
{
_roCache = new ReadOnlyCollection<SelectableDirectory>(_directories);
}
return _roCache;
}
}
public IEnumerable<SelectableDirectory> SelectedDirectories
{
get
{
if (_directories != null)
{
foreach (SelectableDirectory sd in _directories)
{
if (sd.IsSelected)
{
yield return sd;
}
foreach (SelectableDirectory sd2 in sd.SelectedDirectories)
{
yield return sd2;
}
}
}
}
}
public string Name
{
get
{
if (_isDrive)
{
string name = _di.Name;
name = (name.EndsWith("\\")) ? name.Substring(0, name.Length - 1) : name;
return string.Format("Local Disk ({0})", name);
}
else
{
return _di.Name;
}
}
}
public string Path
{
get
{
return _di.FullName;
}
}
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
bool changed = (_isSelected != value);
if (changed)
{
_isSelected = value;
OnIsSelectedChanged();
}
}
}
public ChildSelection ChildSelection
{
get
{
int childCount, selectionCount;
if (_subCountCache != int.MinValue && _subSelectionCountCache != int.MinValue)
{
childCount = _subCountCache;
selectionCount = _subSelectionCountCache;
}
else
{
GetChildSelectionCount(out childCount, out selectionCount);
_subSelectionCountCache = selectionCount;
_subCountCache = childCount;
}
if (selectionCount == 0)
{
return ChildSelection.None;
}
else if (childCount == selectionCount)
{
return ChildSelection.All;
}
else
{
return ChildSelection.Some;
}
}
}
public bool IsDrive
{
get
{
return _isDrive;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public override string ToString()
{
return _di.FullName;
}
#region implementation
protected SelectableDirectory() : this(@"C:\") { }
protected void OnIsSelectedChanged()
{
if (PropertyChanged != null)
{
PropertyChanged(this, IsSelectedChangedArgs);
PropertyChanged(this, SelectedDirectoriesChangedArgs);
}
}
protected void OnChildSelectionChanged()
{
_subSelectionCountCache = int.MinValue;
_subCountCache = int.MinValue;
if (PropertyChanged != null)
{
PropertyChanged(this, ChildSelectionChangedArgs);
PropertyChanged(this, SelectedDirectoriesChangedArgs);
}
}
void dir_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case SelectedDirectoriesPropertyName:
case IsSelectedPropertyName:
OnChildSelectionChanged();
break;
}
}
private void GetChildSelectionCount(out int childCount, out int selectionCount)
{
childCount = 0;
selectionCount = 0;
int subChildCount, subSelectionCount;
if (_directories != null)
{
foreach (SelectableDirectory dir in _directories)
{
childCount++;
if (dir.IsSelected)
{
selectionCount++;
}
subChildCount = 0;
subSelectionCount = 0;
dir.GetChildSelectionCount(out subChildCount, out subSelectionCount);
childCount += subChildCount;
selectionCount += subSelectionCount;
}
}
else
{
childCount = 0;
selectionCount = 0;
}
}
DirectoryInfo _di;
Collection<SelectableDirectory> _directories;
ReadOnlyCollection<SelectableDirectory> _roCache = null;
private int _subCountCache = int.MinValue;
private int _subSelectionCountCache = int.MinValue;
private bool _isSelected = false;
private bool _isDrive = false;
const string IsSelectedPropertyName = "IsSelected";
const string ChildSelectionPropertyName = "ChildSelection";
internal const string SelectedDirectoriesPropertyName = "SelectedDirectories";
private static readonly PropertyChangedEventArgs ChildSelectionChangedArgs = new PropertyChangedEventArgs(ChildSelectionPropertyName);
private static readonly PropertyChangedEventArgs IsSelectedChangedArgs = new PropertyChangedEventArgs(IsSelectedPropertyName);
internal static readonly PropertyChangedEventArgs SelectedDirectoriesChangedArgs = new PropertyChangedEventArgs(SelectedDirectoriesPropertyName);
#endregion
}
public enum ChildSelection { All, Some, None }
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmStockfromFile
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmStockfromFile() : base()
{
Load += frmStockfromFile_Load;
KeyPress += frmStockfromFile_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox txtFile;
public System.Windows.Forms.ProgressBar prgStockItem;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.GroupBox Frame2;
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBack;
public System.Windows.Forms.Button cmdBack {
get { return withEventsField_cmdBack; }
set {
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click -= cmdBack_Click;
}
withEventsField_cmdBack = value;
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click += cmdBack_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.OpenFileDialog CommonDialog1Open;
public System.Windows.Forms.SaveFileDialog CommonDialog1Save;
public System.Windows.Forms.FontDialog CommonDialog1Font;
public System.Windows.Forms.ColorDialog CommonDialog1Color;
public System.Windows.Forms.PrintDialog CommonDialog1Print;
public System.Windows.Forms.PictureBox Picture1;
private System.Windows.Forms.TextBox withEventsField_txtName;
public System.Windows.Forms.TextBox txtName {
get { return withEventsField_txtName; }
set {
if (withEventsField_txtName != null) {
withEventsField_txtName.Enter -= txtName_Enter;
withEventsField_txtName.Leave -= txtName_Leave;
}
withEventsField_txtName = value;
if (withEventsField_txtName != null) {
withEventsField_txtName.Enter += txtName_Enter;
withEventsField_txtName.Leave += txtName_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtReceipt;
public System.Windows.Forms.TextBox txtReceipt {
get { return withEventsField_txtReceipt; }
set {
if (withEventsField_txtReceipt != null) {
withEventsField_txtReceipt.Enter -= txtReceipt_Enter;
}
withEventsField_txtReceipt = value;
if (withEventsField_txtReceipt != null) {
withEventsField_txtReceipt.Enter += txtReceipt_Enter;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtQuantity;
public System.Windows.Forms.TextBox txtQuantity {
get { return withEventsField_txtQuantity; }
set {
if (withEventsField_txtQuantity != null) {
withEventsField_txtQuantity.Enter -= txtQuantity_Enter;
withEventsField_txtQuantity.KeyPress -= txtQuantity_KeyPress;
withEventsField_txtQuantity.Leave -= txtQuantity_Leave;
}
withEventsField_txtQuantity = value;
if (withEventsField_txtQuantity != null) {
withEventsField_txtQuantity.Enter += txtQuantity_Enter;
withEventsField_txtQuantity.KeyPress += txtQuantity_KeyPress;
withEventsField_txtQuantity.Leave += txtQuantity_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtCost;
public System.Windows.Forms.TextBox txtCost {
get { return withEventsField_txtCost; }
set {
if (withEventsField_txtCost != null) {
withEventsField_txtCost.Enter -= txtCost_Enter;
withEventsField_txtCost.KeyPress -= txtCost_KeyPress;
withEventsField_txtCost.Leave -= txtCost_Leave;
}
withEventsField_txtCost = value;
if (withEventsField_txtCost != null) {
withEventsField_txtCost.Enter += txtCost_Enter;
withEventsField_txtCost.KeyPress += txtCost_KeyPress;
withEventsField_txtCost.Leave += txtCost_Leave;
}
}
}
private myDataGridView withEventsField_cmbShrink;
public myDataGridView cmbShrink {
get { return withEventsField_cmbShrink; }
set {
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyDown -= cmbShrink_KeyDown;
}
withEventsField_cmbShrink = value;
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyDown += cmbShrink_KeyDown;
}
}
}
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.Label _lblLabels_10;
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.GroupBox Frame1;
private myDataGridView withEventsField_cmbPricingGroup;
public myDataGridView cmbPricingGroup {
get { return withEventsField_cmbPricingGroup; }
set {
if (withEventsField_cmbPricingGroup != null) {
withEventsField_cmbPricingGroup.KeyDown -= cmbPricingGroup_KeyDown;
}
withEventsField_cmbPricingGroup = value;
if (withEventsField_cmbPricingGroup != null) {
withEventsField_cmbPricingGroup.KeyDown += cmbPricingGroup_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbStockGroup;
public myDataGridView cmbStockGroup {
get { return withEventsField_cmbStockGroup; }
set {
if (withEventsField_cmbStockGroup != null) {
withEventsField_cmbStockGroup.KeyDown -= cmbStockGroup_KeyDown;
}
withEventsField_cmbStockGroup = value;
if (withEventsField_cmbStockGroup != null) {
withEventsField_cmbStockGroup.KeyDown += cmbStockGroup_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbDeposit;
public myDataGridView cmbDeposit {
get { return withEventsField_cmbDeposit; }
set {
if (withEventsField_cmbDeposit != null) {
withEventsField_cmbDeposit.KeyDown -= cmbDeposit_KeyDown;
}
withEventsField_cmbDeposit = value;
if (withEventsField_cmbDeposit != null) {
withEventsField_cmbDeposit.KeyDown += cmbDeposit_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbSupplier;
public myDataGridView cmbSupplier {
get { return withEventsField_cmbSupplier; }
set {
if (withEventsField_cmbSupplier != null) {
withEventsField_cmbSupplier.KeyDown -= cmbSupplier_KeyDown;
}
withEventsField_cmbSupplier = value;
if (withEventsField_cmbSupplier != null) {
withEventsField_cmbSupplier.KeyDown += cmbSupplier_KeyDown;
}
}
}
public System.Windows.Forms.Label _lblLabels_6;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_3;
public System.Windows.Forms.Label _lblLabels_4;
public System.Windows.Forms.Label _lblLabels_7;
public System.Windows.Forms.Label _lblLabels_8;
public System.Windows.Forms.GroupBox _frmMode_1;
//Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockfromFile));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.Frame2 = new System.Windows.Forms.GroupBox();
this.txtFile = new System.Windows.Forms.TextBox();
this.prgStockItem = new System.Windows.Forms.ProgressBar();
this.Label1 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdNext = new System.Windows.Forms.Button();
this.cmdBack = new System.Windows.Forms.Button();
this.CommonDialog1Open = new System.Windows.Forms.OpenFileDialog();
this.CommonDialog1Save = new System.Windows.Forms.SaveFileDialog();
this.CommonDialog1Font = new System.Windows.Forms.FontDialog();
this.CommonDialog1Color = new System.Windows.Forms.ColorDialog();
this.CommonDialog1Print = new System.Windows.Forms.PrintDialog();
this._frmMode_1 = new System.Windows.Forms.GroupBox();
this.Picture1 = new System.Windows.Forms.PictureBox();
this.txtName = new System.Windows.Forms.TextBox();
this.txtReceipt = new System.Windows.Forms.TextBox();
this.Frame1 = new System.Windows.Forms.GroupBox();
this.txtQuantity = new System.Windows.Forms.TextBox();
this.txtCost = new System.Windows.Forms.TextBox();
this.cmbShrink = new myDataGridView();
this._lblLabels_2 = new System.Windows.Forms.Label();
this._lblLabels_10 = new System.Windows.Forms.Label();
this._lblLabels_1 = new System.Windows.Forms.Label();
this.cmbPricingGroup = new myDataGridView();
this.cmbStockGroup = new myDataGridView();
this.cmbDeposit = new myDataGridView();
this.cmbSupplier = new myDataGridView();
this._lblLabels_6 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_3 = new System.Windows.Forms.Label();
this._lblLabels_4 = new System.Windows.Forms.Label();
this._lblLabels_7 = new System.Windows.Forms.Label();
this._lblLabels_8 = new System.Windows.Forms.Label();
//Me.frmMode = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.Frame2.SuspendLayout();
this.picButtons.SuspendLayout();
this._frmMode_1.SuspendLayout();
this.Frame1.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.cmbShrink).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbPricingGroup).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbStockGroup).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbDeposit).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbSupplier).BeginInit();
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Adding Stock Items";
this.ClientSize = new System.Drawing.Size(528, 170);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmStockfromFile";
this.Frame2.Size = new System.Drawing.Size(515, 99);
this.Frame2.Location = new System.Drawing.Point(6, 62);
this.Frame2.TabIndex = 24;
this.Frame2.BackColor = System.Drawing.SystemColors.Control;
this.Frame2.Enabled = true;
this.Frame2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame2.Visible = true;
this.Frame2.Padding = new System.Windows.Forms.Padding(0);
this.Frame2.Name = "Frame2";
this.txtFile.AutoSize = false;
this.txtFile.Enabled = false;
this.txtFile.Size = new System.Drawing.Size(403, 19);
this.txtFile.Location = new System.Drawing.Point(104, 12);
this.txtFile.TabIndex = 26;
this.txtFile.AcceptsReturn = true;
this.txtFile.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtFile.BackColor = System.Drawing.SystemColors.Window;
this.txtFile.CausesValidation = true;
this.txtFile.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtFile.HideSelection = true;
this.txtFile.ReadOnly = false;
this.txtFile.MaxLength = 0;
this.txtFile.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtFile.Multiline = false;
this.txtFile.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtFile.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtFile.TabStop = true;
this.txtFile.Visible = true;
this.txtFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtFile.Name = "txtFile";
this.prgStockItem.Size = new System.Drawing.Size(495, 21);
this.prgStockItem.Location = new System.Drawing.Point(14, 34);
this.prgStockItem.TabIndex = 25;
this.prgStockItem.Maximum = 10000;
this.prgStockItem.Name = "prgStockItem";
this.Label1.Text = "File Name: ";
this.Label1.Size = new System.Drawing.Size(81, 17);
this.Label1.Location = new System.Drawing.Point(20, 12);
this.Label1.TabIndex = 28;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.Label2.Text = ":";
this.Label2.Size = new System.Drawing.Size(295, 23);
this.Label2.Location = new System.Drawing.Point(212, 60);
this.Label2.TabIndex = 27;
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Enabled = true;
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.UseMnemonic = true;
this.Label2.Visible = true;
this.Label2.AutoSize = false;
this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label2.Name = "Label2";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(528, 53);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 21;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNext.Text = "&Do Update>>";
this.cmdNext.Size = new System.Drawing.Size(96, 33);
this.cmdNext.Location = new System.Drawing.Point(420, 6);
this.cmdNext.TabIndex = 23;
this.cmdNext.TabStop = false;
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.CausesValidation = true;
this.cmdNext.Enabled = true;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.Name = "cmdNext";
this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBack.Text = "E&xit";
this.cmdBack.Size = new System.Drawing.Size(97, 33);
this.cmdBack.Location = new System.Drawing.Point(8, 6);
this.cmdBack.TabIndex = 22;
this.cmdBack.TabStop = false;
this.cmdBack.BackColor = System.Drawing.SystemColors.Control;
this.cmdBack.CausesValidation = true;
this.cmdBack.Enabled = true;
this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBack.Name = "cmdBack";
this._frmMode_1.Text = "New \"Stock Item\" Details.";
this._frmMode_1.Enabled = false;
this._frmMode_1.Size = new System.Drawing.Size(331, 263);
this._frmMode_1.Location = new System.Drawing.Point(-2, 506);
this._frmMode_1.TabIndex = 0;
this._frmMode_1.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_1.Visible = true;
this._frmMode_1.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_1.Name = "_frmMode_1";
this.Picture1.Size = new System.Drawing.Size(295, 4);
this.Picture1.Location = new System.Drawing.Point(28, 162);
this.Picture1.TabIndex = 10;
this.Picture1.TabStop = false;
this.Picture1.Dock = System.Windows.Forms.DockStyle.None;
this.Picture1.BackColor = System.Drawing.SystemColors.Control;
this.Picture1.CausesValidation = true;
this.Picture1.Enabled = true;
this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Picture1.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture1.Visible = true;
this.Picture1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Picture1.Name = "Picture1";
this.txtName.AutoSize = false;
this.txtName.Size = new System.Drawing.Size(241, 19);
this.txtName.Location = new System.Drawing.Point(82, 18);
this.txtName.TabIndex = 9;
this.txtName.Text = "[New Product]";
this.txtName.AcceptsReturn = true;
this.txtName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtName.BackColor = System.Drawing.SystemColors.Window;
this.txtName.CausesValidation = true;
this.txtName.Enabled = true;
this.txtName.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtName.HideSelection = true;
this.txtName.ReadOnly = false;
this.txtName.MaxLength = 0;
this.txtName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtName.Multiline = false;
this.txtName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtName.TabStop = true;
this.txtName.Visible = true;
this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtName.Name = "txtName";
this.txtReceipt.AutoSize = false;
this.txtReceipt.Size = new System.Drawing.Size(241, 19);
this.txtReceipt.Location = new System.Drawing.Point(82, 39);
this.txtReceipt.MaxLength = 20;
this.txtReceipt.TabIndex = 8;
this.txtReceipt.AcceptsReturn = true;
this.txtReceipt.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtReceipt.BackColor = System.Drawing.SystemColors.Window;
this.txtReceipt.CausesValidation = true;
this.txtReceipt.Enabled = true;
this.txtReceipt.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtReceipt.HideSelection = true;
this.txtReceipt.ReadOnly = false;
this.txtReceipt.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtReceipt.Multiline = false;
this.txtReceipt.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtReceipt.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtReceipt.TabStop = true;
this.txtReceipt.Visible = true;
this.txtReceipt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtReceipt.Name = "txtReceipt";
this.Frame1.Size = new System.Drawing.Size(317, 57);
this.Frame1.Location = new System.Drawing.Point(8, 168);
this.Frame1.TabIndex = 1;
this.Frame1.BackColor = System.Drawing.SystemColors.Control;
this.Frame1.Enabled = true;
this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame1.Visible = true;
this.Frame1.Padding = new System.Windows.Forms.Padding(0);
this.Frame1.Name = "Frame1";
this.txtQuantity.AutoSize = false;
this.txtQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtQuantity.Size = new System.Drawing.Size(28, 19);
this.txtQuantity.Location = new System.Drawing.Point(56, 12);
this.txtQuantity.TabIndex = 3;
this.txtQuantity.Text = "12";
this.txtQuantity.AcceptsReturn = true;
this.txtQuantity.BackColor = System.Drawing.SystemColors.Window;
this.txtQuantity.CausesValidation = true;
this.txtQuantity.Enabled = true;
this.txtQuantity.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtQuantity.HideSelection = true;
this.txtQuantity.ReadOnly = false;
this.txtQuantity.MaxLength = 0;
this.txtQuantity.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQuantity.Multiline = false;
this.txtQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtQuantity.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtQuantity.TabStop = true;
this.txtQuantity.Visible = true;
this.txtQuantity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtQuantity.Name = "txtQuantity";
this.txtCost.AutoSize = false;
this.txtCost.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtCost.Size = new System.Drawing.Size(56, 19);
this.txtCost.Location = new System.Drawing.Point(256, 14);
this.txtCost.TabIndex = 2;
this.txtCost.Text = "0.00";
this.txtCost.AcceptsReturn = true;
this.txtCost.BackColor = System.Drawing.SystemColors.Window;
this.txtCost.CausesValidation = true;
this.txtCost.Enabled = true;
this.txtCost.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtCost.HideSelection = true;
this.txtCost.ReadOnly = false;
this.txtCost.MaxLength = 0;
this.txtCost.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtCost.Multiline = false;
this.txtCost.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtCost.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtCost.TabStop = true;
this.txtCost.Visible = true;
this.txtCost.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtCost.Name = "txtCost";
//cmbShrink.OcxState = CType(resources.GetObject("cmbShrink.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbShrink.Size = new System.Drawing.Size(91, 21);
this.cmbShrink.Location = new System.Drawing.Point(134, 30);
this.cmbShrink.TabIndex = 4;
this.cmbShrink.Name = "cmbShrink";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_2.Text = "There are ";
this._lblLabels_2.Size = new System.Drawing.Size(49, 13);
this._lblLabels_2.Location = new System.Drawing.Point(6, 16);
this._lblLabels_2.TabIndex = 7;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Enabled = true;
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.UseMnemonic = true;
this._lblLabels_2.Visible = true;
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_2.Name = "_lblLabels_2";
this._lblLabels_10.Text = "Units in a case/carton, which costs";
this._lblLabels_10.Size = new System.Drawing.Size(167, 13);
this._lblLabels_10.Location = new System.Drawing.Point(86, 16);
this._lblLabels_10.TabIndex = 6;
this._lblLabels_10.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblLabels_10.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_10.Enabled = true;
this._lblLabels_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_10.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_10.UseMnemonic = true;
this._lblLabels_10.Visible = true;
this._lblLabels_10.AutoSize = true;
this._lblLabels_10.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_10.Name = "_lblLabels_10";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_1.Text = "and you sell in shrinks of";
this._lblLabels_1.Size = new System.Drawing.Size(115, 13);
this._lblLabels_1.Location = new System.Drawing.Point(8, 38);
this._lblLabels_1.TabIndex = 5;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Enabled = true;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.UseMnemonic = true;
this._lblLabels_1.Visible = true;
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_1.Name = "_lblLabels_1";
//cmbPricingGroup.OcxState = CType(resources.GetObject("cmbPricingGroup.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbPricingGroup.Size = new System.Drawing.Size(241, 21);
this.cmbPricingGroup.Location = new System.Drawing.Point(82, 108);
this.cmbPricingGroup.TabIndex = 11;
this.cmbPricingGroup.Name = "cmbPricingGroup";
//cmbStockGroup.OcxState = CType(resources.GetObject("cmbStockGroup.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbStockGroup.Size = new System.Drawing.Size(241, 21);
this.cmbStockGroup.Location = new System.Drawing.Point(82, 132);
this.cmbStockGroup.TabIndex = 12;
this.cmbStockGroup.Name = "cmbStockGroup";
//cmbDeposit.OcxState = CType(resources.GetObject("cmbDeposit.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbDeposit.Size = new System.Drawing.Size(241, 21);
this.cmbDeposit.Location = new System.Drawing.Point(82, 84);
this.cmbDeposit.TabIndex = 13;
this.cmbDeposit.Name = "cmbDeposit";
//cmbSupplier.OcxState = CType(resources.GetObject("cmbSupplier.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbSupplier.Size = new System.Drawing.Size(241, 21);
this.cmbSupplier.Location = new System.Drawing.Point(82, 60);
this.cmbSupplier.TabIndex = 14;
this.cmbSupplier.Name = "cmbSupplier";
this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_6.Text = "Deposit:";
this._lblLabels_6.Size = new System.Drawing.Size(39, 13);
this._lblLabels_6.Location = new System.Drawing.Point(38, 90);
this._lblLabels_6.TabIndex = 20;
this._lblLabels_6.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_6.Enabled = true;
this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_6.UseMnemonic = true;
this._lblLabels_6.Visible = true;
this._lblLabels_6.AutoSize = true;
this._lblLabels_6.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_6.Name = "_lblLabels_6";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_0.Text = "Supplier:";
this._lblLabels_0.Size = new System.Drawing.Size(41, 13);
this._lblLabels_0.Location = new System.Drawing.Point(36, 66);
this._lblLabels_0.TabIndex = 19;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Enabled = true;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.UseMnemonic = true;
this._lblLabels_0.Visible = true;
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_3.Text = "Pricing Group:";
this._lblLabels_3.Size = new System.Drawing.Size(67, 13);
this._lblLabels_3.Location = new System.Drawing.Point(10, 114);
this._lblLabels_3.TabIndex = 18;
this._lblLabels_3.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_3.Enabled = true;
this._lblLabels_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_3.UseMnemonic = true;
this._lblLabels_3.Visible = true;
this._lblLabels_3.AutoSize = true;
this._lblLabels_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_3.Name = "_lblLabels_3";
this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_4.Text = "Stock Group:";
this._lblLabels_4.Size = new System.Drawing.Size(63, 13);
this._lblLabels_4.Location = new System.Drawing.Point(14, 138);
this._lblLabels_4.TabIndex = 17;
this._lblLabels_4.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_4.Enabled = true;
this._lblLabels_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_4.UseMnemonic = true;
this._lblLabels_4.Visible = true;
this._lblLabels_4.AutoSize = true;
this._lblLabels_4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_4.Name = "_lblLabels_4";
this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_7.Text = "Display Name:";
this._lblLabels_7.Size = new System.Drawing.Size(68, 13);
this._lblLabels_7.Location = new System.Drawing.Point(10, 20);
this._lblLabels_7.TabIndex = 16;
this._lblLabels_7.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_7.Enabled = true;
this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_7.UseMnemonic = true;
this._lblLabels_7.Visible = true;
this._lblLabels_7.AutoSize = true;
this._lblLabels_7.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_7.Name = "_lblLabels_7";
this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_8.Text = "Receipt Name:";
this._lblLabels_8.Size = new System.Drawing.Size(71, 13);
this._lblLabels_8.Location = new System.Drawing.Point(6, 45);
this._lblLabels_8.TabIndex = 15;
this._lblLabels_8.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_8.Enabled = true;
this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_8.UseMnemonic = true;
this._lblLabels_8.Visible = true;
this._lblLabels_8.AutoSize = true;
this._lblLabels_8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_8.Name = "_lblLabels_8";
this.Controls.Add(Frame2);
this.Controls.Add(picButtons);
this.Controls.Add(_frmMode_1);
this.Frame2.Controls.Add(txtFile);
this.Frame2.Controls.Add(prgStockItem);
this.Frame2.Controls.Add(Label1);
this.Frame2.Controls.Add(Label2);
this.picButtons.Controls.Add(cmdNext);
this.picButtons.Controls.Add(cmdBack);
this._frmMode_1.Controls.Add(Picture1);
this._frmMode_1.Controls.Add(txtName);
this._frmMode_1.Controls.Add(txtReceipt);
this._frmMode_1.Controls.Add(Frame1);
this._frmMode_1.Controls.Add(cmbPricingGroup);
this._frmMode_1.Controls.Add(cmbStockGroup);
this._frmMode_1.Controls.Add(cmbDeposit);
this._frmMode_1.Controls.Add(cmbSupplier);
this._frmMode_1.Controls.Add(_lblLabels_6);
this._frmMode_1.Controls.Add(_lblLabels_0);
this._frmMode_1.Controls.Add(_lblLabels_3);
this._frmMode_1.Controls.Add(_lblLabels_4);
this._frmMode_1.Controls.Add(_lblLabels_7);
this._frmMode_1.Controls.Add(_lblLabels_8);
this.Frame1.Controls.Add(txtQuantity);
this.Frame1.Controls.Add(txtCost);
this.Frame1.Controls.Add(cmbShrink);
this.Frame1.Controls.Add(_lblLabels_2);
this.Frame1.Controls.Add(_lblLabels_10);
this.Frame1.Controls.Add(_lblLabels_1);
//Me.frmMode.SetIndex(_frmMode_1, CType(1, Short))
//Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short))
//Me.lblLabels.SetIndex(_lblLabels_10, CType(10, Short))
//Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short))
//Me.lblLabels.SetIndex(_lblLabels_6, CType(6, Short))
//Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
//Me.lblLabels.SetIndex(_lblLabels_3, CType(3, Short))
//Me.lblLabels.SetIndex(_lblLabels_4, CType(4, Short))
//Me.lblLabels.SetIndex(_lblLabels_7, CType(7, Short))
//Me.lblLabels.SetIndex(_lblLabels_8, CType(8, Short))
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.cmbSupplier).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbDeposit).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbStockGroup).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbPricingGroup).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbShrink).EndInit();
this.Frame2.ResumeLayout(false);
this.picButtons.ResumeLayout(false);
this._frmMode_1.ResumeLayout(false);
this.Frame1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Orleans.Runtime.ConsistentRing
{
/// <summary>
/// We use the 'backward/clockwise' definition to assign responsibilities on the ring.
/// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range).
/// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc.
/// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities.
/// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range)..
/// </summary>
internal class ConsistentRingProvider : MarshalByRefObject, IConsistentRingProvider, ISiloStatusListener // make the ring shutdown-able?
{
// internal, so that unit tests can access them
internal SiloAddress MyAddress { get; private set; }
internal IRingRange MyRange { get; private set; }
/// list of silo members sorted by the hash value of their address
private readonly List<SiloAddress> membershipRingList;
private readonly TraceLogger log;
private bool isRunning;
private readonly int myKey;
private readonly List<IRingRangeListener> statusListeners;
public ConsistentRingProvider(SiloAddress siloAddr)
{
log = TraceLogger.GetLogger(typeof(ConsistentRingProvider).Name);
membershipRingList = new List<SiloAddress>();
MyAddress = siloAddr;
myKey = MyAddress.GetConsistentHashCode();
// add myself to the list of members
AddServer(MyAddress);
MyRange = RangeFactory.CreateFullRange(); // i am responsible for the whole range
statusListeners = new List<IRingRangeListener>();
Start();
}
/// <summary>
/// Returns the silo that this silo thinks is the primary owner of the key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public SiloAddress GetPrimaryTargetSilo(uint key)
{
return CalculateTargetSilo(key);
}
public IRingRange GetMyRange()
{
return MyRange; // its immutable, so no need to clone
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
public List<SiloAddress> GetMySucessors(int n = 1)
{
return FindSuccessors(MyAddress, n);
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
public List<SiloAddress> GetMyPredecessors(int n = 1)
{
return FindPredecessors(MyAddress, n);
}
#region Handling the membership
private void Start()
{
isRunning = true;
}
private void Stop()
{
isRunning = false;
}
internal void AddServer(SiloAddress silo)
{
lock (membershipRingList)
{
if (membershipRingList.Contains(silo)) return; // we already have this silo
int myOldIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));
if (!(membershipRingList.Count == 0 || myOldIndex != -1))
throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, Utils.EnumerableToString(membershipRingList)));
// insert new silo in the sorted order
int hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
// relating to triggering handler ... new node took over some of my responsibility
if (index == myOldIndex || // new node was inserted in my place
(myOldIndex == 0 && index == membershipRingList.Count - 1)) // I am the first node, and the new server is the last node
{
IRingRange oldRange = MyRange;
try
{
MyRange = RangeFactory.CreateRange(unchecked((uint)hash), unchecked((uint)myKey));
}
catch (OverflowException exc)
{
log.Error(ErrorCode.ConsistentRingProviderBase + 5,
String.Format("OverflowException: hash as int= x{0, 8:X8}, hash as uint= x{1, 8:X8}, myKey as int x{2, 8:X8}, myKey as uint x{3, 8:X8}.",
hash, (uint)hash, myKey, (uint)myKey), exc);
}
NotifyLocalRangeSubscribers(oldRange, MyRange, false);
}
log.Info("Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
}
}
public override string ToString()
{
lock (membershipRingList)
{
if (membershipRingList.Count == 1)
return Utils.EnumerableToString(membershipRingList, silo => String.Format("{0} -> {1}", silo.ToStringWithHashCode(), RangeFactory.CreateFullRange()));
var sb = new StringBuilder("[");
for (int i=0; i < membershipRingList.Count; i++)
{
SiloAddress curr = membershipRingList[ i ];
SiloAddress next = membershipRingList[ (i +1) % membershipRingList.Count];
IRingRange range = RangeFactory.CreateRange(unchecked((uint)curr.GetConsistentHashCode()), unchecked((uint)next.GetConsistentHashCode()));
sb.Append(String.Format("{0} -> {1}, ", curr.ToStringWithHashCode(), range));
}
sb.Append("]");
return sb.ToString();
}
}
internal void RemoveServer(SiloAddress silo)
{
lock (membershipRingList)
{
int indexOfFailedSilo = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (indexOfFailedSilo < 0) return; // we have already removed this silo
membershipRingList.Remove(silo);
// related to triggering handler
int myNewIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));
if (myNewIndex == -1)
throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, this.ToString()));
bool wasMyPred = ((myNewIndex == indexOfFailedSilo) || (myNewIndex == 0 && indexOfFailedSilo == membershipRingList.Count)); // no need for '- 1'
if (wasMyPred) // failed node was our predecessor
{
if (log.IsVerbose) log.Verbose("Failed server was my pred? {0}, updated view {1}", wasMyPred, this.ToString());
IRingRange oldRange = MyRange;
if (membershipRingList.Count == 1) // i'm the only one left
{
MyRange = RangeFactory.CreateFullRange();
NotifyLocalRangeSubscribers(oldRange, MyRange, true);
}
else
{
int myNewPredIndex = myNewIndex == 0 ? membershipRingList.Count - 1 : myNewIndex - 1;
int myPredecessorsHash = membershipRingList[myNewPredIndex].GetConsistentHashCode();
MyRange = RangeFactory.CreateRange(unchecked((uint)myPredecessorsHash), unchecked((uint)myKey));
NotifyLocalRangeSubscribers(oldRange, MyRange, true);
}
}
log.Info("Removed Server {0} hash {1}. Current view {2}", silo, silo.GetConsistentHashCode(), this.ToString());
}
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipRingList)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members.");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipRingList)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members.");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
#region Notification related
public bool SubscribeToRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer)) return false;
statusListeners.Add(observer);
return true;
}
}
public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased)
{
log.Info("-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old, now, increased);
List<IRingRangeListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (IRingRangeListener listener in copy)
{
try
{
listener.RangeChangeNotification(old, now, increased);
}
catch (Exception exc)
{
log.Error(ErrorCode.CRP_Local_Subscriber_Exception,
String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}",
listener.GetType().FullName, old, now, increased), exc);
}
}
}
#endregion
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (updatedSilo.Equals(MyAddress))
{
if (status.IsTerminating())
{
Stop();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
RemoveServer(updatedSilo);
}
else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active
{
AddServer(updatedSilo);
}
}
}
#endregion
/// <summary>
/// Finds the silo that owns the given hash value.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="hash"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true)
{
SiloAddress siloAddress;
lock (membershipRingList)
{
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = excludeThisSiloIfStopping && !isRunning;
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeMySelf ? null : MyAddress;
}
// use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ...
// if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
siloAddress = membershipRingList.Find(siloAddr => (siloAddr.GetConsistentHashCode() >= hash) && // <= hash for counter-clockwise responsibilities
(!siloAddr.Equals(MyAddress) || !excludeMySelf));
if (siloAddress == null)
{
// if not found in traversal, then first silo should be returned (we are on a ring)
// if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory
siloAddress = membershipRingList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
// vs [membershipRingList.Count - 2]; for counter-clockwise policy
siloAddress = membershipRingList.Count > 1 ? membershipRingList[1] : null;
}
}
}
if (log.IsVerbose2) log.Verbose2("Silo {0} calculated ring partition owner silo {1} for key {2}: {3} --> {4}", MyAddress, siloAddress, hash, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class RapidTestReport
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RapidTestReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.DeatilTable = new DevExpress.XtraReports.UI.XRTable();
this.DetailRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.HeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.HeaderRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.rapidTestDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestDataSet();
this.sp_Rep_VET_PensideTestsListTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestDataSetTableAdapters.sp_Rep_VET_PensideTestsListTableAdapter();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.DeatilTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rapidTestDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DeatilTable});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// DeatilTable
//
this.DeatilTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.DeatilTable, "DeatilTable");
this.DeatilTable.Name = "DeatilTable";
this.DeatilTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.DetailRow});
this.DeatilTable.StylePriority.UseBorders = false;
//
// DetailRow
//
this.DetailRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell2,
this.xrTableCell3,
this.xrTableCell4,
this.xrTableCell5});
resources.ApplyResources(this.DetailRow, "DetailRow");
this.DetailRow.Name = "DetailRow";
this.DetailRow.StylePriority.UseBackColor = false;
//
// xrTableCell1
//
this.xrTableCell1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetPensideTestsList.strTestName")});
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
//
// xrTableCell2
//
this.xrTableCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetPensideTestsList.strFieldSampleID")});
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
//
// xrTableCell3
//
this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetPensideTestsList.strSampleType")});
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
//
// xrTableCell4
//
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetPensideTestsList.strSpecies")});
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
//
// xrTableCell5
//
this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetPensideTestsList.strTestResult")});
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseFont = false;
//
// HeaderTable
//
this.HeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.HeaderTable, "HeaderTable");
this.HeaderTable.Name = "HeaderTable";
this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.HeaderRow});
this.HeaderTable.StylePriority.UseBorders = false;
//
// HeaderRow
//
this.HeaderRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell6,
this.xrTableCell12});
resources.ApplyResources(this.HeaderRow, "HeaderRow");
this.HeaderRow.Name = "HeaderRow";
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
//
// xrTableCell15
//
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageFooter.StylePriority.UseFont = false;
//
// rapidTestDataSet1
//
this.rapidTestDataSet1.DataSetName = "RapidTestDataSet";
this.rapidTestDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_Rep_VET_PensideTestsListTableAdapter
//
this.sp_Rep_VET_PensideTestsListTableAdapter.ClearBeforeFill = true;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.HeaderTable});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UseTextAlignment = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// RapidTestReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.DataAdapter = this.sp_Rep_VET_PensideTestsListTableAdapter;
this.DataMember = "spRepVetPensideTestsList";
this.DataSource = this.rapidTestDataSet1;
resources.ApplyResources(this, "$this");
this.ExportOptions.Xls.SheetName = resources.GetString("RapidTestReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("RapidTestReport.ExportOptions.Xlsx.SheetName");
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Version = "14.1";
((System.ComponentModel.ISupportInitialize)(this.DeatilTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rapidTestDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private RapidTestDataSet rapidTestDataSet1;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestDataSetTableAdapters.sp_Rep_VET_PensideTestsListTableAdapter sp_Rep_VET_PensideTestsListTableAdapter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTable HeaderTable;
private DevExpress.XtraReports.UI.XRTableRow HeaderRow;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTable DeatilTable;
private DevExpress.XtraReports.UI.XRTableRow DetailRow;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
}
}
| |
// 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.CognitiveServices
{
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>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<CognitiveServicesManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(CognitiveServicesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CognitiveServicesManagementClient
/// </summary>
public CognitiveServicesManagementClient Client { get; private set; }
/// <summary>
/// Lists all the available Cognitive Services account operations.
/// </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<OperationEntity>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.CognitiveServices/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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<OperationEntity>>();
_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<OperationEntity>>(_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>
/// Lists all the available Cognitive Services account operations.
/// </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<OperationEntity>>> 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<OperationEntity>>();
_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<OperationEntity>>(_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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Diagnostics;
namespace System.Runtime.Serialization.Formatters.Binary
{
// Routines to convert between the runtime type and the type as it appears on the wire
internal static class BinaryTypeConverter
{
// From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
{
BinaryTypeEnum binaryTypeEnum;
assemId = 0;
typeInformation = null;
if (ReferenceEquals(type, Converter.s_typeofString))
{
binaryTypeEnum = BinaryTypeEnum.String;
}
else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject)))
{
// If objectInfo.Si then can be a surrogate which will change the type
binaryTypeEnum = BinaryTypeEnum.Object;
}
else if (ReferenceEquals(type, Converter.s_typeofStringArray))
{
binaryTypeEnum = BinaryTypeEnum.StringArray;
}
else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
{
binaryTypeEnum = BinaryTypeEnum.ObjectArray;
}
else if (Converter.IsPrimitiveArray(type, out typeInformation))
{
binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
}
else
{
InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type);
switch (primitiveTypeEnum)
{
case InternalPrimitiveTypeE.Invalid:
string assembly = null;
if (objectInfo == null)
{
assembly = type.GetTypeInfo().Assembly.FullName;
typeInformation = type.FullName;
}
else
{
assembly = objectInfo.GetAssemblyString();
typeInformation = objectInfo.GetTypeFullName();
}
if (assembly.Equals(Converter.s_urtAssemblyString))
{
binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
assemId = 0;
}
else
{
binaryTypeEnum = BinaryTypeEnum.ObjectUser;
Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object");
assemId = (int)objectInfo._assemId;
if (assemId == 0)
{
throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, typeInformation));
}
}
break;
default:
binaryTypeEnum = BinaryTypeEnum.Primitive;
typeInformation = primitiveTypeEnum;
break;
}
}
return binaryTypeEnum;
}
// Used for non Si types when Parsing
internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object typeInformation)
{
BinaryTypeEnum binaryTypeEnum;
typeInformation = null;
if (ReferenceEquals(type, Converter.s_typeofString))
{
binaryTypeEnum = BinaryTypeEnum.String;
}
else if (ReferenceEquals(type, Converter.s_typeofObject))
{
binaryTypeEnum = BinaryTypeEnum.Object;
}
else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
{
binaryTypeEnum = BinaryTypeEnum.ObjectArray;
}
else if (ReferenceEquals(type, Converter.s_typeofStringArray))
{
binaryTypeEnum = BinaryTypeEnum.StringArray;
}
else if (Converter.IsPrimitiveArray(type, out typeInformation))
{
binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
}
else
{
InternalPrimitiveTypeE primitiveTypeEnum = Converter.ToCode(type);
switch (primitiveTypeEnum)
{
case InternalPrimitiveTypeE.Invalid:
binaryTypeEnum = type.GetTypeInfo().Assembly == Converter.s_urtAssembly ?
BinaryTypeEnum.ObjectUrt :
BinaryTypeEnum.ObjectUser;
typeInformation = type.FullName;
break;
default:
binaryTypeEnum = BinaryTypeEnum.Primitive;
typeInformation = primitiveTypeEnum;
break;
}
}
return binaryTypeEnum;
}
// Writes the type information on the wire
internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, int assemId, BinaryFormatterWriter output)
{
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
case BinaryTypeEnum.PrimitiveArray:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteByte((byte)((InternalPrimitiveTypeE)typeInformation));
break;
case BinaryTypeEnum.String:
case BinaryTypeEnum.Object:
case BinaryTypeEnum.StringArray:
case BinaryTypeEnum.ObjectArray:
break;
case BinaryTypeEnum.ObjectUrt:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteString(typeInformation.ToString());
break;
case BinaryTypeEnum.ObjectUser:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteString(typeInformation.ToString());
output.WriteInt32(assemId);
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeWrite, binaryTypeEnum.ToString()));
}
}
// Reads the type information from the wire
internal static object ReadTypeInfo(BinaryTypeEnum binaryTypeEnum, BinaryParser input, out int assemId)
{
object var = null;
int readAssemId = 0;
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
case BinaryTypeEnum.PrimitiveArray:
var = (InternalPrimitiveTypeE)input.ReadByte();
break;
case BinaryTypeEnum.String:
case BinaryTypeEnum.Object:
case BinaryTypeEnum.StringArray:
case BinaryTypeEnum.ObjectArray:
break;
case BinaryTypeEnum.ObjectUrt:
var = input.ReadString();
break;
case BinaryTypeEnum.ObjectUser:
var = input.ReadString();
readAssemId = input.ReadInt32();
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString()));
}
assemId = readAssemId;
return var;
}
// Given the wire type information, returns the actual type and additional information
internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum,
object typeInformation,
ObjectReader objectReader,
BinaryAssemblyInfo assemblyInfo,
out InternalPrimitiveTypeE primitiveTypeEnum,
out string typeString,
out Type type,
out bool isVariant)
{
isVariant = false;
primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
typeString = null;
type = null;
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
typeString = Converter.ToComType(primitiveTypeEnum);
type = Converter.ToType(primitiveTypeEnum);
break;
case BinaryTypeEnum.String:
type = Converter.s_typeofString;
break;
case BinaryTypeEnum.Object:
type = Converter.s_typeofObject;
isVariant = true;
break;
case BinaryTypeEnum.ObjectArray:
type = Converter.s_typeofObjectArray;
break;
case BinaryTypeEnum.StringArray:
type = Converter.s_typeofStringArray;
break;
case BinaryTypeEnum.PrimitiveArray:
primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
type = Converter.ToArrayType(primitiveTypeEnum);
break;
case BinaryTypeEnum.ObjectUser:
case BinaryTypeEnum.ObjectUrt:
if (typeInformation != null)
{
typeString = typeInformation.ToString();
type = objectReader.GetType(assemblyInfo, typeString);
if (ReferenceEquals(type, Converter.s_typeofObject))
{
isVariant = true;
}
}
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString()));
}
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* G Suite Activity API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/google-apps/activity/'>G Suite Activity API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170619 (900)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/google-apps/activity/'>
* https://developers.google.com/google-apps/activity/</a>
* <tr><th>Discovery Name<td>appsactivity
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using G Suite Activity API can be found at
* <a href='https://developers.google.com/google-apps/activity/'>https://developers.google.com/google-apps/activity/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Appsactivity.v1
{
/// <summary>The Appsactivity Service.</summary>
public class AppsactivityService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AppsactivityService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AppsactivityService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
activities = new ActivitiesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "appsactivity"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/appsactivity/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "appsactivity/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the G Suite Activity API.</summary>
public class Scope
{
/// <summary>View the activity history of your Google apps</summary>
public static string Activity = "https://www.googleapis.com/auth/activity";
/// <summary>View and manage the files in your Google Drive</summary>
public static string Drive = "https://www.googleapis.com/auth/drive";
/// <summary>View and manage metadata of files in your Google Drive</summary>
public static string DriveMetadata = "https://www.googleapis.com/auth/drive.metadata";
/// <summary>View metadata for files in your Google Drive</summary>
public static string DriveMetadataReadonly = "https://www.googleapis.com/auth/drive.metadata.readonly";
/// <summary>View the files in your Google Drive</summary>
public static string DriveReadonly = "https://www.googleapis.com/auth/drive.readonly";
}
private readonly ActivitiesResource activities;
/// <summary>Gets the Activities resource.</summary>
public virtual ActivitiesResource Activities
{
get { return activities; }
}
}
///<summary>A base abstract class for Appsactivity requests.</summary>
public abstract class AppsactivityBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new AppsactivityBaseServiceRequest instance.</summary>
protected AppsactivityBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Appsactivity parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "activities" collection of methods.</summary>
public class ActivitiesResource
{
private const string Resource = "activities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ActivitiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Returns a list of activities visible to the current logged in user. Visible activities are
/// determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An
/// activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped
/// to activities from a given Google service using the source parameter.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Returns a list of activities visible to the current logged in user. Visible activities are
/// determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An
/// activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped
/// to activities from a given Google service using the source parameter.</summary>
public class ListRequest : AppsactivityBaseServiceRequest<Google.Apis.Appsactivity.v1.Data.ListActivitiesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Identifies the Drive folder containing the items for which to return activities.</summary>
[Google.Apis.Util.RequestParameterAttribute("drive.ancestorId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DriveAncestorId { get; set; }
/// <summary>Identifies the Drive item to return activities for.</summary>
[Google.Apis.Util.RequestParameterAttribute("drive.fileId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DriveFileId { get; set; }
/// <summary>Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent
/// object.</summary>
/// [default: driveUi]
[Google.Apis.Util.RequestParameterAttribute("groupingStrategy", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<GroupingStrategyEnum> GroupingStrategy { get; set; }
/// <summary>Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent
/// object.</summary>
public enum GroupingStrategyEnum
{
[Google.Apis.Util.StringValueAttribute("driveUi")]
DriveUi,
[Google.Apis.Util.StringValueAttribute("none")]
None,
}
/// <summary>The maximum number of events to return on a page. The response includes a continuation token if
/// there are more events.</summary>
/// [default: 50]
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token to retrieve a specific page of results.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>The Google service from which to return activities. Possible values of source are: -
/// drive.google.com</summary>
[Google.Apis.Util.RequestParameterAttribute("source", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Source { get; set; }
/// <summary>Indicates the user to return activity for. Use the special value me to indicate the currently
/// authenticated user.</summary>
/// [default: me]
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserId { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "activities"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"drive.ancestorId", new Google.Apis.Discovery.Parameter
{
Name = "drive.ancestorId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"drive.fileId", new Google.Apis.Discovery.Parameter
{
Name = "drive.fileId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"groupingStrategy", new Google.Apis.Discovery.Parameter
{
Name = "groupingStrategy",
IsRequired = false,
ParameterType = "query",
DefaultValue = "driveUi",
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = "50",
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"source", new Google.Apis.Discovery.Parameter
{
Name = "source",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = false,
ParameterType = "query",
DefaultValue = "me",
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Appsactivity.v1.Data
{
/// <summary>An Activity resource is a combined view of multiple events. An activity has a list of individual events
/// and a combined view of the common fields among all events.</summary>
public class Activity : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The fields common to all of the singleEvents that make up the Activity.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("combinedEvent")]
public virtual Event CombinedEvent { get; set; }
/// <summary>A list of all the Events that make up the Activity.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("singleEvents")]
public virtual System.Collections.Generic.IList<Event> SingleEvents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the changes associated with an action taken by a user.</summary>
public class Event : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Additional event types. Some events may have multiple types when multiple actions are part of a
/// single event. For example, creating a document, renaming it, and sharing it may be part of a single file-
/// creation event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("additionalEventTypes")]
public virtual System.Collections.Generic.IList<string> AdditionalEventTypes { get; set; }
/// <summary>The time at which the event occurred formatted as Unix time in milliseconds.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventTimeMillis")]
public virtual System.Nullable<ulong> EventTimeMillis { get; set; }
/// <summary>Whether this event is caused by a user being deleted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fromUserDeletion")]
public virtual System.Nullable<bool> FromUserDeletion { get; set; }
/// <summary>Extra information for move type events, such as changes in an object's parents.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("move")]
public virtual Move Move { get; set; }
/// <summary>Extra information for permissionChange type events, such as the user or group the new permission
/// applies to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissionChanges")]
public virtual System.Collections.Generic.IList<PermissionChange> PermissionChanges { get; set; }
/// <summary>The main type of event that occurred.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("primaryEventType")]
public virtual string PrimaryEventType { get; set; }
/// <summary>Extra information for rename type events, such as the old and new names.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rename")]
public virtual Rename Rename { get; set; }
/// <summary>Information specific to the Target object modified by the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual Target Target { get; set; }
/// <summary>Represents the user responsible for the event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("user")]
public virtual User User { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response from the list request. Contains a list of activities and a token to retrieve the next page
/// of results.</summary>
public class ListActivitiesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of activities.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("activities")]
public virtual System.Collections.Generic.IList<Activity> Activities { get; set; }
/// <summary>Token for the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains information about changes in an object's parents as a result of a move type event.</summary>
public class Move : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The added parent(s).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("addedParents")]
public virtual System.Collections.Generic.IList<Parent> AddedParents { get; set; }
/// <summary>The removed parent(s).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("removedParents")]
public virtual System.Collections.Generic.IList<Parent> RemovedParents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains information about a parent object. For example, a folder in Drive is a parent for all files
/// within it.</summary>
public class Parent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The parent's ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Whether this is the root folder.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isRoot")]
public virtual System.Nullable<bool> IsRoot { get; set; }
/// <summary>The parent's title.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains information about the permissions and type of access allowed with regards to a Google Drive
/// object. This is a subset of the fields contained in a corresponding Drive Permissions object.</summary>
public class Permission : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the user or group the permission applies to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ID for this permission. Corresponds to the Drive API's permission ID returned as part of the
/// Drive Permissions resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissionId")]
public virtual string PermissionId { get; set; }
/// <summary>Indicates the Google Drive permissions role. The role determines a user's ability to read, write,
/// or comment on the file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>Indicates how widely permissions are granted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The user's information if the type is USER.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("user")]
public virtual User User { get; set; }
/// <summary>Whether the permission requires a link to the file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("withLink")]
public virtual System.Nullable<bool> WithLink { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains information about a Drive object's permissions that changed as a result of a permissionChange
/// type event.</summary>
public class PermissionChange : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Lists all Permission objects added.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("addedPermissions")]
public virtual System.Collections.Generic.IList<Permission> AddedPermissions { get; set; }
/// <summary>Lists all Permission objects removed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("removedPermissions")]
public virtual System.Collections.Generic.IList<Permission> RemovedPermissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Photo information for a user.</summary>
public class Photo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The URL of the photo.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("url")]
public virtual string Url { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Contains information about a renametype event.</summary>
public class Rename : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The new title.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("newTitle")]
public virtual string NewTitle { get; set; }
/// <summary>The old title.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("oldTitle")]
public virtual string OldTitle { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Information about the object modified by the event.</summary>
public class Target : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ID of the target. For example, in Google Drive, this is the file or folder ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The MIME type of the target.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mimeType")]
public virtual string MimeType { get; set; }
/// <summary>The name of the target. For example, in Google Drive, this is the title of the file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A representation of a user.</summary>
public class User : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A boolean which indicates whether the specified User was deleted. If true, name, photo and
/// permission_id will be omitted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isDeleted")]
public virtual System.Nullable<bool> IsDeleted { get; set; }
/// <summary>Whether the user is the authenticated user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isMe")]
public virtual System.Nullable<bool> IsMe { get; set; }
/// <summary>The displayable name of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The permission ID associated with this user. Equivalent to the Drive API's permission ID for this
/// user, returned as part of the Drive Permissions resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissionId")]
public virtual string PermissionId { get; set; }
/// <summary>The profile photo of the user. Not present if the user has no profile photo.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("photo")]
public virtual Photo Photo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedFlowsClientSnippets
{
/// <summary>Snippet for CreateFlow</summary>
public void CreateFlowRequestObject()
{
// Snippet: CreateFlow(CreateFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
CreateFlowRequest request = new CreateFlowRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
Flow = new Flow(),
LanguageCode = "",
};
// Make the request
Flow response = flowsClient.CreateFlow(request);
// End snippet
}
/// <summary>Snippet for CreateFlowAsync</summary>
public async Task CreateFlowRequestObjectAsync()
{
// Snippet: CreateFlowAsync(CreateFlowRequest, CallSettings)
// Additional: CreateFlowAsync(CreateFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
CreateFlowRequest request = new CreateFlowRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
Flow = new Flow(),
LanguageCode = "",
};
// Make the request
Flow response = await flowsClient.CreateFlowAsync(request);
// End snippet
}
/// <summary>Snippet for CreateFlow</summary>
public void CreateFlow()
{
// Snippet: CreateFlow(string, Flow, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
Flow flow = new Flow();
// Make the request
Flow response = flowsClient.CreateFlow(parent, flow);
// End snippet
}
/// <summary>Snippet for CreateFlowAsync</summary>
public async Task CreateFlowAsync()
{
// Snippet: CreateFlowAsync(string, Flow, CallSettings)
// Additional: CreateFlowAsync(string, Flow, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
Flow flow = new Flow();
// Make the request
Flow response = await flowsClient.CreateFlowAsync(parent, flow);
// End snippet
}
/// <summary>Snippet for CreateFlow</summary>
public void CreateFlowResourceNames()
{
// Snippet: CreateFlow(AgentName, Flow, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
Flow flow = new Flow();
// Make the request
Flow response = flowsClient.CreateFlow(parent, flow);
// End snippet
}
/// <summary>Snippet for CreateFlowAsync</summary>
public async Task CreateFlowResourceNamesAsync()
{
// Snippet: CreateFlowAsync(AgentName, Flow, CallSettings)
// Additional: CreateFlowAsync(AgentName, Flow, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
Flow flow = new Flow();
// Make the request
Flow response = await flowsClient.CreateFlowAsync(parent, flow);
// End snippet
}
/// <summary>Snippet for DeleteFlow</summary>
public void DeleteFlowRequestObject()
{
// Snippet: DeleteFlow(DeleteFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
DeleteFlowRequest request = new DeleteFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
Force = false,
};
// Make the request
flowsClient.DeleteFlow(request);
// End snippet
}
/// <summary>Snippet for DeleteFlowAsync</summary>
public async Task DeleteFlowRequestObjectAsync()
{
// Snippet: DeleteFlowAsync(DeleteFlowRequest, CallSettings)
// Additional: DeleteFlowAsync(DeleteFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
DeleteFlowRequest request = new DeleteFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
Force = false,
};
// Make the request
await flowsClient.DeleteFlowAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteFlow</summary>
public void DeleteFlow()
{
// Snippet: DeleteFlow(string, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
flowsClient.DeleteFlow(name);
// End snippet
}
/// <summary>Snippet for DeleteFlowAsync</summary>
public async Task DeleteFlowAsync()
{
// Snippet: DeleteFlowAsync(string, CallSettings)
// Additional: DeleteFlowAsync(string, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
await flowsClient.DeleteFlowAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteFlow</summary>
public void DeleteFlowResourceNames()
{
// Snippet: DeleteFlow(FlowName, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
flowsClient.DeleteFlow(name);
// End snippet
}
/// <summary>Snippet for DeleteFlowAsync</summary>
public async Task DeleteFlowResourceNamesAsync()
{
// Snippet: DeleteFlowAsync(FlowName, CallSettings)
// Additional: DeleteFlowAsync(FlowName, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
await flowsClient.DeleteFlowAsync(name);
// End snippet
}
/// <summary>Snippet for ListFlows</summary>
public void ListFlowsRequestObject()
{
// Snippet: ListFlows(ListFlowsRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
ListFlowsRequest request = new ListFlowsRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlows(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Flow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListFlowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFlowsAsync</summary>
public async Task ListFlowsRequestObjectAsync()
{
// Snippet: ListFlowsAsync(ListFlowsRequest, CallSettings)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
ListFlowsRequest request = new ListFlowsRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
LanguageCode = "",
};
// Make the request
PagedAsyncEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlowsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Flow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListFlowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFlows</summary>
public void ListFlows()
{
// Snippet: ListFlows(string, string, int?, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Flow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListFlowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFlowsAsync</summary>
public async Task ListFlowsAsync()
{
// Snippet: ListFlowsAsync(string, string, int?, CallSettings)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]";
// Make the request
PagedAsyncEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Flow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListFlowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFlows</summary>
public void ListFlowsResourceNames()
{
// Snippet: ListFlows(AgentName, string, int?, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Flow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListFlowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFlowsAsync</summary>
public async Task ListFlowsResourceNamesAsync()
{
// Snippet: ListFlowsAsync(AgentName, string, int?, CallSettings)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedAsyncEnumerable<ListFlowsResponse, Flow> response = flowsClient.ListFlowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Flow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListFlowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Flow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Flow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Flow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetFlow</summary>
public void GetFlowRequestObject()
{
// Snippet: GetFlow(GetFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
GetFlowRequest request = new GetFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
Flow response = flowsClient.GetFlow(request);
// End snippet
}
/// <summary>Snippet for GetFlowAsync</summary>
public async Task GetFlowRequestObjectAsync()
{
// Snippet: GetFlowAsync(GetFlowRequest, CallSettings)
// Additional: GetFlowAsync(GetFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
GetFlowRequest request = new GetFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
Flow response = await flowsClient.GetFlowAsync(request);
// End snippet
}
/// <summary>Snippet for GetFlow</summary>
public void GetFlow()
{
// Snippet: GetFlow(string, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
Flow response = flowsClient.GetFlow(name);
// End snippet
}
/// <summary>Snippet for GetFlowAsync</summary>
public async Task GetFlowAsync()
{
// Snippet: GetFlowAsync(string, CallSettings)
// Additional: GetFlowAsync(string, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
Flow response = await flowsClient.GetFlowAsync(name);
// End snippet
}
/// <summary>Snippet for GetFlow</summary>
public void GetFlowResourceNames()
{
// Snippet: GetFlow(FlowName, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
Flow response = flowsClient.GetFlow(name);
// End snippet
}
/// <summary>Snippet for GetFlowAsync</summary>
public async Task GetFlowResourceNamesAsync()
{
// Snippet: GetFlowAsync(FlowName, CallSettings)
// Additional: GetFlowAsync(FlowName, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
Flow response = await flowsClient.GetFlowAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateFlow</summary>
public void UpdateFlowRequestObject()
{
// Snippet: UpdateFlow(UpdateFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
UpdateFlowRequest request = new UpdateFlowRequest
{
Flow = new Flow(),
UpdateMask = new FieldMask(),
LanguageCode = "",
};
// Make the request
Flow response = flowsClient.UpdateFlow(request);
// End snippet
}
/// <summary>Snippet for UpdateFlowAsync</summary>
public async Task UpdateFlowRequestObjectAsync()
{
// Snippet: UpdateFlowAsync(UpdateFlowRequest, CallSettings)
// Additional: UpdateFlowAsync(UpdateFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
UpdateFlowRequest request = new UpdateFlowRequest
{
Flow = new Flow(),
UpdateMask = new FieldMask(),
LanguageCode = "",
};
// Make the request
Flow response = await flowsClient.UpdateFlowAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateFlow</summary>
public void UpdateFlow()
{
// Snippet: UpdateFlow(Flow, FieldMask, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
Flow flow = new Flow();
FieldMask updateMask = new FieldMask();
// Make the request
Flow response = flowsClient.UpdateFlow(flow, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateFlowAsync</summary>
public async Task UpdateFlowAsync()
{
// Snippet: UpdateFlowAsync(Flow, FieldMask, CallSettings)
// Additional: UpdateFlowAsync(Flow, FieldMask, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
Flow flow = new Flow();
FieldMask updateMask = new FieldMask();
// Make the request
Flow response = await flowsClient.UpdateFlowAsync(flow, updateMask);
// End snippet
}
/// <summary>Snippet for TrainFlow</summary>
public void TrainFlowRequestObject()
{
// Snippet: TrainFlow(TrainFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
TrainFlowRequest request = new TrainFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
};
// Make the request
Operation<Empty, Struct> response = flowsClient.TrainFlow(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = flowsClient.PollOnceTrainFlow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TrainFlowAsync</summary>
public async Task TrainFlowRequestObjectAsync()
{
// Snippet: TrainFlowAsync(TrainFlowRequest, CallSettings)
// Additional: TrainFlowAsync(TrainFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
TrainFlowRequest request = new TrainFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
};
// Make the request
Operation<Empty, Struct> response = await flowsClient.TrainFlowAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = await flowsClient.PollOnceTrainFlowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TrainFlow</summary>
public void TrainFlow()
{
// Snippet: TrainFlow(string, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
Operation<Empty, Struct> response = flowsClient.TrainFlow(name);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = flowsClient.PollOnceTrainFlow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TrainFlowAsync</summary>
public async Task TrainFlowAsync()
{
// Snippet: TrainFlowAsync(string, CallSettings)
// Additional: TrainFlowAsync(string, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]";
// Make the request
Operation<Empty, Struct> response = await flowsClient.TrainFlowAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = await flowsClient.PollOnceTrainFlowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TrainFlow</summary>
public void TrainFlowResourceNames()
{
// Snippet: TrainFlow(FlowName, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
Operation<Empty, Struct> response = flowsClient.TrainFlow(name);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = flowsClient.PollOnceTrainFlow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TrainFlowAsync</summary>
public async Task TrainFlowResourceNamesAsync()
{
// Snippet: TrainFlowAsync(FlowName, CallSettings)
// Additional: TrainFlowAsync(FlowName, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
FlowName name = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
Operation<Empty, Struct> response = await flowsClient.TrainFlowAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse = await flowsClient.PollOnceTrainFlowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ValidateFlow</summary>
public void ValidateFlowRequestObject()
{
// Snippet: ValidateFlow(ValidateFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
ValidateFlowRequest request = new ValidateFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
FlowValidationResult response = flowsClient.ValidateFlow(request);
// End snippet
}
/// <summary>Snippet for ValidateFlowAsync</summary>
public async Task ValidateFlowRequestObjectAsync()
{
// Snippet: ValidateFlowAsync(ValidateFlowRequest, CallSettings)
// Additional: ValidateFlowAsync(ValidateFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
ValidateFlowRequest request = new ValidateFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
FlowValidationResult response = await flowsClient.ValidateFlowAsync(request);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResult</summary>
public void GetFlowValidationResultRequestObject()
{
// Snippet: GetFlowValidationResult(GetFlowValidationResultRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
GetFlowValidationResultRequest request = new GetFlowValidationResultRequest
{
FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
FlowValidationResult response = flowsClient.GetFlowValidationResult(request);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResultAsync</summary>
public async Task GetFlowValidationResultRequestObjectAsync()
{
// Snippet: GetFlowValidationResultAsync(GetFlowValidationResultRequest, CallSettings)
// Additional: GetFlowValidationResultAsync(GetFlowValidationResultRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
GetFlowValidationResultRequest request = new GetFlowValidationResultRequest
{
FlowValidationResultName = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
LanguageCode = "",
};
// Make the request
FlowValidationResult response = await flowsClient.GetFlowValidationResultAsync(request);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResult</summary>
public void GetFlowValidationResult()
{
// Snippet: GetFlowValidationResult(string, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/validationResult";
// Make the request
FlowValidationResult response = flowsClient.GetFlowValidationResult(name);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResultAsync</summary>
public async Task GetFlowValidationResultAsync()
{
// Snippet: GetFlowValidationResultAsync(string, CallSettings)
// Additional: GetFlowValidationResultAsync(string, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/validationResult";
// Make the request
FlowValidationResult response = await flowsClient.GetFlowValidationResultAsync(name);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResult</summary>
public void GetFlowValidationResultResourceNames()
{
// Snippet: GetFlowValidationResult(FlowValidationResultName, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
FlowValidationResultName name = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
FlowValidationResult response = flowsClient.GetFlowValidationResult(name);
// End snippet
}
/// <summary>Snippet for GetFlowValidationResultAsync</summary>
public async Task GetFlowValidationResultResourceNamesAsync()
{
// Snippet: GetFlowValidationResultAsync(FlowValidationResultName, CallSettings)
// Additional: GetFlowValidationResultAsync(FlowValidationResultName, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
FlowValidationResultName name = FlowValidationResultName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]");
// Make the request
FlowValidationResult response = await flowsClient.GetFlowValidationResultAsync(name);
// End snippet
}
/// <summary>Snippet for ImportFlow</summary>
public void ImportFlowRequestObject()
{
// Snippet: ImportFlow(ImportFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
ImportFlowRequest request = new ImportFlowRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
FlowUri = "",
ImportOption = ImportFlowRequest.Types.ImportOption.Unspecified,
};
// Make the request
Operation<ImportFlowResponse, Struct> response = flowsClient.ImportFlow(request);
// Poll until the returned long-running operation is complete
Operation<ImportFlowResponse, Struct> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportFlowResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportFlowResponse, Struct> retrievedResponse = flowsClient.PollOnceImportFlow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportFlowResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportFlowAsync</summary>
public async Task ImportFlowRequestObjectAsync()
{
// Snippet: ImportFlowAsync(ImportFlowRequest, CallSettings)
// Additional: ImportFlowAsync(ImportFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
ImportFlowRequest request = new ImportFlowRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
FlowUri = "",
ImportOption = ImportFlowRequest.Types.ImportOption.Unspecified,
};
// Make the request
Operation<ImportFlowResponse, Struct> response = await flowsClient.ImportFlowAsync(request);
// Poll until the returned long-running operation is complete
Operation<ImportFlowResponse, Struct> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportFlowResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportFlowResponse, Struct> retrievedResponse = await flowsClient.PollOnceImportFlowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportFlowResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportFlow</summary>
public void ExportFlowRequestObject()
{
// Snippet: ExportFlow(ExportFlowRequest, CallSettings)
// Create client
FlowsClient flowsClient = FlowsClient.Create();
// Initialize request argument(s)
ExportFlowRequest request = new ExportFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
FlowUri = "",
IncludeReferencedFlows = false,
};
// Make the request
Operation<ExportFlowResponse, Struct> response = flowsClient.ExportFlow(request);
// Poll until the returned long-running operation is complete
Operation<ExportFlowResponse, Struct> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ExportFlowResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportFlowResponse, Struct> retrievedResponse = flowsClient.PollOnceExportFlow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportFlowResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportFlowAsync</summary>
public async Task ExportFlowRequestObjectAsync()
{
// Snippet: ExportFlowAsync(ExportFlowRequest, CallSettings)
// Additional: ExportFlowAsync(ExportFlowRequest, CancellationToken)
// Create client
FlowsClient flowsClient = await FlowsClient.CreateAsync();
// Initialize request argument(s)
ExportFlowRequest request = new ExportFlowRequest
{
FlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
FlowUri = "",
IncludeReferencedFlows = false,
};
// Make the request
Operation<ExportFlowResponse, Struct> response = await flowsClient.ExportFlowAsync(request);
// Poll until the returned long-running operation is complete
Operation<ExportFlowResponse, Struct> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportFlowResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportFlowResponse, Struct> retrievedResponse = await flowsClient.PollOnceExportFlowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportFlowResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// <copyright file="ProcessorSupport.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BeanIO.Internal.Config;
namespace BeanIO.Internal.Compiler
{
/// <summary>
/// A base class for configuration processors
/// </summary>
/// <remarks>
/// The class provides support for traversing a tree of stream
/// configuration components and generates a "stack trace" if
/// any overridden method throws a <see cref="BeanIOConfigurationException"/>.
/// </remarks>
internal abstract class ProcessorSupport
{
private readonly Stack<ComponentConfig> _componentConfigurations = new Stack<ComponentConfig>();
/// <summary>
/// Gets the parent component for the component being processed
/// </summary>
protected virtual ComponentConfig Parent
{
get
{
if (_componentConfigurations.Count > 1)
return _componentConfigurations.Skip(1).First();
return null;
}
}
/// <summary>
/// Processes a stream configuration
/// </summary>
/// <param name="stream">the <see cref="StreamConfig"/> to process</param>
public virtual void Process(StreamConfig stream)
{
try
{
HandleComponent(stream);
}
catch (BeanIOConfigurationException ex)
{
var message = new StringBuilder();
message.Append("Invalid ");
var index = 0;
foreach (var node in _componentConfigurations)
{
string type;
switch (node.ComponentType)
{
case ComponentType.Constant:
type = "property";
break;
default:
type = node.ComponentType.ToString().ToLowerInvariant();
break;
}
++index;
if (index > 1)
message.Append(", in ");
message.AppendFormat("{0} '{1}'", type, node.Name);
}
message.AppendFormat(": {0}", ex.Message);
throw new BeanIOConfigurationException(message.ToString(), ex);
}
}
/// <summary>
/// Recursively preprocesses a component and its descendants
/// </summary>
/// <param name="component">the component to preprocess</param>
protected virtual void HandleComponent(ComponentConfig component)
{
_componentConfigurations.Push(component);
switch (component.ComponentType)
{
case ComponentType.Stream:
InitializeStream((StreamConfig)component);
foreach (var child in component)
HandleComponent(child);
FinalizeStream((StreamConfig)component);
break;
case ComponentType.Group:
InitializeGroup((GroupConfig)component);
foreach (ComponentConfig child in component)
HandleComponent(child);
FinalizeGroup((GroupConfig)component);
break;
case ComponentType.Record:
InitializeRecord((RecordConfig)component);
foreach (ComponentConfig child in component)
HandleComponent(child);
FinalizeRecord((RecordConfig)component);
break;
case ComponentType.Segment:
InitializeSegment((SegmentConfig)component);
foreach (ComponentConfig child in component)
HandleComponent(child);
FinalizeSegment((SegmentConfig)component);
break;
case ComponentType.Field:
HandleField((FieldConfig)component);
break;
case ComponentType.Constant:
HandleConstant((ConstantConfig)component);
break;
}
_componentConfigurations.Pop();
}
/// <summary>
/// Initializes a stream configuration before its children have been processed
/// </summary>
/// <param name="stream">the stream configuration to process</param>
protected virtual void InitializeStream(StreamConfig stream)
{
}
/// <summary>
/// Finalizes a stream configuration after its children have been processed
/// </summary>
/// <param name="stream">the stream configuration to finalize</param>
protected virtual void FinalizeStream(StreamConfig stream)
{
}
/// <summary>
/// Initializes a group configuration before its children have been processed
/// </summary>
/// <param name="group">the group configuration to process</param>
protected virtual void InitializeGroup(GroupConfig group)
{
}
/// <summary>
/// Finalizes a group configuration after its children have been processed
/// </summary>
/// <param name="group">the group configuration to finalize</param>
protected virtual void FinalizeGroup(GroupConfig group)
{
}
/// <summary>
/// Initializes a record configuration before its children have been processed
/// </summary>
/// <param name="record">the record configuration to process</param>
protected virtual void InitializeRecord(RecordConfig record)
{
}
/// <summary>
/// Finalizes a record configuration after its children have been processed
/// </summary>
/// <param name="record">the record configuration to finalize</param>
protected virtual void FinalizeRecord(RecordConfig record)
{
}
/// <summary>
/// Initializes a segment configuration before its children have been processed
/// </summary>
/// <param name="segment">the segment configuration to process</param>
protected virtual void InitializeSegment(SegmentConfig segment)
{
}
/// <summary>
/// Finalizes a segment configuration after its children have been processed
/// </summary>
/// <param name="segment">the segment configuration to finalize</param>
protected virtual void FinalizeSegment(SegmentConfig segment)
{
}
/// <summary>
/// Processes a field configuration
/// </summary>
/// <param name="field">the field configuration to process</param>
protected virtual void HandleField(FieldConfig field)
{
}
/// <summary>
/// Processes a constant configuration
/// </summary>
/// <param name="constant">the constant configuration to process</param>
protected virtual void HandleConstant(ConstantConfig constant)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalUInt6464()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt6464();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalUInt6464
{
private struct TestStruct
{
public Vector256<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalUInt6464 testClass)
{
var result = Avx2.ShiftLeftLogical(_fld, 64);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector256<UInt64> _clsVar;
private Vector256<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalUInt6464()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalUInt6464()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt6464();
var result = Avx2.ShiftLeftLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt64>(Vector256<UInt64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class HeaderoutDialog
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HeaderoutDialog));
this.btnHelp = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.fontSizeToolStripDDL = new System.Windows.Forms.ToolStripComboBox();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.boldToolStripButton = new System.Windows.Forms.ToolStripButton();
this.italicToolStripButton = new System.Windows.Forms.ToolStripButton();
this.underlineToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.fontColorToolStripDDL = new System.Windows.Forms.ToolStripSplitButton();
this.defaultToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aquaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.blackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.blueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cyanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fuchsiaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.grayToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.greenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.limeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.magentaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.maroonToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.navyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.oliveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.purpleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.silverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tealToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.whiteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.yellowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.txtTitle = new System.Windows.Forms.RichTextBox();
this.lblTitle = new System.Windows.Forms.Label();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Name = "btnCancel";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Name = "btnOK";
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// toolStrip1
//
resources.ApplyResources(this.toolStrip1, "toolStrip1");
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fontSizeToolStripDDL,
this.toolStripSeparator1,
this.boldToolStripButton,
this.italicToolStripButton,
this.underlineToolStripButton,
this.toolStripSeparator2,
this.fontColorToolStripDDL});
this.toolStrip1.Name = "toolStrip1";
//
// fontSizeToolStripDDL
//
this.fontSizeToolStripDDL.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.fontSizeToolStripDDL.Items.AddRange(new object[] {
resources.GetString("fontSizeToolStripDDL.Items"),
resources.GetString("fontSizeToolStripDDL.Items1"),
resources.GetString("fontSizeToolStripDDL.Items2"),
resources.GetString("fontSizeToolStripDDL.Items3"),
resources.GetString("fontSizeToolStripDDL.Items4"),
resources.GetString("fontSizeToolStripDDL.Items5"),
resources.GetString("fontSizeToolStripDDL.Items6"),
resources.GetString("fontSizeToolStripDDL.Items7"),
resources.GetString("fontSizeToolStripDDL.Items8"),
resources.GetString("fontSizeToolStripDDL.Items9"),
resources.GetString("fontSizeToolStripDDL.Items10"),
resources.GetString("fontSizeToolStripDDL.Items11"),
resources.GetString("fontSizeToolStripDDL.Items12"),
resources.GetString("fontSizeToolStripDDL.Items13"),
resources.GetString("fontSizeToolStripDDL.Items14"),
resources.GetString("fontSizeToolStripDDL.Items15"),
resources.GetString("fontSizeToolStripDDL.Items16"),
resources.GetString("fontSizeToolStripDDL.Items17"),
resources.GetString("fontSizeToolStripDDL.Items18"),
resources.GetString("fontSizeToolStripDDL.Items19"),
resources.GetString("fontSizeToolStripDDL.Items20"),
resources.GetString("fontSizeToolStripDDL.Items21")});
resources.ApplyResources(this.fontSizeToolStripDDL, "fontSizeToolStripDDL");
this.fontSizeToolStripDDL.MergeAction = System.Windows.Forms.MergeAction.MatchOnly;
this.fontSizeToolStripDDL.Name = "fontSizeToolStripDDL";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// boldToolStripButton
//
this.boldToolStripButton.CheckOnClick = true;
this.boldToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.boldToolStripButton, "boldToolStripButton");
this.boldToolStripButton.Name = "boldToolStripButton";
//
// italicToolStripButton
//
this.italicToolStripButton.CheckOnClick = true;
this.italicToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.italicToolStripButton, "italicToolStripButton");
this.italicToolStripButton.Name = "italicToolStripButton";
//
// underlineToolStripButton
//
this.underlineToolStripButton.CheckOnClick = true;
this.underlineToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.underlineToolStripButton, "underlineToolStripButton");
this.underlineToolStripButton.Name = "underlineToolStripButton";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// fontColorToolStripDDL
//
this.fontColorToolStripDDL.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.defaultToolStripMenuItem,
this.aquaToolStripMenuItem,
this.blackToolStripMenuItem,
this.blueToolStripMenuItem,
this.cyanToolStripMenuItem,
this.fuchsiaToolStripMenuItem,
this.grayToolStripMenuItem,
this.greenToolStripMenuItem,
this.limeToolStripMenuItem,
this.magentaToolStripMenuItem,
this.maroonToolStripMenuItem,
this.navyToolStripMenuItem,
this.oliveToolStripMenuItem,
this.purpleToolStripMenuItem,
this.redToolStripMenuItem,
this.silverToolStripMenuItem,
this.tealToolStripMenuItem,
this.whiteToolStripMenuItem,
this.yellowToolStripMenuItem});
resources.ApplyResources(this.fontColorToolStripDDL, "fontColorToolStripDDL");
this.fontColorToolStripDDL.Name = "fontColorToolStripDDL";
this.fontColorToolStripDDL.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.fontColorToolStripDDL_DropDownItemClicked);
//
// defaultToolStripMenuItem
//
this.defaultToolStripMenuItem.Name = "defaultToolStripMenuItem";
resources.ApplyResources(this.defaultToolStripMenuItem, "defaultToolStripMenuItem");
//
// aquaToolStripMenuItem
//
this.aquaToolStripMenuItem.BackColor = System.Drawing.Color.Aqua;
this.aquaToolStripMenuItem.Name = "aquaToolStripMenuItem";
resources.ApplyResources(this.aquaToolStripMenuItem, "aquaToolStripMenuItem");
//
// blackToolStripMenuItem
//
this.blackToolStripMenuItem.BackColor = System.Drawing.Color.Black;
this.blackToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.blackToolStripMenuItem.Name = "blackToolStripMenuItem";
resources.ApplyResources(this.blackToolStripMenuItem, "blackToolStripMenuItem");
//
// blueToolStripMenuItem
//
this.blueToolStripMenuItem.BackColor = System.Drawing.Color.Blue;
this.blueToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.blueToolStripMenuItem.Name = "blueToolStripMenuItem";
resources.ApplyResources(this.blueToolStripMenuItem, "blueToolStripMenuItem");
//
// cyanToolStripMenuItem
//
this.cyanToolStripMenuItem.BackColor = System.Drawing.Color.Cyan;
this.cyanToolStripMenuItem.Name = "cyanToolStripMenuItem";
resources.ApplyResources(this.cyanToolStripMenuItem, "cyanToolStripMenuItem");
//
// fuchsiaToolStripMenuItem
//
this.fuchsiaToolStripMenuItem.BackColor = System.Drawing.Color.Fuchsia;
this.fuchsiaToolStripMenuItem.Name = "fuchsiaToolStripMenuItem";
resources.ApplyResources(this.fuchsiaToolStripMenuItem, "fuchsiaToolStripMenuItem");
//
// grayToolStripMenuItem
//
this.grayToolStripMenuItem.BackColor = System.Drawing.Color.Gray;
this.grayToolStripMenuItem.Name = "grayToolStripMenuItem";
resources.ApplyResources(this.grayToolStripMenuItem, "grayToolStripMenuItem");
//
// greenToolStripMenuItem
//
this.greenToolStripMenuItem.BackColor = System.Drawing.Color.Green;
this.greenToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.greenToolStripMenuItem.Name = "greenToolStripMenuItem";
resources.ApplyResources(this.greenToolStripMenuItem, "greenToolStripMenuItem");
//
// limeToolStripMenuItem
//
this.limeToolStripMenuItem.BackColor = System.Drawing.Color.Lime;
this.limeToolStripMenuItem.Name = "limeToolStripMenuItem";
resources.ApplyResources(this.limeToolStripMenuItem, "limeToolStripMenuItem");
//
// magentaToolStripMenuItem
//
this.magentaToolStripMenuItem.BackColor = System.Drawing.Color.Magenta;
this.magentaToolStripMenuItem.Name = "magentaToolStripMenuItem";
resources.ApplyResources(this.magentaToolStripMenuItem, "magentaToolStripMenuItem");
//
// maroonToolStripMenuItem
//
this.maroonToolStripMenuItem.BackColor = System.Drawing.Color.Maroon;
this.maroonToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.maroonToolStripMenuItem.Name = "maroonToolStripMenuItem";
resources.ApplyResources(this.maroonToolStripMenuItem, "maroonToolStripMenuItem");
//
// navyToolStripMenuItem
//
this.navyToolStripMenuItem.BackColor = System.Drawing.Color.Navy;
this.navyToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.navyToolStripMenuItem.Name = "navyToolStripMenuItem";
resources.ApplyResources(this.navyToolStripMenuItem, "navyToolStripMenuItem");
//
// oliveToolStripMenuItem
//
this.oliveToolStripMenuItem.BackColor = System.Drawing.Color.Olive;
this.oliveToolStripMenuItem.Name = "oliveToolStripMenuItem";
resources.ApplyResources(this.oliveToolStripMenuItem, "oliveToolStripMenuItem");
//
// purpleToolStripMenuItem
//
this.purpleToolStripMenuItem.BackColor = System.Drawing.Color.Purple;
this.purpleToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.purpleToolStripMenuItem.Name = "purpleToolStripMenuItem";
resources.ApplyResources(this.purpleToolStripMenuItem, "purpleToolStripMenuItem");
//
// redToolStripMenuItem
//
this.redToolStripMenuItem.BackColor = System.Drawing.Color.Red;
this.redToolStripMenuItem.Name = "redToolStripMenuItem";
resources.ApplyResources(this.redToolStripMenuItem, "redToolStripMenuItem");
//
// silverToolStripMenuItem
//
this.silverToolStripMenuItem.BackColor = System.Drawing.Color.Silver;
this.silverToolStripMenuItem.Name = "silverToolStripMenuItem";
resources.ApplyResources(this.silverToolStripMenuItem, "silverToolStripMenuItem");
//
// tealToolStripMenuItem
//
this.tealToolStripMenuItem.BackColor = System.Drawing.Color.Teal;
this.tealToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.tealToolStripMenuItem.Name = "tealToolStripMenuItem";
resources.ApplyResources(this.tealToolStripMenuItem, "tealToolStripMenuItem");
//
// whiteToolStripMenuItem
//
this.whiteToolStripMenuItem.BackColor = System.Drawing.Color.White;
this.whiteToolStripMenuItem.Name = "whiteToolStripMenuItem";
resources.ApplyResources(this.whiteToolStripMenuItem, "whiteToolStripMenuItem");
//
// yellowToolStripMenuItem
//
this.yellowToolStripMenuItem.BackColor = System.Drawing.Color.Yellow;
this.yellowToolStripMenuItem.Name = "yellowToolStripMenuItem";
resources.ApplyResources(this.yellowToolStripMenuItem, "yellowToolStripMenuItem");
//
// txtTitle
//
resources.ApplyResources(this.txtTitle, "txtTitle");
this.txtTitle.Name = "txtTitle";
//
// lblTitle
//
resources.ApplyResources(this.lblTitle, "lblTitle");
this.lblTitle.Name = "lblTitle";
//
// HeaderoutDialog
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.lblTitle);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "HeaderoutDialog";
this.ShowIcon = false;
this.Load += new System.EventHandler(this.HeaderoutDialog_Load);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripComboBox fontSizeToolStripDDL;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton boldToolStripButton;
private System.Windows.Forms.ToolStripButton italicToolStripButton;
private System.Windows.Forms.ToolStripButton underlineToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSplitButton fontColorToolStripDDL;
private System.Windows.Forms.ToolStripMenuItem defaultToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aquaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem blackToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem blueToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cyanToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fuchsiaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem grayToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem greenToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem limeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem magentaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem maroonToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem navyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem oliveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem purpleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem silverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tealToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem whiteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem yellowToolStripMenuItem;
private System.Windows.Forms.RichTextBox txtTitle;
private System.Windows.Forms.Label lblTitle;
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using PixelFarm.VectorMath;
using PixelFarm.Drawing;
namespace PixelFarm.CpuBlit.VertexProcessing
{
public static class MyMath
{
public static bool MinDistanceFirst(Vector2 baseVec, Vector2 compare0, Vector2 compare1)
{
return (SquareDistance(baseVec, compare0) < SquareDistance(baseVec, compare1)) ? true : false;
}
public static double SquareDistance(Vector2 v0, Vector2 v1)
{
double xdiff = v1.X - v0.X;
double ydiff = v1.Y - v0.Y;
return (xdiff * xdiff) + (ydiff * ydiff);
}
/// <summary>
/// find parameter A,B,C from Ax + By = C, with given 2 points
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
static void FindABC(Vector2 p0, Vector2 p1, out double a, out double b, out double c)
{
//line is in the form
//Ax + By = C
//from http://stackoverflow.com/questions/4543506/algorithm-for-intersection-of-2-lines
//and https://www.topcoder.com/community/data-science/data-science-tutorials/geometry-concepts-line-intersection-and-its-applications/
a = p1.Y - p0.Y;
b = p0.X - p1.X;
c = a * p0.X + b * p0.Y;
}
public static bool FindCutPoint(
Vector2 p0, Vector2 p1,
Vector2 p2, Vector2 p3, out Vector2 result)
{
//TODO: review here
//from http://stackoverflow.com/questions/4543506/algorithm-for-intersection-of-2-lines
//and https://www.topcoder.com/community/data-science/data-science-tutorials/geometry-concepts-line-intersection-and-its-applications/
//------------------------------------------
//use matrix style ***
//------------------------------------------
//line is in the form
//Ax + By = C
//so A1x +B1y= C1 ... line1
// A2x +B2y=C2 ... line2
//------------------------------------------
//
//from Ax+By=C ... (1)
//By = C- Ax;
double a1, b1, c1;
FindABC(p0, p1, out a1, out b1, out c1);
double a2, b2, c2;
FindABC(p2, p3, out a2, out b2, out c2);
double delta = a1 * b2 - a2 * b1; //delta is the determinant in math parlance
if (delta == 0)
{
//"Lines are parallel"
result = Vector2.Zero;
return false; //
throw new System.ArgumentException("Lines are parallel");
}
double x = (b2 * c1 - b1 * c2) / delta;
double y = (a1 * c2 - a2 * c1) / delta;
result = new Vector2((float)x, (float)y);
return true; //has cutpoint
}
static double FindB(Vector2 p0, Vector2 p1)
{
double m1 = (p1.Y - p0.Y) / (p1.X - p0.X);
//y = mx + b ...(1)
//b = y- mx
//substitute with known value to gett b
//double b0 = p0.Y - (slope_m) * p0.X;
//double b1 = p1.Y - (slope_m) * p1.X;
//return b0;
return p0.Y - (m1) * p0.X;
}
}
class LineJoiner
{
int _mitterLimit = 4; //default
double x0, y0, x1, y1, x2, y2;
public LineJoiner()
{
//_mitterLimit = 1;
}
public LineJoin LineJoinKind { get; set; }
public double HalfWidth { get; set; }
/// <summary>
/// a limit on the ratio of the miter length to the stroke-width
/// </summary>
public int MitterLimit
{
get => _mitterLimit;
set => _mitterLimit = (value < 1) ? 1 : value;
}
/// <summary>
/// set input line (x0,y0)-> (x1,y1) and output line (x1,y1)-> (x2,y2)
/// </summary>
/// <param name="x0"></param>
/// <param name="y0"></param>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
public void SetControlVectors(double x0, double y0, double x1, double y1, double x2, double y2)
{
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void BuildJointVertex(
List<Vector> positiveSideVectors,
List<Vector> negativeSideVectors)
{
if (LineJoinKind == LineJoin.Bevel) return;
//--------------------------------------------------------------
Vector2 v0v1 = new Vector2(x1 - x0, y1 - y0);
Vector2 v1v2 = new Vector2(x2 - x1, y2 - y1);
Vector2 delta_v0v1 = v0v1.RotateInDegree(90).NewLength(HalfWidth);
Vector2 delta_v1v2 = v1v2.RotateInDegree(90).NewLength(HalfWidth);
double rad_v0v1 = Math.Atan2(v0v1.y, v0v1.x);
double rad_v1v2 = Math.Atan2(v1v2.y, v1v2.x);
double angle_rad_diff = rad_v1v2 - rad_v0v1;
if (positiveSideVectors != null)
{
Vector2 vec_a = new Vector2(x0 + delta_v0v1.x, y0 + delta_v0v1.y);
Vector2 vec_b = new Vector2(x1 + delta_v0v1.x, y1 + delta_v0v1.y);
Vector2 vec_c = new Vector2(x1 + delta_v1v2.x, y1 + delta_v1v2.y);
Vector2 vec_d = new Vector2(x2 + delta_v1v2.x, y2 + delta_v1v2.y);
Vector2 cutPoint;
if (MyMath.FindCutPoint(
vec_a, vec_b, //a->b
vec_c, vec_d, //b->c
out cutPoint))
{
if (angle_rad_diff > 0)
{
//'ACUTE' angle side, 'INNER' join
//------------
//inner join
//v0v1 => v1v2 is inner angle for positive side
//and is outter angle of negative side
//inside joint share the same cutpoint
positiveSideVectors.Add(new Vector(cutPoint.x, cutPoint.y));
}
else if (angle_rad_diff < 0)
{
//'OBTUSE' angle side,'OUTTER' join
//-------------------
switch (LineJoinKind)
{
default: throw new NotSupportedException();
case LineJoin.Round:
ArcGenerator.GenerateArcNew(positiveSideVectors,
x1, y1,
delta_v0v1,
angle_rad_diff);
break;
case LineJoin.Miter:
{
//check mitter limit
double cal_mitterLen = HalfWidth / Math.Sin((Math.PI - angle_rad_diff) / 2);
double half_mitterLen = HalfWidth * MitterLimit;
if (cal_mitterLen > half_mitterLen)
{
Vector2 mid_bc = (vec_b + vec_c) / 2;
Vector2 vec_bc = vec_c - vec_b;
Vector2 limit_delta = vec_bc.RotateInDegree(90).NewLength(half_mitterLen);
Vector2 mid_bc_n = mid_bc + limit_delta;
Vector2 lim_cutPoint;
if (MyMath.FindCutPoint(
vec_a, vec_b, //a->b
mid_bc_n, mid_bc_n + vec_bc, //b->c
out lim_cutPoint))
{
positiveSideVectors.Add(new Vector(lim_cutPoint.x, lim_cutPoint.y));
}
else
{
}
if (MyMath.FindCutPoint(
vec_c, vec_d, //a->b
mid_bc_n, mid_bc_n + vec_bc, //b->c
out lim_cutPoint))
{
positiveSideVectors.Add(new Vector(lim_cutPoint.x, lim_cutPoint.y));
}
else
{
}
}
else
{
positiveSideVectors.Add(new Vector(cutPoint.x, cutPoint.y));
}
}
break;
}
}
else
{
//angle =0 , same line
}
}
else
{
//the 2 not cut
}
}
//----------------------------------------------------------------
if (negativeSideVectors != null)
{
delta_v0v1 = -delta_v0v1; //change vector direction***
delta_v1v2 = -delta_v1v2; //change vector direction***
Vector2 vec_a = new Vector2(x0 + delta_v0v1.x, y0 + delta_v0v1.y);
Vector2 vec_b = new Vector2(x1 + delta_v0v1.x, y1 + delta_v0v1.y);
Vector2 vec_c = new Vector2(x1 + delta_v1v2.x, y1 + delta_v1v2.y);
Vector2 vec_d = new Vector2(x2 + delta_v1v2.x, y2 + delta_v1v2.y);
//-------------
Vector2 cutPoint;
if (MyMath.FindCutPoint(
vec_a, vec_b, //a->b
vec_c, vec_d, //b->c
out cutPoint))
{
if (angle_rad_diff > 0)
{
//'ACUTE' angle side
//for negative side, this is outter join
//-------------------
switch (LineJoinKind)
{
case LineJoin.Round:
ArcGenerator.GenerateArcNew(negativeSideVectors,
x1, y1,
delta_v0v1,
angle_rad_diff);
break;
case LineJoin.Miter:
{
//see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
double cal_mitterLen = HalfWidth / Math.Sin((Math.PI - angle_rad_diff) / 2);
double half_mitterLen = HalfWidth * MitterLimit;
if (cal_mitterLen > half_mitterLen)
{
Vector2 mid_bc = (vec_b + vec_c) / 2;
Vector2 vec_bc = vec_c - vec_b;
Vector2 limit_delta = vec_bc.RotateInDegree(-90).NewLength(half_mitterLen);
Vector2 mid_bc_n = mid_bc + limit_delta;
Vector2 lim_cutPoint;
if (MyMath.FindCutPoint(
vec_a, vec_b, //a->b
mid_bc_n, mid_bc_n + vec_bc, //b->c
out lim_cutPoint))
{
negativeSideVectors.Add(new Vector(lim_cutPoint.x, lim_cutPoint.y));
}
else
{
}
if (MyMath.FindCutPoint(
vec_c, vec_d, //a->b
mid_bc_n, mid_bc_n + vec_bc, //b->c
out lim_cutPoint))
{
negativeSideVectors.Add(new Vector(lim_cutPoint.x, lim_cutPoint.y));
}
else
{
}
}
else
{
negativeSideVectors.Add(new Vector(cutPoint.x, cutPoint.y));
}
}
break;
}
}
else if (angle_rad_diff < 0)
{
//'OBTUSE' angle side
//------------
//for negative side, this is outter join
//inner join share the same cutpoint
negativeSideVectors.Add(new Vector(cutPoint.x, cutPoint.y));
}
else
{
}
}
else
{
//the 2 not cut
}
}
}
}
class LineStrokeGenerator
{
LineJoiner _lineJoiner;
double _latest_moveto_x;
double _latest_moveto_y;
double _positiveSide;
//line core (x0,y0) -> (x1,y1) -> (x2,y2)
double _x0, _y0, _x1, _y1;
Vector _delta0, _delta1;
Vector _e1_positive;
Vector _e1_negative;
Vector _line_vector; //latest line vector
int _coordCount = 0;
double _first_lineto_x, _first_lineto_y;
public LineStrokeGenerator()
{
_lineJoiner = new LineJoiner();
_lineJoiner.LineJoinKind = LineJoin.Bevel;
}
public double HalfStrokWidth
{
get => _positiveSide;
set => _positiveSide = _lineJoiner.HalfWidth = value;
}
public LineJoin JoinKind
{
get => _lineJoiner.LineJoinKind;
set => _lineJoiner.LineJoinKind = value;
}
void AcceptLatest()
{
//TODO: rename this method
_x0 = _x1;
_y0 = _y1;
}
public void MoveTo(double x0, double y0)
{
//reset data
_coordCount = 0;
_latest_moveto_x = x0;
_latest_moveto_y = y0;
_x0 = x0;
_y0 = y0;
}
public void LineTo(double x1, double y1,
List<Vector> outputPositiveSideList,
List<Vector> outputNegativeSideList)
{
double ex0, ey0, ex0_n, ey0_n;
if (_coordCount > 0)
{
CreateLineJoin(x1, y1, outputPositiveSideList, outputNegativeSideList);
AcceptLatest();
ExactLineTo(x1, y1);
//--------------------------------------------------
//consider create joint here
GetEdge0(out ex0, out ey0, out ex0_n, out ey0_n);
//add to vectors
outputPositiveSideList.Add(new Vector(ex0, ey0));
outputPositiveSideList.Add(_e1_positive);
//
outputNegativeSideList.Add(new Vector(ex0_n, ey0_n));
outputNegativeSideList.Add(_e1_negative);
}
else
{
ExactLineTo(_first_lineto_x = x1, _first_lineto_y = y1);
GetEdge0(out ex0, out ey0, out ex0_n, out ey0_n);
//add to vectors
outputPositiveSideList.Add(new Vector(ex0, ey0));
outputNegativeSideList.Add(new Vector(ex0_n, ey0_n));
}
}
public void Close(
List<Vector> outputPositiveSideList,
List<Vector> outputNegativeSideList)
{
double ex0, ey0, ex0_n, ey0_n;
CreateLineJoin(_latest_moveto_x, _latest_moveto_y, outputPositiveSideList, outputNegativeSideList);
//
ExactLineTo(_latest_moveto_x, _latest_moveto_y);
if (_coordCount > 1)
{
//consider create joint here
GetEdge0(out ex0, out ey0, out ex0_n, out ey0_n);
//add to vectors
outputPositiveSideList.Add(new Vector(ex0, ey0));
outputPositiveSideList.Add(_e1_positive);
//
outputNegativeSideList.Add(new Vector(ex0_n, ey0_n));
outputNegativeSideList.Add(_e1_negative);
}
else
{
GetEdge0(out ex0, out ey0, out ex0_n, out ey0_n);
//add to vectors
outputPositiveSideList.Add(new Vector(ex0, ey0));
outputPositiveSideList.Add(_e1_positive);
//
outputNegativeSideList.Add(new Vector(ex0_n, ey0_n));
outputNegativeSideList.Add(_e1_negative);
}
//------------------------------------------
CreateLineJoin(_first_lineto_x, _first_lineto_y, outputPositiveSideList, outputNegativeSideList);
AcceptLatest();
//------------------------------------------
}
void GetEdge0(out double ex0, out double ey0, out double ex0_n, out double ey0_n)
{
ex0 = _x0 + _delta0.X;
ey0 = _y0 + _delta0.Y;
ex0_n = _x0 - _delta0.X;
ey0_n = _y0 - _delta0.Y;
}
void ExactLineTo(double x1, double y1)
{
//perpendicular line
//create line vector
_line_vector = _delta0 = new Vector(x1 - _x0, y1 - _y0);
_delta1 = _delta0 = _delta0.Rotate(90).NewLength(_positiveSide);
_x1 = x1;
_y1 = y1;
//------------------------------------------------------
_e1_positive = new Vector(x1 + _delta1.X, y1 + _delta1.Y);
_e1_negative = new Vector(x1 - _delta1.X, y1 - _delta1.Y);
//------------------------------------------------------
//create both positive and negative edge
_coordCount++;
}
void CreateLineJoin(
double previewX1,
double previewY1,
List<Vector> outputPositiveSideList,
List<Vector> outputNegativeSideList)
{
if (_lineJoiner.LineJoinKind == LineJoin.Bevel)
{
Vector p = new Vector(_x1, _y1);
outputPositiveSideList.Add(p + _delta0);
outputNegativeSideList.Add(p - _delta0);
return;
}
//------------------------------------------
_lineJoiner.SetControlVectors(_x0, _y0, _x1, _y1, previewX1, previewY1);
_lineJoiner.BuildJointVertex(outputPositiveSideList, outputNegativeSideList);
//------------------------------------------
}
}
public class StrokeGen2
{
//UNDER CONSTRUCTION **
LineStrokeGenerator _lineGen = new LineStrokeGenerator();
List<Vector> _positiveSideVectors = new List<Vector>();
List<Vector> _negativeSideVectors = new List<Vector>();
List<Vector> _capVectors = new List<Vector>(); //temporary
public StrokeGen2()
{
this.LineCapStyle = LineCap.Square;
this.StrokeWidth = 1;
}
public LineCap LineCapStyle { get; set; }
public LineJoin LineJoinStyle
{
get => _lineGen.JoinKind;
set => _lineGen.JoinKind = value;
}
public double StrokeWidth
{
get => _lineGen.HalfStrokWidth * 2;
set => _lineGen.HalfStrokWidth = value / 2;
}
public double HalfStrokeWidth
{
get => _lineGen.HalfStrokWidth;
set => _lineGen.HalfStrokWidth = value;
}
public void Generate(VertexStore srcVxs, VertexStore outputVxs)
{
//read data from src
//generate stroke and
//write to output
//-----------
int cmdCount = srcVxs.Count;
VertexCmd cmd;
double x, y;
_positiveSideVectors.Clear();
_negativeSideVectors.Clear();
bool has_some_results = false;
for (int i = 0; i < cmdCount; ++i)
{
cmd = srcVxs.GetVertex(i, out x, out y);
switch (cmd)
{
case VertexCmd.LineTo:
_lineGen.LineTo(x, y, _positiveSideVectors, _negativeSideVectors);
has_some_results = true;
break;
case VertexCmd.MoveTo:
//if we have current shape
//leave it and start the new shape
_lineGen.MoveTo(x, y);
break;
case VertexCmd.Close:
_lineGen.Close(_positiveSideVectors, _negativeSideVectors);
WriteOutput(outputVxs, true);
has_some_results = false;
break;
default:
break;
}
}
//-------------
if (has_some_results)
{
WriteOutput(outputVxs, false);
}
}
void WriteOutput(VertexStore outputVxs, bool close)
{
//write output to
if (close)
{
int positive_edgeCount = _positiveSideVectors.Count;
int negative_edgeCount = _negativeSideVectors.Count;
int n = positive_edgeCount - 1;
Vector v = _positiveSideVectors[n];
outputVxs.AddMoveTo(v.X, v.Y);
for (; n >= 0; --n)
{
v = _positiveSideVectors[n];
outputVxs.AddLineTo(v.X, v.Y);
}
outputVxs.AddCloseFigure();
//end ... create join to negative side
//------------------------------------------
//create line join from positive to negative side
v = _negativeSideVectors[0];
outputVxs.AddMoveTo(v.X, v.Y);
n = 1;
for (; n < negative_edgeCount; ++n)
{
v = _negativeSideVectors[n];
outputVxs.AddLineTo(v.X, v.Y);
}
//------------------------------------------
//close
outputVxs.AddCloseFigure();
}
else
{
int positive_edgeCount = _positiveSideVectors.Count;
int negative_edgeCount = _negativeSideVectors.Count;
//no a close shape stroke
//create line cap for this
//
//positive
Vector v = _positiveSideVectors[0];
//-----------
//1. moveto
//2.
CreateStartLineCap(outputVxs,
v,
_negativeSideVectors[0], this.HalfStrokeWidth);
//-----------
int n = 1;
for (; n < positive_edgeCount; ++n)
{
//increment n
v = _positiveSideVectors[n];
outputVxs.AddLineTo(v.X, v.Y);
}
//negative
//----------------------------------
CreateEndLineCap(outputVxs,
_positiveSideVectors[positive_edgeCount - 1],
_negativeSideVectors[negative_edgeCount - 1],
this.HalfStrokeWidth);
//----------------------------------
for (n = negative_edgeCount - 2; n >= 0; --n)
{
//decrement n
v = _negativeSideVectors[n];
outputVxs.AddLineTo(v.X, v.Y);
}
outputVxs.AddCloseFigure();
}
//reset
_positiveSideVectors.Clear();
_negativeSideVectors.Clear();
}
void CreateStartLineCap(VertexStore outputVxs, Vector v0, Vector v1, double edgeWidth)
{
switch (this.LineCapStyle)
{
default: throw new NotSupportedException();
case LineCap.Butt:
outputVxs.AddMoveTo(v1.X, v1.Y);// moveto
outputVxs.AddLineTo(v0.X, v0.Y);
break;
case LineCap.Square:
{
Vector delta = (v0 - v1).Rotate(90).NewLength(edgeWidth);
//------------------------
outputVxs.AddMoveTo(v1.X + delta.X, v1.Y + delta.Y);
outputVxs.AddLineTo(v0.X + delta.X, v0.Y + delta.Y);
}
break;
case LineCap.Round:
_capVectors.Clear();
BuildBeginCap(v0.X, v0.Y, v1.X, v1.Y, _capVectors);
//----------------------------------------------------
int j = _capVectors.Count;
outputVxs.AddMoveTo(v1.X, v1.Y);
for (int i = j - 1; i >= 0; --i)
{
Vector v = _capVectors[i];
outputVxs.AddLineTo(v.X, v.Y);
}
break;
}
}
void CreateEndLineCap(VertexStore outputVxs, Vector v0, Vector v1, double edgeWidth)
{
switch (this.LineCapStyle)
{
default: throw new NotSupportedException();
case LineCap.Butt:
outputVxs.AddLineTo(v0.X, v0.Y);
outputVxs.AddLineTo(v1.X, v1.Y);
break;
case LineCap.Square:
{
Vector delta = (v1 - v0).Rotate(90).NewLength(edgeWidth);
outputVxs.AddLineTo(v0.X + delta.X, v0.Y + delta.Y);
outputVxs.AddLineTo(v1.X + delta.X, v1.Y + delta.Y);
}
break;
case LineCap.Round:
{
_capVectors.Clear();
BuildEndCap(v0.X, v0.Y, v1.X, v1.Y, _capVectors);
int j = _capVectors.Count;
for (int i = j - 1; i >= 0; --i)
{
Vector v = _capVectors[i];
outputVxs.AddLineTo(v.X, v.Y);
}
}
break;
}
}
void BuildBeginCap(
double x0, double y0,
double x1, double y1,
List<Vector> outputVectors)
{
switch (LineCapStyle)
{
default: throw new NotSupportedException();
case LineCap.Butt:
break;
case LineCap.Square:
break;
case LineCap.Round:
{
//------------------------
//x0,y0 -> begin of line 1
//x1,y1 -> begin of line 2
//------------------------
double c_x = (x0 + x1) / 2;
double c_y = (y0 + y1) / 2;
Vector2 delta = new Vector2(x0 - c_x, y0 - c_y);
ArcGenerator.GenerateArcNew(outputVectors,
c_x, c_y, delta, AggMath.deg2rad(180));
}
break;
}
}
void BuildEndCap(
double x0, double y0,
double x1, double y1,
List<Vector> outputVectors)
{
switch (LineCapStyle)
{
default: throw new NotSupportedException();
case LineCap.Butt:
break;
case LineCap.Square:
break;
case LineCap.Round:
{
//------------------------
//x0,y0 -> end of line 1
//x1,y1 -> end of line 2
//------------------------
double c_x = (x0 + x1) / 2;
double c_y = (y0 + y1) / 2;
Vector2 delta = new Vector2(x1 - c_x, y1 - c_y);
ArcGenerator.GenerateArcNew(outputVectors,
c_x, c_y, delta, AggMath.deg2rad(180));
}
break;
}
}
}
static class ArcGenerator
{
//helper class for generate arc
//
public static void GenerateArcNew(List<Vector> output, double cx,
double cy,
Vector2 startDelta,
double sweepAngleRad)
{
//TODO: review here ***
int nsteps = 4;
double eachStep = AggMath.rad2deg(sweepAngleRad) / nsteps;
double angle = 0;
for (int i = 0; i < nsteps; ++i)
{
Vector2 newPerpend = startDelta.RotateInDegree(angle);
Vector2 newpos = new Vector2(cx + newPerpend.x, cy + newPerpend.y);
output.Add(new Vector(newpos.x, newpos.y));
angle += eachStep;
}
}
}
}
| |
/* ====================================================================
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.IO;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
namespace NPOI.POIFS.Crypt
{
using System;
using System.Reflection;
public class EncryptionInfo
{
/**
* A flag that specifies whether CryptoAPI RC4 or ECMA-376 encryption
* ECMA-376 is used. It MUST be 1 unless flagExternal is 1. If flagExternal is 1, it MUST be 0.
*/
public static BitField flagCryptoAPI = BitFieldFactory.GetInstance(0x04);
/**
* A value that MUST be 0 if document properties are encrypted.
* The encryption of document properties is specified in section 2.3.5.4.
*/
public static BitField flagDocProps = BitFieldFactory.GetInstance(0x08);
/**
* A value that MUST be 1 if extensible encryption is used. If this value is 1,
* the value of every other field in this structure MUST be 0.
*/
public static BitField flagExternal = BitFieldFactory.GetInstance(0x10);
/**
* A value that MUST be 1 if the protected content is an ECMA-376 document
* ECMA-376. If the fAES bit is 1, the fCryptoAPI bit MUST also be 1.
*/
public static BitField flagAES = BitFieldFactory.GetInstance(0x20);
/**
* Opens for decryption
*/
public EncryptionInfo(POIFSFileSystem fs)
: this(fs.Root)
{
}
/**
* Opens for decryption
*/
public EncryptionInfo(OPOIFSFileSystem fs)
: this(fs.Root)
{
}
/**
* Opens for decryption
*/
public EncryptionInfo(NPOIFSFileSystem fs) : this(fs.Root)
{
}
/**
* Opens for decryption
*/
public EncryptionInfo(DirectoryNode dir)
: this(dir.CreateDocumentInputStream("EncryptionInfo"), false)
{
}
public EncryptionInfo(ILittleEndianInput dis, bool isCryptoAPI)
{
EncryptionMode encryptionMode;
VersionMajor = dis.ReadShort();
VersionMinor = dis.ReadShort();
if (!isCryptoAPI
&& VersionMajor == EncryptionMode.BinaryRC4.VersionMajor
&& VersionMinor == EncryptionMode.BinaryRC4.VersionMinor)
{
encryptionMode = EncryptionMode.BinaryRC4;
EncryptionFlags = -1;
}
else if (!isCryptoAPI
&& VersionMajor == EncryptionMode.Agile.VersionMajor
&& VersionMinor == EncryptionMode.Agile.VersionMinor)
{
encryptionMode = EncryptionMode.Agile;
EncryptionFlags = dis.ReadInt();
}
else if (!isCryptoAPI
&& 2 <= VersionMajor && VersionMajor <= 4
&& VersionMinor == EncryptionMode.Standard.VersionMinor)
{
encryptionMode = EncryptionMode.Standard;
EncryptionFlags = dis.ReadInt();
}
else if (isCryptoAPI
&& 2 <= VersionMajor && VersionMajor <= 4
&& VersionMinor == EncryptionMode.CryptoAPI.VersionMinor)
{
encryptionMode = EncryptionMode.CryptoAPI;
EncryptionFlags = dis.ReadInt();
}
else
{
EncryptionFlags = dis.ReadInt();
throw new EncryptedDocumentException(
"Unknown encryption: version major: " + VersionMajor +
" / version minor: " + VersionMinor +
" / fCrypto: " + flagCryptoAPI.IsSet(EncryptionFlags) +
" / fExternal: " + flagExternal.IsSet(EncryptionFlags) +
" / fDocProps: " + flagDocProps.IsSet(EncryptionFlags) +
" / fAES: " + flagAES.IsSet(EncryptionFlags));
}
IEncryptionInfoBuilder eib;
try
{
eib = GetBuilder(encryptionMode);
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
eib.Initialize(this, dis);
Header = eib.GetHeader();
Verifier = eib.GetVerifier();
Decryptor = eib.GetDecryptor();
Encryptor = eib.GetEncryptor();
}
/**
* @deprecated Use {@link #EncryptionInfo(EncryptionMode)} (fs parameter no longer required)
*/
public EncryptionInfo(POIFSFileSystem fs, EncryptionMode encryptionMode)
: this(encryptionMode)
{
;
}
/**
* @deprecated Use {@link #EncryptionInfo(EncryptionMode)} (fs parameter no longer required)
*/
public EncryptionInfo(NPOIFSFileSystem fs, EncryptionMode encryptionMode)
: this(encryptionMode)
{
;
}
/**
* @deprecated Use {@link #EncryptionInfo(EncryptionMode)} (dir parameter no longer required)
*/
public EncryptionInfo(DirectoryNode dir, EncryptionMode encryptionMode)
: this(encryptionMode)
{
;
}
/**
* @deprecated use {@link #EncryptionInfo(EncryptionMode, CipherAlgorithm, HashAlgorithm, int, int, ChainingMode)}
*/
public EncryptionInfo(
POIFSFileSystem fs
, EncryptionMode encryptionMode
, CipherAlgorithm cipherAlgorithm
, HashAlgorithm hashAlgorithm
, int keyBits
, int blockSize
, ChainingMode chainingMode
)
: this(encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode)
{
;
}
/**
* @deprecated use {@link #EncryptionInfo(EncryptionMode, CipherAlgorithm, HashAlgorithm, int, int, ChainingMode)}
*/
public EncryptionInfo(
NPOIFSFileSystem fs
, EncryptionMode encryptionMode
, CipherAlgorithm cipherAlgorithm
, HashAlgorithm hashAlgorithm
, int keyBits
, int blockSize
, ChainingMode chainingMode
)
: this(encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode)
{
;
}
/**
* @deprecated use {@link #EncryptionInfo(EncryptionMode, CipherAlgorithm, HashAlgorithm, int, int, ChainingMode)}
*/
public EncryptionInfo(
DirectoryNode dir
, EncryptionMode encryptionMode
, CipherAlgorithm cipherAlgorithm
, HashAlgorithm hashAlgorithm
, int keyBits
, int blockSize
, ChainingMode chainingMode
)
: this(encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode)
{
;
}
/**
* Prepares for encryption, using the given Encryption Mode, and
* all other parameters as default.
* @see #EncryptionInfo(EncryptionMode, CipherAlgorithm, HashAlgorithm, int, int, ChainingMode)
*/
public EncryptionInfo(EncryptionMode encryptionMode)
: this(encryptionMode, null, null, -1, -1, null)
{
}
/**
* Constructs an EncryptionInfo from scratch
*
* @param encryptionMode see {@link EncryptionMode} for values, {@link EncryptionMode#cryptoAPI} is for
* internal use only, as it's record based
* @param cipherAlgorithm
* @param hashAlgorithm
* @param keyBits
* @param blockSize
* @param chainingMode
*
* @throws EncryptedDocumentException if the given parameters mismatch, e.g. only certain combinations
* of keyBits, blockSize are allowed for a given {@link CipherAlgorithm}
*/
public EncryptionInfo(
EncryptionMode encryptionMode
, CipherAlgorithm cipherAlgorithm
, HashAlgorithm hashAlgorithm
, int keyBits
, int blockSize
, ChainingMode chainingMode
)
{
VersionMajor = encryptionMode.VersionMajor;
VersionMinor = encryptionMode.VersionMinor;
EncryptionFlags = encryptionMode.EncryptionFlags;
IEncryptionInfoBuilder eib;
try
{
eib = GetBuilder(encryptionMode);
}
catch (Exception e)
{
throw new EncryptedDocumentException(e);
}
eib.Initialize(this, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
Header = eib.GetHeader();
Verifier = eib.GetVerifier();
Decryptor = eib.GetDecryptor();
Encryptor = eib.GetEncryptor();
}
protected static IEncryptionInfoBuilder GetBuilder(EncryptionMode encryptionMode)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Type t = null;
foreach (Assembly assembly in assemblies)
{
t = assembly.GetType(encryptionMode.Builder);
if (t != null)
break;
}
if (t == null)
{
throw new EncryptedDocumentException("Not found type " + encryptionMode.Builder);
}
IEncryptionInfoBuilder eib = null;
eib = (IEncryptionInfoBuilder)t.Assembly.CreateInstance(encryptionMode.Builder);
return eib;
}
public int VersionMajor { get; }
public int VersionMinor { get; }
public int EncryptionFlags { get; }
public EncryptionHeader Header { get; }
public EncryptionVerifier Verifier { get; }
public Decryptor Decryptor { get; }
public Encryptor Encryptor { get; }
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.Cil;
namespace Mono.Cecil.Rocks {
#if INSIDE_ROCKS
public
#endif
static class MethodBodyRocks {
public static void SimplifyMacros (this MethodBody self)
{
if (self == null)
throw new ArgumentNullException ("self");
foreach (var instruction in self.Instructions) {
if (instruction.OpCode.OpCodeType != OpCodeType.Macro)
continue;
switch (instruction.OpCode.Code) {
case Code.Ldarg_0:
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (0));
break;
case Code.Ldarg_1:
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (1));
break;
case Code.Ldarg_2:
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (2));
break;
case Code.Ldarg_3:
ExpandMacro (instruction, OpCodes.Ldarg, self.GetParameter (3));
break;
case Code.Ldloc_0:
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [0]);
break;
case Code.Ldloc_1:
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [1]);
break;
case Code.Ldloc_2:
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [2]);
break;
case Code.Ldloc_3:
ExpandMacro (instruction, OpCodes.Ldloc, self.Variables [3]);
break;
case Code.Stloc_0:
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [0]);
break;
case Code.Stloc_1:
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [1]);
break;
case Code.Stloc_2:
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [2]);
break;
case Code.Stloc_3:
ExpandMacro (instruction, OpCodes.Stloc, self.Variables [3]);
break;
case Code.Ldarg_S:
instruction.OpCode = OpCodes.Ldarg;
break;
case Code.Ldarga_S:
instruction.OpCode = OpCodes.Ldarga;
break;
case Code.Starg_S:
instruction.OpCode = OpCodes.Starg;
break;
case Code.Ldloc_S:
instruction.OpCode = OpCodes.Ldloc;
break;
case Code.Ldloca_S:
instruction.OpCode = OpCodes.Ldloca;
break;
case Code.Stloc_S:
instruction.OpCode = OpCodes.Stloc;
break;
case Code.Ldc_I4_M1:
ExpandMacro (instruction, OpCodes.Ldc_I4, -1);
break;
case Code.Ldc_I4_0:
ExpandMacro (instruction, OpCodes.Ldc_I4, 0);
break;
case Code.Ldc_I4_1:
ExpandMacro (instruction, OpCodes.Ldc_I4, 1);
break;
case Code.Ldc_I4_2:
ExpandMacro (instruction, OpCodes.Ldc_I4, 2);
break;
case Code.Ldc_I4_3:
ExpandMacro (instruction, OpCodes.Ldc_I4, 3);
break;
case Code.Ldc_I4_4:
ExpandMacro (instruction, OpCodes.Ldc_I4, 4);
break;
case Code.Ldc_I4_5:
ExpandMacro (instruction, OpCodes.Ldc_I4, 5);
break;
case Code.Ldc_I4_6:
ExpandMacro (instruction, OpCodes.Ldc_I4, 6);
break;
case Code.Ldc_I4_7:
ExpandMacro (instruction, OpCodes.Ldc_I4, 7);
break;
case Code.Ldc_I4_8:
ExpandMacro (instruction, OpCodes.Ldc_I4, 8);
break;
case Code.Ldc_I4_S:
ExpandMacro (instruction, OpCodes.Ldc_I4, (int) (sbyte) instruction.Operand);
break;
case Code.Br_S:
instruction.OpCode = OpCodes.Br;
break;
case Code.Brfalse_S:
instruction.OpCode = OpCodes.Brfalse;
break;
case Code.Brtrue_S:
instruction.OpCode = OpCodes.Brtrue;
break;
case Code.Beq_S:
instruction.OpCode = OpCodes.Beq;
break;
case Code.Bge_S:
instruction.OpCode = OpCodes.Bge;
break;
case Code.Bgt_S:
instruction.OpCode = OpCodes.Bgt;
break;
case Code.Ble_S:
instruction.OpCode = OpCodes.Ble;
break;
case Code.Blt_S:
instruction.OpCode = OpCodes.Blt;
break;
case Code.Bne_Un_S:
instruction.OpCode = OpCodes.Bne_Un;
break;
case Code.Bge_Un_S:
instruction.OpCode = OpCodes.Bge_Un;
break;
case Code.Bgt_Un_S:
instruction.OpCode = OpCodes.Bgt_Un;
break;
case Code.Ble_Un_S:
instruction.OpCode = OpCodes.Ble_Un;
break;
case Code.Blt_Un_S:
instruction.OpCode = OpCodes.Blt_Un;
break;
case Code.Leave_S:
instruction.OpCode = OpCodes.Leave;
break;
}
}
}
static void ExpandMacro (Instruction instruction, OpCode opcode, object operand)
{
instruction.OpCode = opcode;
instruction.Operand = operand;
}
static void MakeMacro (Instruction instruction, OpCode opcode)
{
instruction.OpCode = opcode;
instruction.Operand = null;
}
public static void Optimize (this MethodBody self)
{
if (self == null)
throw new ArgumentNullException ("self");
OptimizeLongs (self);
OptimizeMacros (self);
}
static void OptimizeLongs (this MethodBody self)
{
for (var i = 0; i < self.Instructions.Count; i++) {
var instruction = self.Instructions [i];
if (instruction.OpCode.Code != Code.Ldc_I8)
continue;
var l = (long) instruction.Operand;
if (l >= int.MaxValue || l <= int.MinValue)
continue;
ExpandMacro (instruction, OpCodes.Ldc_I4, (int) l);
self.Instructions.Insert (++i, Instruction.Create (OpCodes.Conv_I8));
}
}
public static void OptimizeMacros (this MethodBody self)
{
if (self == null)
throw new ArgumentNullException ("self");
var method = self.Method;
foreach (var instruction in self.Instructions) {
int index;
switch (instruction.OpCode.Code) {
case Code.Ldarg:
index = ((ParameterDefinition) instruction.Operand).Index;
if (index == -1 && instruction.Operand == self.ThisParameter)
index = 0;
else if (method.HasThis)
index++;
switch (index) {
case 0:
MakeMacro (instruction, OpCodes.Ldarg_0);
break;
case 1:
MakeMacro (instruction, OpCodes.Ldarg_1);
break;
case 2:
MakeMacro (instruction, OpCodes.Ldarg_2);
break;
case 3:
MakeMacro (instruction, OpCodes.Ldarg_3);
break;
default:
if (index < 256)
ExpandMacro (instruction, OpCodes.Ldarg_S, instruction.Operand);
break;
}
break;
case Code.Ldloc:
index = ((VariableDefinition) instruction.Operand).Index;
switch (index) {
case 0:
MakeMacro (instruction, OpCodes.Ldloc_0);
break;
case 1:
MakeMacro (instruction, OpCodes.Ldloc_1);
break;
case 2:
MakeMacro (instruction, OpCodes.Ldloc_2);
break;
case 3:
MakeMacro (instruction, OpCodes.Ldloc_3);
break;
default:
if (index < 256)
ExpandMacro (instruction, OpCodes.Ldloc_S, instruction.Operand);
break;
}
break;
case Code.Stloc:
index = ((VariableDefinition) instruction.Operand).Index;
switch (index) {
case 0:
MakeMacro (instruction, OpCodes.Stloc_0);
break;
case 1:
MakeMacro (instruction, OpCodes.Stloc_1);
break;
case 2:
MakeMacro (instruction, OpCodes.Stloc_2);
break;
case 3:
MakeMacro (instruction, OpCodes.Stloc_3);
break;
default:
if (index < 256)
ExpandMacro (instruction, OpCodes.Stloc_S, instruction.Operand);
break;
}
break;
case Code.Ldarga:
index = ((ParameterDefinition) instruction.Operand).Index;
if (index == -1 && instruction.Operand == self.ThisParameter)
index = 0;
else if (method.HasThis)
index++;
if (index < 256)
ExpandMacro (instruction, OpCodes.Ldarga_S, instruction.Operand);
break;
case Code.Ldloca:
if (((VariableDefinition) instruction.Operand).Index < 256)
ExpandMacro (instruction, OpCodes.Ldloca_S, instruction.Operand);
break;
case Code.Ldc_I4:
int i = (int) instruction.Operand;
switch (i) {
case -1:
MakeMacro (instruction, OpCodes.Ldc_I4_M1);
break;
case 0:
MakeMacro (instruction, OpCodes.Ldc_I4_0);
break;
case 1:
MakeMacro (instruction, OpCodes.Ldc_I4_1);
break;
case 2:
MakeMacro (instruction, OpCodes.Ldc_I4_2);
break;
case 3:
MakeMacro (instruction, OpCodes.Ldc_I4_3);
break;
case 4:
MakeMacro (instruction, OpCodes.Ldc_I4_4);
break;
case 5:
MakeMacro (instruction, OpCodes.Ldc_I4_5);
break;
case 6:
MakeMacro (instruction, OpCodes.Ldc_I4_6);
break;
case 7:
MakeMacro (instruction, OpCodes.Ldc_I4_7);
break;
case 8:
MakeMacro (instruction, OpCodes.Ldc_I4_8);
break;
default:
if (i >= -128 && i < 128)
ExpandMacro (instruction, OpCodes.Ldc_I4_S, (sbyte) i);
break;
}
break;
}
}
OptimizeBranches (self);
}
static void OptimizeBranches (MethodBody body)
{
ComputeOffsets (body);
foreach (var instruction in body.Instructions) {
if (instruction.OpCode.OperandType != OperandType.InlineBrTarget)
continue;
if (OptimizeBranch (instruction))
ComputeOffsets (body);
}
}
static bool OptimizeBranch (Instruction instruction)
{
var offset = ((Instruction) instruction.Operand).Offset - (instruction.Offset + instruction.OpCode.Size + 4);
if (!(offset >= -128 && offset <= 127))
return false;
switch (instruction.OpCode.Code) {
case Code.Br:
instruction.OpCode = OpCodes.Br_S;
break;
case Code.Brfalse:
instruction.OpCode = OpCodes.Brfalse_S;
break;
case Code.Brtrue:
instruction.OpCode = OpCodes.Brtrue_S;
break;
case Code.Beq:
instruction.OpCode = OpCodes.Beq_S;
break;
case Code.Bge:
instruction.OpCode = OpCodes.Bge_S;
break;
case Code.Bgt:
instruction.OpCode = OpCodes.Bgt_S;
break;
case Code.Ble:
instruction.OpCode = OpCodes.Ble_S;
break;
case Code.Blt:
instruction.OpCode = OpCodes.Blt_S;
break;
case Code.Bne_Un:
instruction.OpCode = OpCodes.Bne_Un_S;
break;
case Code.Bge_Un:
instruction.OpCode = OpCodes.Bge_Un_S;
break;
case Code.Bgt_Un:
instruction.OpCode = OpCodes.Bgt_Un_S;
break;
case Code.Ble_Un:
instruction.OpCode = OpCodes.Ble_Un_S;
break;
case Code.Blt_Un:
instruction.OpCode = OpCodes.Blt_Un_S;
break;
case Code.Leave:
instruction.OpCode = OpCodes.Leave_S;
break;
}
return true;
}
static void ComputeOffsets (MethodBody body)
{
var offset = 0;
foreach (var instruction in body.Instructions) {
instruction.Offset = offset;
offset += instruction.GetSize ();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore.Collections;
using NetGore.IO;
namespace NetGore.Features.NPCChat
{
/// <summary>
/// Base class for managing the <see cref="NPCChatDialogBase"/>s.
/// </summary>
public abstract class NPCChatManagerBase : IEnumerable<NPCChatDialogBase>
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string _chatDialogsNodeName = "ChatDialogs";
const string _rootNodeName = "NPCChatManager";
readonly bool _isReadonly;
readonly DArray<NPCChatDialogBase> _npcChatDialogs = new DArray<NPCChatDialogBase>(32);
/// <summary>
/// Initializes a new instance of the <see cref="NPCChatManagerBase"/> class.
/// </summary>
/// <param name="isReadonly">If this manager is read-only.</param>
protected NPCChatManagerBase(bool isReadonly)
{
_isReadonly = isReadonly;
Load(ContentPaths.Build);
}
/// <summary>
/// Gets the <see cref="NPCChatDialogBase"/> at the specified index.
/// </summary>
/// <param name="id">Index of the <see cref="NPCChatDialogBase"/>.</param>
/// <returns>The <see cref="NPCChatDialogBase"/> at the specified index, or null if invalid.</returns>
/// <exception cref="MethodAccessException">Tried to set when <see cref="IsReadonly"/> was true.</exception>
public NPCChatDialogBase this[NPCChatDialogID id]
{
get
{
// Check for a valid index
if (!_npcChatDialogs.CanGet((int)id))
{
const string errmsg = "Invalid NPC chat dialog index `{0}`.";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, id);
Debug.Fail(string.Format(errmsg, id));
return null;
}
return _npcChatDialogs[(int)id];
}
set
{
if (IsReadonly)
throw CreateReadonlyException();
_npcChatDialogs[(int)id] = value;
}
}
/// <summary>
/// Gets or sets the <see cref="GenericValueIOFormat"/> to use for when an instance of this class
/// writes itself out to a new <see cref="GenericValueWriter"/>. If null, the format to use
/// will be inherited from <see cref="GenericValueWriter.DefaultFormat"/>.
/// Default value is null.
/// </summary>
public static GenericValueIOFormat? EncodingFormat { get; set; }
/// <summary>
/// Gets if this manager is read-only.
/// </summary>
public bool IsReadonly
{
get { return _isReadonly; }
}
/// <summary>
/// When overridden in the derived class, creates a <see cref="NPCChatDialogBase"/> from the given <see cref="IValueReader"/>.
/// </summary>
/// <param name="reader"><see cref="IValueReader"/> to read the values from.</param>
/// <returns>A <see cref="NPCChatDialogBase"/> created from the given <see cref="IValueReader"/>.</returns>
protected abstract NPCChatDialogBase CreateDialog(IValueReader reader);
/// <summary>
/// Creates a <see cref="MethodAccessException"/> to use for when trying to access a method that is cannot be access when read-only.
/// </summary>
/// <returns>A <see cref="MethodAccessException"/> to use for when trying to access a method that is cannot be
/// access when read-only.</returns>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "NPCChatManagerBase")]
protected static MethodAccessException CreateReadonlyException()
{
return new MethodAccessException("Cannot access this method when the NPCChatManagerBase is set to Read-Only.");
}
/// <summary>
/// Gets if a chat dialog exists at the given ID.
/// </summary>
/// <param name="id">The ID to check if contains a dialog.</param>
/// <returns>True if a dialog exists at the given <paramref name="id"/>; otherwise false.</returns>
public bool DialogExists(NPCChatDialogID id)
{
if (!_npcChatDialogs.CanGet((int)id))
return false;
return _npcChatDialogs[(int)id] != null;
}
/// <summary>
/// Gets the path for the data file.
/// </summary>
/// <param name="contentPath"><see cref="ContentPaths"/> to use.</param>
/// <returns>The path for the data file.</returns>
protected static string GetFilePath(ContentPaths contentPath)
{
return contentPath.Data.Join("npcchat" + EngineSettings.DataFileSuffix);
}
/// <summary>
/// Loads the data from file.
/// </summary>
/// <param name="contentPath">The content path to load the data from.</param>
void Load(ContentPaths contentPath)
{
_npcChatDialogs.Clear();
var filePath = GetFilePath(contentPath);
if (!File.Exists(filePath))
{
_npcChatDialogs.Trim();
return;
}
var reader = GenericValueReader.CreateFromFile(filePath, _rootNodeName);
var items = reader.ReadManyNodes(_chatDialogsNodeName, CreateDialog);
for (var i = 0; i < items.Length; i++)
{
if (items[i] != null)
_npcChatDialogs[i] = items[i];
}
_npcChatDialogs.Trim();
}
/// <summary>
/// Reorganizes the internal buffer to ensure the indices all match up. Only needed if IsReadonly is false
/// and you don't manually update the indices.
/// </summary>
public void Reorganize()
{
var dialogs = _npcChatDialogs.ToArray();
_npcChatDialogs.Clear();
foreach (var dialog in dialogs.Where(x => x != null))
{
_npcChatDialogs[(int)dialog.ID] = dialog;
}
}
/// <summary>
/// Saves the <see cref="NPCChatDialogBase"/>s in this <see cref="NPCChatManagerBase"/> to file.
/// </summary>
/// <param name="contentPath">The content path.</param>
public void Save(ContentPaths contentPath)
{
var dialogs = _npcChatDialogs.Where(x => x != null);
// Write
var filePath = GetFilePath(contentPath);
using (var writer = GenericValueWriter.Create(filePath, _rootNodeName, EncodingFormat))
{
writer.WriteManyNodes(_chatDialogsNodeName, dialogs, ((w, item) => item.Write(w)));
}
}
#region IEnumerable<NPCChatDialogBase> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<NPCChatDialogBase> GetEnumerator()
{
return ((IEnumerable<NPCChatDialogBase>)_npcChatDialogs).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEditor;
namespace TiltBrushToolkit {
[CustomEditor(typeof(Sequence))]
public class SequenceEditor : Editor {
Texture2D m_IconUp;
Texture2D m_IconDown;
Texture2D m_IconDelete;
Texture2D m_IconAdd;
public static bool FOLDOUT_DIRECTOR = false;
void OnEnable() {
m_IconUp = Resources.Load("UI/up") as Texture2D;
m_IconDown = Resources.Load("UI/down") as Texture2D;
m_IconDelete = Resources.Load("UI/delete") as Texture2D;
m_IconAdd = Resources.Load("UI/add") as Texture2D;
var t = (target as Sequence);
// Update source types
for(int i = 0; i < t.m_FrameSources.Count; i++) {
var f = t.m_FrameSources[i];
if (f.m_Source)
f.m_SourceType = SequenceUtils.GetAssetType(f.m_Source);
t.m_FrameSources[i] = f;
}
}
public override void OnInspectorGUI() {
Undo.RecordObject(target, "Add frames");
serializedObject.Update();
CustomLabel("Sequence", 16, FontStyle.Bold);
CustomLabel("Creates an animated sequence", 12, FontStyle.BoldAndItalic);
EditorGUILayout.Space();
GUIStyle gs;
var t = target as Sequence;
EditorGUI.BeginChangeCheck();
CustomLabel("Playback", 12, FontStyle.Italic, TextAnchor.MiddleRight);
t.m_PlaybackMode = (Sequence.PlaybackMode)EditorGUILayout.EnumPopup("Playback Mode", t.m_PlaybackMode);
if (t.m_PlaybackMode == Sequence.PlaybackMode.Constant) {
EditorGUI.indentLevel++;
t.m_ConstantFramesPerSecond = EditorGUILayout.FloatField(new GUIContent("Frames Per Second", "Speed of the animation"), t.m_ConstantFramesPerSecond);
t.m_RandomizeStart = EditorGUILayout.Toggle(new GUIContent("Randomize start", "Choose the first frame at random? (to add variety)"), t.m_RandomizeStart);
EditorGUI.indentLevel--;
}
if (t.m_PlaybackMode == Sequence.PlaybackMode.Constant) {
EditorGUILayout.HelpBox("The sequence will show each frame for " + (Mathf.Round((1f / t.m_ConstantFramesPerSecond) * 100) / 100f) + " seconds", MessageType.Info);
} else if (t.m_PlaybackMode == Sequence.PlaybackMode.EveryBeat) {
EditorGUILayout.HelpBox("The sequence will play one frame per beat", MessageType.Info);
if (FindObjectOfType<VisualizerManager>() == null)
EditorGUILayout.HelpBox("Add the [TiltBrush Audio Reactivity] prefab to your scene.", MessageType.Error);
}
#if TILTBRUSH_CINEMADIRECTORPRESENT
EditorGUILayout.Space ();
CustomLabel ("Export", 12, FontStyle.Italic, TextAnchor.MiddleRight);
FOLDOUT_DIRECTOR = EditorGUILayout.Foldout (FOLDOUT_DIRECTOR, "Export to Cutscene Director");
if (FOLDOUT_DIRECTOR) {
t.m_DirectorFrameDuration = EditorGUILayout.FloatField (new GUIContent ("Time per frame", "How long should each frame last when exporting into a Cutscene?"), t.m_DirectorFrameDuration);
if (GUILayout.Button ("Turn into Cutscene")) {
SequenceUtils.CreateCutscene (t.m_FrameSources, t.m_DirectorFrameDuration);
}
}
#endif
EditorGUILayout.Space();
CustomLabel("Animation", 10, FontStyle.Italic, TextAnchor.MiddleRight);
string dragBoxText = "Drag folders, models or game objects here to add frames";
GUI.color = DRAGBOX_COLOR_NORMAL;
var firstDraggedObject = DragAndDrop.objectReferences.Length > 0 ? DragAndDrop.objectReferences[0] : null;
if (firstDraggedObject != null) {
DragAndDrop.visualMode = DragAndDropVisualMode.Link;
if (Event.current.type == EventType.DragPerform) {
// Add all the dragged objects/folders
var allAssets = DragAndDrop.objectReferences;
System.Array.Sort(allAssets, new AlphanumericComparer());
foreach (var asset in allAssets) {
ProcessAsset(asset, true);
}
} else {
// Just preview
dragBoxText = ProcessAsset(firstDraggedObject);
Repaint();
}
}
// Box to drag things on
var rect = EditorGUILayout.BeginVertical(GUILayout.MinHeight(64));
EditorGUILayout.Space();
gs = new GUIStyle(GUI.skin.box);
gs.normal.textColor = GUI.skin.label.normal.textColor;
gs.alignment = TextAnchor.MiddleCenter;
gs.fontSize = 14;
gs.fontStyle = FontStyle.Bold;
gs.onHover.textColor = Color.green;
GUI.Box(rect, dragBoxText, gs);
GUI.color = Color.white;
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
Rect r;
int frameHeight = 70;
r = EditorGUILayout.BeginVertical(GUILayout.Height(frameHeight * t.m_FrameSources.Count));
GUI.Box(r, GUIContent.none, GUI.skin.box);
if (EditorUtils.IconButton(
new Rect(r.x + r.width - 28, r.y + 7, 20, 20),
m_IconDelete,
new Color(0.7f, 0.2f, 0.2f),
"Delete all frames")
&& EditorUtility.DisplayDialogComplex("Delete all", "Delete all the frames in this sequence?", "Delete All", "Cancel", "") == 0)
t.m_FrameSources.Clear();
if (EditorUtils.IconButton(
new Rect(r.x + r.width - 50, r.y + 7, 20, 20),
m_IconAdd,
EditorGUIUtility.isProSkin ? new Color(0.7f, 0.7f, 0.7f) : new Color(0.3f, 0.3f, 0.3f),
"Add an empty frame"
))
t.m_FrameSources.Add(new Sequence.FrameInfo());
EditorGUILayout.Space();
CustomLabel(t.m_FrameSources.Count + " Frames", 12, FontStyle.Bold, TextAnchor.MiddleCenter);
EditorGUILayout.Space();
if (Event.current.type != EventType.DragPerform) {
for (int i = 0; i < t.m_FrameSources.Count; i++) {
var frame = t.m_FrameSources[i];
var isEmpty = frame.m_Source == null;
r = EditorGUILayout.BeginHorizontal(GUILayout.Height(frameHeight));
gs = new GUIStyle(GUI.skin.textArea);
GUI.backgroundColor = i % 2 != 0 ? new Color(0.9f, 0.9f, 0.9f) : Color.white;
GUI.Box(r, GUIContent.none, gs);
float margin = 6;
r.x += margin;
r.y += margin;
r.height -= margin * 2;
gs = new GUIStyle(GUI.skin.box);
gs.alignment = TextAnchor.MiddleLeft;
gs.padding = new RectOffset(2, 2, 2, 2);
GUI.color = isEmpty ? Color.gray : Color.white;
GUI.Box(new Rect(r.x, r.y, r.height, r.height),
isEmpty ? null : AssetPreview.GetAssetPreview(frame.m_Source), gs);
GUI.color = Color.white;
gs = new GUIStyle(GUI.skin.label);
gs.alignment = TextAnchor.MiddleLeft;
GUI.Label(new Rect(r.x + r.height + 5, r.y, r.width * .5f - r.height - 5, r.height),
isEmpty ? "(Empty)" : frame.m_Source.name, gs);
if (!isEmpty && Event.current.type == EventType.MouseDown &&
new Rect(r.x, r.y, r.width * .5f, r.height).Contains(Event.current.mousePosition)) {
EditorGUIUtility.PingObject(frame.m_Source);
}
var repetitionsRect = new Rect(r.width - 55, r.y, 30, r.height);
gs = new GUIStyle(GUI.skin.label);
gs.alignment = TextAnchor.LowerCenter;
gs.fontSize = 9;
GUI.Label(
new Rect(repetitionsRect.x - 7, repetitionsRect.y, repetitionsRect.width + 10, repetitionsRect.height * .5f - 4),
new GUIContent("Repeat", "How many times is this frame repeated?"), gs
);
gs = new GUIStyle(GUI.skin.textField);
gs.alignment = TextAnchor.MiddleCenter;
frame.m_Repetitions = EditorGUI.IntField(
new Rect(repetitionsRect.x, repetitionsRect.y + repetitionsRect.height * .5f, repetitionsRect.width, repetitionsRect.height * .5f),
new GUIContent("", "How many times is this frame repeated?"),
frame.m_Repetitions,
gs
);
t.m_FrameSources[i] = frame;
Color button_color_normal = EditorGUIUtility.isProSkin ? new Color(0.7f, 0.7f, 0.7f) : new Color(0.3f, 0.3f, 0.3f);
float icon_height = r.height / 3f;
Rect rect_delete = new Rect(r.width - 15, r.y, 20, icon_height);
Rect rect_up = new Rect(r.width - 15, r.y + icon_height * 1, 20, icon_height);
Rect rect_down = new Rect(r.width - 15, r.y + icon_height * 2, 20, icon_height);
if (EditorUtils.IconButton(rect_delete, m_IconDelete, new Color(0.7f, 0.2f, 0.2f), "Delete")) {
t.m_FrameSources.RemoveAt(i);
i--;
}
if (EditorUtils.IconButton
(rect_up, m_IconUp,
i > 0 ? button_color_normal : new Color(0.5f, 0.5f, 0.5f, 0.25f),
"Move up"
) && i > 0) {
var prev = t.m_FrameSources[i - 1];
t.m_FrameSources[i - 1] = t.m_FrameSources[i];
t.m_FrameSources[i] = prev;
}
if (EditorUtils.IconButton(
rect_down, m_IconDown,
i < t.m_FrameSources.Count - 1 ? button_color_normal : new Color(0.5f, 0.5f, 0.5f, 0.25f),
"Move down"
) && i < t.m_FrameSources.Count - 1) {
var next = t.m_FrameSources[i + 1];
t.m_FrameSources[i + 1] = t.m_FrameSources[i];
t.m_FrameSources[i] = next;
}
EditorGUILayout.Space();
EditorGUILayout.EndHorizontal();
}
}
if (t.m_FrameSources.Count == 0) {
EditorGUILayout.HelpBox("There's no frames! Add some models", MessageType.Warning);
EditorGUILayout.Space();
}
EditorGUILayout.EndVertical();
t.m_PreviewFirstFrame = EditorGUILayout.ToggleLeft("Preview first frame", t.m_PreviewFirstFrame);
if (EditorGUI.EndChangeCheck()) {
t.EnsureEditorPreview(true);
}
}
void CustomLabel(string Text, int FontSize, FontStyle FontStyle = FontStyle.Normal, TextAnchor Alignment = TextAnchor.MiddleLeft) {
var gs = new GUIStyle(GUI.skin.label);
gs.fontSize = FontSize;
gs.fontStyle = FontStyle;
gs.alignment = Alignment;
EditorGUILayout.LabelField(Text, gs, GUILayout.MinHeight(FontSize * 1.5f));
}
static Color DRAGBOX_COLOR_NORMAL = Color.white;
static Color DRAGBOX_COLOR_ONDRAG_FOLDER = new Color(1.0f, 1.0f, 0.5f);
static Color DRAGBOX_COLOR_ONDRAG_FILE = new Color(0.5f, 1.0f, 0.5f);
static Color DRAGBOX_COLOR_ERROR = new Color(1.0f, 0.3f, 0.3f);
string ProcessAsset(Object Asset, bool Add = false) {
var type = SequenceUtils.GetAssetType(Asset);
if (type == Sequence.SourceType.Folder) {
if (Add) {
var frames = EditorUtils.GetFramesFromFolder(Asset);
foreach (var f in frames) {
(target as Sequence).AddFrame(f, Sequence.SourceType.Model);
EditorUtility.SetDirty(target);
}
}
GUI.color = DRAGBOX_COLOR_ONDRAG_FOLDER;
return string.Format("Adding folder '{0}'", Asset.name);
} else if (type != Sequence.SourceType.Unsupported) {
if (Add) {
(target as Sequence).AddFrame(Asset as GameObject, type);
EditorUtility.SetDirty(target);
}
GUI.color = DRAGBOX_COLOR_ONDRAG_FILE;
return "Adding '" + Asset.name + "'";
}
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
GUI.color = DRAGBOX_COLOR_ERROR;
return "This asset isn't compatible!";
}
}
} // namespace TiltBrushToolkit
| |
using System;
using System.Collections.Generic;
using System.Text;
using JsonLD.Core;
using Newtonsoft.Json.Linq;
namespace JsonLD.Core
{
internal class RDFDatasetUtils
{
/// <summary>Creates an array of RDF triples for the given graph.</summary>
/// <remarks>Creates an array of RDF triples for the given graph.</remarks>
/// <param name="graph">the graph to create RDF triples for.</param>
/// <param name="namer">a UniqueNamer for assigning blank node names.</param>
/// <returns>the array of RDF triples for the given graph.</returns>
[Obsolete]
internal static JArray GraphToRDF(JObject graph, UniqueNamer
namer)
{
// use RDFDataset.graphToRDF
JArray rval = new JArray();
foreach (string id in graph.GetKeys())
{
JObject node = (JObject)graph[id];
JArray properties = new JArray(node.GetKeys());
properties.SortInPlace();
foreach (string property in properties)
{
var eachProperty = property;
JToken items = node[eachProperty];
if ("@type".Equals(eachProperty))
{
eachProperty = JSONLDConsts.RdfType;
}
else
{
if (JsonLdUtils.IsKeyword(eachProperty))
{
continue;
}
}
foreach (JToken item in (JArray)items)
{
// RDF subjects
JObject subject = new JObject();
if (id.IndexOf("_:") == 0)
{
subject["type"] = "blank node";
subject["value"] = namer.GetName(id);
}
else
{
subject["type"] = "IRI";
subject["value"] = id;
}
// RDF predicates
JObject predicate = new JObject();
predicate["type"] = "IRI";
predicate["value"] = eachProperty;
// convert @list to triples
if (JsonLdUtils.IsList(item))
{
ListToRDF((JArray)((JObject)item)["@list"], namer, subject
, predicate, rval);
}
else
{
// convert value or node object to triple
object @object = ObjectToRDF(item, namer);
IDictionary<string, object> tmp = new Dictionary<string, object>();
tmp["subject"] = subject;
tmp["predicate"] = predicate;
tmp["object"] = @object;
rval.Add(tmp);
}
}
}
}
return rval;
}
/// <summary>
/// Converts a @list value into linked list of blank node RDF triples (an RDF
/// collection).
/// </summary>
/// <remarks>
/// Converts a @list value into linked list of blank node RDF triples (an RDF
/// collection).
/// </remarks>
/// <param name="list">the @list value.</param>
/// <param name="namer">a UniqueNamer for assigning blank node names.</param>
/// <param name="subject">the subject for the head of the list.</param>
/// <param name="predicate">the predicate for the head of the list.</param>
/// <param name="triples">the array of triples to append to.</param>
private static void ListToRDF(JArray list, UniqueNamer namer, JObject subject, JObject predicate, JArray triples
)
{
JObject first = new JObject();
first["type"] = "IRI";
first["value"] = JSONLDConsts.RdfFirst;
JObject rest = new JObject();
rest["type"] = "IRI";
rest["value"] = JSONLDConsts.RdfRest;
JObject nil = new JObject();
nil["type"] = "IRI";
nil["value"] = JSONLDConsts.RdfNil;
foreach (JToken item in list)
{
JObject blankNode = new JObject();
blankNode["type"] = "blank node";
blankNode["value"] = namer.GetName();
{
JObject tmp = new JObject();
tmp["subject"] = subject;
tmp["predicate"] = predicate;
tmp["object"] = blankNode;
triples.Add(tmp);
}
subject = blankNode;
predicate = first;
JToken @object = ObjectToRDF(item, namer);
{
JObject tmp = new JObject();
tmp["subject"] = subject;
tmp["predicate"] = predicate;
tmp["object"] = @object;
triples.Add(tmp);
}
predicate = rest;
}
JObject tmp_1 = new JObject();
tmp_1["subject"] = subject;
tmp_1["predicate"] = predicate;
tmp_1["object"] = nil;
triples.Add(tmp_1);
}
/// <summary>
/// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
/// node object to an RDF resource.
/// </summary>
/// <remarks>
/// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
/// node object to an RDF resource.
/// </remarks>
/// <param name="item">the JSON-LD value or node object.</param>
/// <param name="namer">the UniqueNamer to use to assign blank node names.</param>
/// <returns>the RDF literal or RDF resource.</returns>
private static JObject ObjectToRDF(JToken item, UniqueNamer namer)
{
JObject @object = new JObject();
// convert value object to RDF
if (JsonLdUtils.IsValue(item))
{
@object["type"] = "literal";
JToken value = ((JObject)item)["@value"];
JToken datatype = ((JObject)item)["@type"];
// convert to XSD datatypes as appropriate
if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer )
{
// convert to XSD datatype
if (value.Type == JTokenType.Boolean)
{
@object["value"] = value.ToString();
@object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdBoolean : datatype;
}
else
{
if (value.Type == JTokenType.Float)
{
// canonical double representation
@object["value"] = string.Format("{0:0.0###############E0}", (double)value);
@object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdDouble : datatype;
}
else
{
DecimalFormat df = new DecimalFormat("0");
@object["value"] = df.Format((int)value);
@object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdInteger : datatype;
}
}
}
else
{
if (((IDictionary<string, JToken>)item).ContainsKey("@language"))
{
@object["value"] = value;
@object["datatype"] = datatype.IsNull() ? JSONLDConsts.RdfLangstring : datatype;
@object["language"] = ((IDictionary<string, JToken>)item)["@language"];
}
else
{
@object["value"] = value;
@object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdString : datatype;
}
}
}
else
{
// convert string/node object to RDF
string id = JsonLdUtils.IsObject(item) ? (string)((JObject)item
)["@id"] : (string)item;
if (id.IndexOf("_:") == 0)
{
@object["type"] = "blank node";
@object["value"] = namer.GetName(id);
}
else
{
@object["type"] = "IRI";
@object["value"] = id;
}
}
return @object;
}
public static string ToNQuads(RDFDataset dataset)
{
IList<string> quads = new List<string>();
foreach (string graphName in dataset.GraphNames())
{
var eachGraphName = graphName;
IList<RDFDataset.Quad> triples = dataset.GetQuads(eachGraphName);
if ("@default".Equals(eachGraphName))
{
eachGraphName = null;
}
foreach (RDFDataset.Quad triple in triples)
{
quads.Add(ToNQuad(triple, eachGraphName));
}
}
((List<string>)quads).Sort(StringComparer.Ordinal);
string rval = string.Empty;
foreach (string quad in quads)
{
rval += quad;
}
return rval;
}
internal static string ToNQuad(RDFDataset.Quad triple, string graphName, string bnode
)
{
RDFDataset.Node s = triple.GetSubject();
RDFDataset.Node p = triple.GetPredicate();
RDFDataset.Node o = triple.GetObject();
string quad = string.Empty;
// subject is an IRI or bnode
if (s.IsIRI())
{
quad += "<" + Escape(s.GetValue()) + ">";
}
else
{
// normalization mode
if (bnode != null)
{
quad += bnode.Equals(s.GetValue()) ? "_:a" : "_:z";
}
else
{
// normal mode
quad += s.GetValue();
}
}
if (p.IsIRI())
{
quad += " <" + Escape(p.GetValue()) + "> ";
}
else
{
// otherwise it must be a bnode (TODO: can we only allow this if the
// flag is set in options?)
quad += " " + Escape(p.GetValue()) + " ";
}
// object is IRI, bnode or literal
if (o.IsIRI())
{
quad += "<" + Escape(o.GetValue()) + ">";
}
else
{
if (o.IsBlankNode())
{
// normalization mode
if (bnode != null)
{
quad += bnode.Equals(o.GetValue()) ? "_:a" : "_:z";
}
else
{
// normal mode
quad += o.GetValue();
}
}
else
{
string escaped = Escape(o.GetValue());
quad += "\"" + escaped + "\"";
if (JSONLDConsts.RdfLangstring.Equals(o.GetDatatype()))
{
quad += "@" + o.GetLanguage();
}
else
{
if (!JSONLDConsts.XsdString.Equals(o.GetDatatype()))
{
quad += "^^<" + Escape(o.GetDatatype()) + ">";
}
}
}
}
// graph
if (graphName != null)
{
if (graphName.IndexOf("_:") != 0)
{
quad += " <" + Escape(graphName) + ">";
}
else
{
if (bnode != null)
{
quad += " _:g";
}
else
{
quad += " " + graphName;
}
}
}
quad += " .\n";
return quad;
}
internal static string ToNQuad(RDFDataset.Quad triple, string graphName)
{
return ToNQuad(triple, graphName, null);
}
private static readonly Pattern UcharMatched = Pattern.Compile("\\u005C(?:([tbnrf\\\"'])|(?:u("
+ JsonLD.Core.Regex.Hex + "{4}))|(?:U(" + JsonLD.Core.Regex.Hex + "{8})))"
);
public static string Unescape(string str)
{
string rval = str;
if (str != null)
{
Matcher m = UcharMatched.Matcher(str);
while (m.Find())
{
string uni = m.Group(0);
if (m.Group(1) == null)
{
string hex = m.Group(2) != null ? m.Group(2) : m.Group(3);
int v = System.Convert.ToInt32(hex, 16);
// hex =
// hex.replaceAll("^(?:00)+",
// "");
if (v > unchecked((int)(0xFFFF)))
{
// deal with UTF-32
// Integer v = Integer.parseInt(hex, 16);
int vt = v - unchecked((int)(0x10000));
int vh = vt >> 10;
int v1 = vt & unchecked((int)(0x3FF));
int w1 = unchecked((int)(0xD800)) + vh;
int w2 = unchecked((int)(0xDC00)) + v1;
StringBuilder b = new StringBuilder();
b.AppendCodePoint(w1);
b.AppendCodePoint(w2);
uni = b.ToString();
}
else
{
uni = char.ToString((char)v);
}
}
else
{
char c = m.Group(1)[0];
switch (c)
{
case 'b':
{
uni = "\b";
break;
}
case 'n':
{
uni = "\n";
break;
}
case 't':
{
uni = "\t";
break;
}
case 'f':
{
uni = "\f";
break;
}
case 'r':
{
uni = "\r";
break;
}
case '\'':
{
uni = "'";
break;
}
case '\"':
{
uni = "\"";
break;
}
case '\\':
{
uni = "\\";
break;
}
default:
{
// do nothing
continue;
}
}
}
string pat = Pattern.Quote(m.Group(0));
string x = JsonLD.JavaCompat.ToHexString(uni[0]);
rval = rval.Replace(pat, uni);
}
}
return rval;
}
public static string Escape(string str)
{
string rval = string.Empty;
for (int i = 0; i < str.Length; i++)
{
char hi = str[i];
if (hi <= unchecked((int)(0x8)) || hi == unchecked((int)(0xB)) || hi == unchecked(
(int)(0xC)) || (hi >= unchecked((int)(0xE)) && hi <= unchecked((int)(0x1F))) ||
(hi >= unchecked((int)(0x7F)) && hi <= unchecked((int)(0xA0))) || ((hi >= unchecked(
(int)(0x24F)) && !char.IsHighSurrogate(hi))))
{
// 0xA0 is end of
// non-printable latin-1
// supplement
// characters
// 0x24F is the end of latin extensions
// TODO: there's probably a lot of other characters that
// shouldn't be escaped that
// fall outside these ranges, this is one example from the
// json-ld tests
rval += string.Format("\\u%04x", (int)hi);
}
else
{
if (char.IsHighSurrogate(hi))
{
char lo = str[++i];
int c = (hi << 10) + lo + (unchecked((int)(0x10000)) - (unchecked((int)(0xD800))
<< 10) - unchecked((int)(0xDC00)));
rval += string.Format("\\U%08x", c);
}
else
{
switch (hi)
{
case '\b':
{
rval += "\\b";
break;
}
case '\n':
{
rval += "\\n";
break;
}
case '\t':
{
rval += "\\t";
break;
}
case '\f':
{
rval += "\\f";
break;
}
case '\r':
{
rval += "\\r";
break;
}
case '\"':
{
// case '\'':
// rval += "\\'";
// break;
rval += "\\\"";
// rval += "\\u0022";
break;
}
case '\\':
{
rval += "\\\\";
break;
}
default:
{
// just put the char as is
rval += hi;
break;
}
}
}
}
}
return rval;
}
private class Regex
{
public static readonly Pattern HEX = Pattern.Compile("[0-9A-Fa-f]");
public static readonly Pattern UCHAR = Pattern.Compile("\\\\u" + HEX + "{4}|\\\\U" + HEX + "{8}");
public static readonly Pattern Iri = Pattern.Compile("(?:<((?:[^\\x00-\\x20<>\"{}|^`\\\\]|" + UCHAR + ")*)>)");
public static readonly Pattern Bnode = Pattern.Compile("(_:(?:[A-Za-z0-9](?:[A-Za-z0-9\\-\\.]*[A-Za-z0-9])?))"
);
public static readonly Pattern ECHAR = Pattern.Compile("\\\\[tbnrf\"'\\\\]");
public static readonly Pattern Plain = Pattern.Compile("\"((?:[^\\x22\\x5C\\x0A\\x0D]|" + ECHAR + "|" + UCHAR + ")*)\"");
public static readonly Pattern Datatype = Pattern.Compile("(?:\\^\\^" + Iri + ")"
);
public static readonly Pattern Language = Pattern.Compile("(?:@([a-z]+(?:-[a-zA-Z0-9]+)*))"
);
public static readonly Pattern Literal = Pattern.Compile("(?:" + Plain + "(?:" +
Datatype + "|" + Language + ")?)");
public static readonly Pattern Wso = Pattern.Compile("[ \\t]*");
public static readonly Pattern Eoln = Pattern.Compile("(?:\r\n)|(?:\n)|(?:\r)");
public static readonly Pattern EmptyOrComment = Pattern.Compile("^" + Wso + "(#.*)?$");
public static readonly Pattern Subject = Pattern.Compile("(?:" + Iri + "|" + Bnode
+ ")" + Wso);
public static readonly Pattern Property = Pattern.Compile(Iri.GetPattern() + Wso);
public static readonly Pattern Object = Pattern.Compile("(?:" + Iri + "|" + Bnode
+ "|" + Literal + ")" + Wso);
public static readonly Pattern Graph = Pattern.Compile("(?:\\.|(?:(?:" + Iri + "|"
+ Bnode + ")" + Wso + "\\.))");
public static readonly Pattern Quad = Pattern.Compile("^" + Wso + Subject + Property
+ Object + Graph + Wso + "(#.*)?$");
// define partial regexes
// final public static Pattern IRI =
// Pattern.compile("(?:<([^:]+:[^>]*)>)");
// define quad part regexes
// full quad regex
}
/// <summary>Parses RDF in the form of N-Quads.</summary>
/// <remarks>Parses RDF in the form of N-Quads.</remarks>
/// <param name="input">the N-Quads input to parse.</param>
/// <returns>an RDF dataset.</returns>
/// <exception cref="JsonLD.Core.JsonLdError"></exception>
public static RDFDataset ParseNQuads(string input)
{
// build RDF dataset
RDFDataset dataset = new RDFDataset();
// split N-Quad input into lines
string[] lines = RDFDatasetUtils.Regex.Eoln.Split(input);
int lineNumber = 0;
foreach (string line in lines)
{
lineNumber++;
// skip empty lines
if (RDFDatasetUtils.Regex.EmptyOrComment.Matcher(line).Matches())
{
continue;
}
// parse quad
Matcher match = RDFDatasetUtils.Regex.Quad.Matcher(line);
if (!match.Matches())
{
throw new JsonLdError(JsonLdError.Error.SyntaxError, "Error while parsing N-Quads; invalid quad. line:"
+ lineNumber);
}
// get subject
RDFDataset.Node subject;
if (match.Group(1) != null)
{
var subjectIri = Unescape(match.Group(1));
AssertAbsoluteIri(subjectIri);
subject = new RDFDataset.IRI(subjectIri);
}
else
{
subject = new RDFDataset.BlankNode(Unescape(match.Group(2)));
}
// get predicate
var predicateIri = Unescape(match.Group(3));
AssertAbsoluteIri(predicateIri);
RDFDataset.Node predicate = new RDFDataset.IRI(predicateIri);
// get object
RDFDataset.Node @object;
if (match.Group(4) != null)
{
var objectIri = Unescape(match.Group(4));
AssertAbsoluteIri(objectIri);
@object = new RDFDataset.IRI(objectIri);
}
else
{
if (match.Group(5) != null)
{
@object = new RDFDataset.BlankNode(Unescape(match.Group(5)));
}
else
{
string language = Unescape(match.Group(8));
string datatype = match.Group(7) != null ? Unescape(match.Group(7)) : match.Group
(8) != null ? JSONLDConsts.RdfLangstring : JSONLDConsts.XsdString;
AssertAbsoluteIri(datatype);
string unescaped = Unescape(match.Group(6));
@object = new RDFDataset.Literal(unescaped, datatype, language);
}
}
// get graph name ('@default' is used for the default graph)
string name = "@default";
if (match.Group(9) != null)
{
name = Unescape(match.Group(9));
AssertAbsoluteIri(name);
}
else
{
if (match.Group(10) != null)
{
name = Unescape(match.Group(10));
}
}
RDFDataset.Quad triple = new RDFDataset.Quad(subject, predicate, @object, name);
// initialise graph in dataset
if (!dataset.ContainsKey(name))
{
IList<RDFDataset.Quad> tmp = new List<RDFDataset.Quad>();
tmp.Add(triple);
dataset[name] = tmp;
}
else
{
// add triple if unique to its graph
IList<RDFDataset.Quad> triples = (IList<RDFDataset.Quad>)dataset[name];
if (!triples.Contains(triple))
{
triples.Add(triple);
}
}
}
return dataset;
}
private static void AssertAbsoluteIri(string iri)
{
if (Uri.IsWellFormedUriString(Uri.EscapeUriString(iri), UriKind.Absolute) == false)
{
throw new JsonLdError(JsonLdError.Error.SyntaxError, "Invalid absolute URI <" + iri + ">");
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A lake (for example, Lake Pontrachain).
/// </summary>
public class LakeBodyOfWater_Core : TypeCore, IBodyOfWater
{
public LakeBodyOfWater_Core()
{
this._TypeId = 145;
this._Id = "LakeBodyOfWater";
this._Schema_Org_Url = "http://schema.org/LakeBodyOfWater";
string label = "";
GetLabel(out label, "LakeBodyOfWater", typeof(LakeBodyOfWater_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,146,40};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{40};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// 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.Xml;
using System.Collections.Generic;
using System.Globalization;
#if NET_NATIVE
namespace System.Runtime.Serialization
{
public sealed class ExtensionDataObject
{
private IList<ExtensionDataMember> _members;
#if USE_REFEMIT
public ExtensionDataObject()
#else
internal ExtensionDataObject()
#endif
{
}
#if USE_REFEMIT
public IList<ExtensionDataMember> Members
#else
internal IList<ExtensionDataMember> Members
#endif
{
get { return _members; }
set { _members = value; }
}
}
#if USE_REFEMIT
public class ExtensionDataMember
#else
internal class ExtensionDataMember
#endif
{
private string _name;
private string _ns;
private IDataNode _value;
private int _memberIndex;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Namespace
{
get { return _ns; }
set { _ns = value; }
}
public IDataNode Value
{
get { return _value; }
set { _value = value; }
}
public int MemberIndex
{
get { return _memberIndex; }
set { _memberIndex = value; }
}
}
#if USE_REFEMIT
public interface IDataNode
#else
internal interface IDataNode
#endif
{
Type DataType { get; }
object Value { get; set; } // boxes for primitives
string DataContractName { get; set; }
string DataContractNamespace { get; set; }
string ClrTypeName { get; set; }
string ClrAssemblyName { get; set; }
string Id { get; set; }
bool PreservesReferences { get; }
// NOTE: consider moving below APIs to DataNode<T> if IDataNode API is made public
void GetData(ElementData element);
bool IsFinalValue { get; set; }
void Clear();
}
internal class DataNode<T> : IDataNode
{
protected Type dataType;
private T _value;
private string _dataContractName;
private string _dataContractNamespace;
private string _clrTypeName;
private string _clrAssemblyName;
private string _id = Globals.NewObjectId;
private bool _isFinalValue;
internal DataNode()
{
this.dataType = typeof(T);
_isFinalValue = true;
}
internal DataNode(T value)
: this()
{
_value = value;
}
public Type DataType
{
get { return dataType; }
}
public object Value
{
get { return _value; }
set { _value = (T)value; }
}
bool IDataNode.IsFinalValue
{
get { return _isFinalValue; }
set { _isFinalValue = value; }
}
public T GetValue()
{
return _value;
}
#if NotUsed
public void SetValue(T value)
{
this.value = value;
}
#endif
public string DataContractName
{
get { return _dataContractName; }
set { _dataContractName = value; }
}
public string DataContractNamespace
{
get { return _dataContractNamespace; }
set { _dataContractNamespace = value; }
}
public string ClrTypeName
{
get { return _clrTypeName; }
set { _clrTypeName = value; }
}
public string ClrAssemblyName
{
get { return _clrAssemblyName; }
set { _clrAssemblyName = value; }
}
public bool PreservesReferences
{
get { return (Id != Globals.NewObjectId); }
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public virtual void GetData(ElementData element)
{
element.dataNode = this;
element.attributeCount = 0;
element.childElementIndex = 0;
if (DataContractName != null)
AddQualifiedNameAttribute(element, Globals.XsiPrefix, Globals.XsiTypeLocalName, Globals.SchemaInstanceNamespace, DataContractName, DataContractNamespace);
if (ClrTypeName != null)
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrTypeLocalName, ClrTypeName);
if (ClrAssemblyName != null)
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, ClrAssemblyName);
}
public virtual void Clear()
{
// dataContractName not cleared because it is used when re-serializing from unknown data
_clrTypeName = _clrAssemblyName = null;
}
internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs)
{
string prefix = ExtensionDataReader.GetPrefix(valueNs);
element.AddAttribute(elementPrefix, elementNs, elementName, String.Format(CultureInfo.InvariantCulture, "{0}:{1}", prefix, valueName));
bool prefixDeclaredOnElement = false;
if (element.attributes != null)
{
for (int i = 0; i < element.attributes.Length; i++)
{
AttributeData attribute = element.attributes[i];
if (attribute != null && attribute.prefix == Globals.XmlnsPrefix && attribute.localName == prefix)
{
prefixDeclaredOnElement = true;
break;
}
}
}
if (!prefixDeclaredOnElement)
element.AddAttribute(Globals.XmlnsPrefix, Globals.XmlnsNamespace, prefix, valueNs);
}
}
internal class ClassDataNode : DataNode<object>
{
private IList<ExtensionDataMember> _members;
internal ClassDataNode()
{
dataType = Globals.TypeOfClassDataNode;
}
internal IList<ExtensionDataMember> Members
{
get { return _members; }
set { _members = value; }
}
public override void Clear()
{
base.Clear();
_members = null;
}
}
internal class CollectionDataNode : DataNode<Array>
{
private IList<IDataNode> _items;
private string _itemName;
private string _itemNamespace;
private int _size = -1;
internal CollectionDataNode()
{
dataType = Globals.TypeOfCollectionDataNode;
}
internal IList<IDataNode> Items
{
get { return _items; }
set { _items = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal string ItemNamespace
{
get { return _itemNamespace; }
set { _itemNamespace = value; }
}
internal int Size
{
get { return _size; }
set { _size = value; }
}
public override void GetData(ElementData element)
{
base.GetData(element);
element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ArraySizeLocalName, Size.ToString(NumberFormatInfo.InvariantInfo));
}
public override void Clear()
{
base.Clear();
_items = null;
_size = -1;
}
}
internal class ISerializableDataNode : DataNode<object>
{
private string _factoryTypeName;
private string _factoryTypeNamespace;
private IList<ISerializableDataMember> _members;
internal ISerializableDataNode()
{
dataType = Globals.TypeOfISerializableDataNode;
}
internal string FactoryTypeName
{
get { return _factoryTypeName; }
set { _factoryTypeName = value; }
}
internal string FactoryTypeNamespace
{
get { return _factoryTypeNamespace; }
set { _factoryTypeNamespace = value; }
}
internal IList<ISerializableDataMember> Members
{
get { return _members; }
set { _members = value; }
}
public override void GetData(ElementData element)
{
base.GetData(element);
if (FactoryTypeName != null)
AddQualifiedNameAttribute(element, Globals.SerPrefix, Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace, FactoryTypeName, FactoryTypeNamespace);
}
public override void Clear()
{
base.Clear();
_members = null;
_factoryTypeName = _factoryTypeNamespace = null;
}
}
internal class ISerializableDataMember
{
private string _name;
private IDataNode _value;
internal string Name
{
get { return _name; }
set { _name = value; }
}
internal IDataNode Value
{
get { return _value; }
set { _value = value; }
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Trinity.MsSql
{
public class SqlModelCommand<T> : DataCommand<T> where T : class
{
public SqlModelCommand(IDbConnection connection)
: base(connection)
{
}
public SqlModelCommand(IDbConnection connection, List<IDataParameter> parameters, DataCommandType commandType)
: base(connection, parameters, commandType)
{
}
public SqlModelCommand(IDataManager manager) : base(manager)
{
}
public override void ResetCommand()
{
this.Changes.Clear();
base.ResetCommand();
}
public override void SetParameter(string parameterName, string column, object value, bool isSelectParameter)
{
{
var newDataParameter = this.Parameters.SingleOrDefault(
m => m.Name.Contains(parameterName));
if (newDataParameter == null)
{
newDataParameter = Activator.CreateInstance<SqlDataParameter>();
newDataParameter.Name = parameterName;
newDataParameter.ColumnName = column;
newDataParameter.IsSelectParameter = isSelectParameter;
Column(column);
this.Parameters.Add(newDataParameter);
}
;
newDataParameter.Value = value;
}
}
public override string GetTableMap()
{
if (string.IsNullOrEmpty(this.TabelName))
{
this.TabelName = this.GetTableAttribute();
IsMapped = true;
}
else
{
if (typeof(T).Name == this.TabelName)
IsMapped = true;
}
var modelName = base.GetTableMapName();
if (Manager.TableMaps.ContainsKey(modelName))
{
this.TableMap = Manager.TableMaps[modelName];
if (this.PrimaryKeys.Count == 0)
this.PrimaryKeys = TableMap.GetPrimaryKeys();
}
else
{
if (this.Manager.TableMapFromDatabase == false)
base.GetTableMap();
else
{
var tableMap = this.TableMap ?? new TableMap();
tableMap.TableName = this.TabelName;
if (Manager.TableMaps.ContainsKey(modelName) == false)
{
try
{
Manager.TableMaps.Add(modelName, tableMap);
}
catch (Exception)
{
}
}
this.TableMap = tableMap;
string sqlTableMap =
string.Format(
@"SELECT INFORMATION_SCHEMA.TABLES.TABLE_TYPE, INFORMATION_SCHEMA.COLUMNS.TABLE_CATALOG,
INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA, INFORMATION_SCHEMA.COLUMNS.TABLE_NAME, INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME,
INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION, INFORMATION_SCHEMA.COLUMNS.COLUMN_DEFAULT, INFORMATION_SCHEMA.COLUMNS.IS_NULLABLE,
INFORMATION_SCHEMA.COLUMNS.DATA_TYPE, INFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH,
INFORMATION_SCHEMA.COLUMNS.CHARACTER_OCTET_LENGTH, INFORMATION_SCHEMA.COLUMNS.NUMERIC_PRECISION,
INFORMATION_SCHEMA.COLUMNS.NUMERIC_PRECISION_RADIX, INFORMATION_SCHEMA.COLUMNS.NUMERIC_SCALE,
INFORMATION_SCHEMA.COLUMNS.DATETIME_PRECISION, INFORMATION_SCHEMA.COLUMNS.CHARACTER_SET_CATALOG,
INFORMATION_SCHEMA.COLUMNS.CHARACTER_SET_SCHEMA, INFORMATION_SCHEMA.COLUMNS.CHARACTER_SET_NAME,
INFORMATION_SCHEMA.COLUMNS.COLLATION_CATALOG, INFORMATION_SCHEMA.COLUMNS.COLLATION_SCHEMA,
INFORMATION_SCHEMA.COLUMNS.COLLATION_NAME, INFORMATION_SCHEMA.COLUMNS.DOMAIN_CATALOG,
INFORMATION_SCHEMA.COLUMNS.DOMAIN_SCHEMA, INFORMATION_SCHEMA.COLUMNS.DOMAIN_NAME,
COLUMNPROPERTY(object_id(INFORMATION_SCHEMA.COLUMNS.TABLE_NAME), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'IsIdentity') as IsIdentity,
COLUMNPROPERTY(object_id(INFORMATION_SCHEMA.COLUMNS.TABLE_NAME), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'ColumnId') as ColumnId,
COLUMNPROPERTY(object_id(INFORMATION_SCHEMA.COLUMNS.TABLE_NAME), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'IsComputed ') as IsComputed,
OBJECT_ID(INFORMATION_SCHEMA.COLUMNS.TABLE_NAME) as TableId
FROM INFORMATION_SCHEMA.TABLES INNER JOIN
INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
WHERE (NOT (INFORMATION_SCHEMA.COLUMNS.TABLE_NAME LIKE N'sys%')) AND
(OBJECTPROPERTY(OBJECT_ID(QUOTENAME(INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA) + '.' + QUOTENAME(INFORMATION_SCHEMA.TABLES.TABLE_NAME)), 'IsMSShipped') = 0)
AND INFORMATION_SCHEMA.TABLES.TABLE_NAME = '{0}'
ORDER BY INFORMATION_SCHEMA.TABLES.TABLE_TYPE, INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA, INFORMATION_SCHEMA.COLUMNS.TABLE_NAME, INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME",
tableMap.TableName);
using (var conn = new SqlConnection(Manager.ConnectionString))
{
conn.Open();
using (var command = new SqlCommand(sqlTableMap, conn))
{
using (var reader = command.ExecuteReader())
{
int index = 0;
while (reader.Read())
{
if (index == 0)
{
tableMap.Id = reader["TableId"].ToInt();
tableMap.TableName = reader["TABLE_NAME"].ToStringValue();
tableMap.Catalog = reader["TABLE_CATALOG"].ToStringValue();
tableMap.Schema = reader["TABLE_SCHEMA"].ToStringValue();
tableMap.TableType = reader["TABLE_TYPE"].ToStringValue();
}
index++;
var columnName = reader["COLUMN_NAME"].ToStringValue();
var columnMap = tableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnName);
if (columnMap == null)
{
columnMap = new SqlColumnMap();
columnMap.ColumnName = columnName;
columnMap.IsMapped = false;
tableMap.ColumnMaps.Add(columnMap);
}
var map = columnMap as SqlColumnMap;
if (map == null)
throw new ApplicationException("ColumnMap is no SqlColumnMap");
map.Id = reader["ColumnId"].ToInt();
map.IsIdentity = reader["IsIdentity"].ToBool();
map.IsComputed = reader["IsComputed"].ToBool();
map.IsNullable = reader["IS_NULLABLE"].ToBool();
map.Size = reader["CHARACTER_MAXIMUM_LENGTH"].ToInt();
map.DbType = reader["DATA_TYPE"].ToEnumValue<SqlDbType>(SqlDbType.NVarChar);
map.OrdinalPosition = reader["ORDINAL_POSITION"].ToInt();
map.Default = reader["COLUMN_DEFAULT"].ToStringValue();
}
reader.Close();
}
var propertyMap = this.GetColumnAttributes();
foreach (var column in tableMap.ColumnMaps)
{
var item =
propertyMap.FirstOrDefault(m => m.ColumnName == column.ColumnName);
if (item != null)
{
column.IsMapped = true;
column.PropertyName = item.PropertyName;
}
else
{
column.IsMapped = false;
}
}
tableMap.KeyMaps = GetKeyMap(tableMap.TableName, tableMap.ColumnMaps);
foreach (var item in tableMap.KeyMaps)
{
var column = tableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == item.ParentColumnName);
if (column != null)
switch (item.KeyType)
{
case KeyMapType.PrimaryKey:
column.IsPrimaryKey = true;
break;
case KeyMapType.ForeignKey:
column.IsForeinKey = true;
break;
}
}
}
}
this.PrimaryKeys = tableMap.GetPrimaryKeys();
}
}
return modelName;
}
private List<KeyMap> GetKeyMap(string tablename, List<IColumnMap> columnMaps)
{
var keys = new List<KeyMap>();
string sqlKeysMap =
string.Format(
@"WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) AS(SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(150)) ,CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(150)) , PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(150)) , PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(150)) ,PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,REFERENCE_TABLE_NAME='' ,REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY INNER JOIN sys.tables as PKnUTable ON PKnUTable.object_id = PKnUKEY.parent_object_id INNER JOIN sys.index_columns as PKnUColIdx ON PKnUColIdx.object_id = PKnUTable.object_id AND PKnUColIdx.index_id = PKnUKEY.unique_index_id INNER JOIN sys.columns as PKnUKEYCol ON PKnUKEYCol.object_id = PKnUTable.object_id AND PKnUKEYCol.column_id = PKnUColIdx.column_id INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl ON oParentColDtl.TABLE_NAME=PKnUTable.name AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(150)) , CONSTRAINT_TYPE='FK', PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(150)) , PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(150)) , PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE, REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(150)) , REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(150))
FROM sys.foreign_key_columns FKC INNER JOIN sys.sysobjects oConstraint ON FKC.constraint_object_id=oConstraint.id INNER JOIN sys.sysobjects oParent ON FKC.parent_object_id=oParent.id INNER JOIN sys.all_columns oParentCol ON FKC.parent_object_id=oParentCol.object_id AND FKC.parent_column_id=oParentCol.column_id INNER JOIN sys.sysobjects oReference ON FKC.referenced_object_id=oReference.id INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl ON oParentColDtl.TABLE_NAME=oParent.name AND oParentColDtl.COLUMN_NAME=oParentCol.name INNER JOIN sys.all_columns oReferenceCol ON FKC.referenced_object_id=oReferenceCol.object_id AND FKC.referenced_column_id=oReferenceCol.column_id)
SELECT * FROM ALL_KEYS_IN_TABLE WHERE PARENT_TABLE_NAME in ('{0}') ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;",
tablename);
using (var conn = new SqlConnection(Manager.ConnectionString))
{
conn.Open();
using (var keyCommand = new SqlCommand(sqlKeysMap, conn))
{
using (var keyReader = keyCommand.ExecuteReader())
{
while (keyReader.Read())
{
var keyMap = new KeyMap();
keyMap.KeyType =
keyMap.GetSqlKeyType(keyReader["CONSTRAINT_TYPE"].ToStringValue());
keyMap.ParentColumnName = keyReader["PARENT_COL_NAME"].ToStringValue();
keyMap.ReferenceTableName =
keyReader["REFERENCE_TABLE_NAME"].ToStringValue();
keyMap.ReferenceColumnName = keyReader["REFERENCE_COL_NAME"].ToStringValue();
if (columnMaps != null)
{
var columnmap = columnMaps.FirstOrDefault(m => m.ColumnName == keyMap.ParentColumnName);
if (columnmap != null)
{
keyMap.PropertyName = columnmap.PropertyName;
keyMap.IsMapped = true;
}
}
if (
keys.FirstOrDefault(
m =>
m.ParentColumnName == keyMap.ParentColumnName
&& m.KeyType == keyMap.KeyType) == null) keys.Add(keyMap);
}
keyReader.Close();
}
}
}
return keys;
}
public override void BuildKeys()
{
var index = 0;
if (this.TableMap == null)
{
base.BuildKeys();
}
else
{
foreach (var key in this.PrimaryKeys)
{
var column = this.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == key);
if (column != null)
{
if (index == 0)
{
this.Where(column.ColumnName, "=", this.GetValue(column.PropertyName));
}
else
{
this.And(column.ColumnName, "=", this.GetValue(column.PropertyName));
}
}
else
{
column = this.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == key);
bool buildNormal = true;
if (column != null)
{
if (Model != null)
{
var item = Model as IModelBase;
if (item != null)
{
if (item.OldValues.ContainsKey(column.PropertyName))
{
if (index == 0)
{
this.Where(column.ColumnName, "=", item.OldValues[column.PropertyName]);
}
else
{
this.And(column.ColumnName, "=", item.OldValues[column.PropertyName]);
}
buildNormal = false;
}
}
}
if (buildNormal)
{
if (index == 0)
{
this.Where(column.ColumnName, "=", this.GetValue(column.PropertyName));
}
else
{
this.And(column.ColumnName, "=", this.GetValue(column.PropertyName));
}
}
}
}
index++;
}
}
}
public override object GetValue(string name)
{
try
{
var model = this.Model as IObjectDataManager;
if (model != null)
{
return model.GetData(name);
}
else
{
return base.GetValue(name);
}
}
catch (Exception exception)
{
var message =
$"Can't GetValue from property {name} try adding the [IgnoreAttribute] to the property {exception.Message} {exception.StackTrace}";
LoggingService.SendToLog("DataCommand", message, LogType.Error);
}
return DBNull.Value;
}
//TODO TEST
public override IDataCommand<T> Count<TField>(Expression<Func<T, TField>> field)
{
this.SelectAll = false;
this.Columns.Clear();
string property = GetField(field);
this.Columns.Add(string.Format("COUNT(*) as {0}", property));
return this;
}
public override IDataCommand<T> Or(string column, string opperator, object value)
{
string columnText = column;
var columnObject = GetColumn(columnText);
if (columnObject != null)
{
columnText = columnObject.ColumnName;
}
return base.Or(columnText, opperator, value);
}
public override IDataCommand<T> And(string column, string opperator, object value)
{
string columnText = column;
var columnObject = GetColumn(columnText);
if (columnObject != null)
{
columnText = columnObject.ColumnName;
}
return base.And(columnText, opperator, value);
}
public override IDataCommand<T> Where(string column, string opperator, object value)
{
string columnText = column;
var columnObject = GetColumn(columnText);
if (columnObject != null)
{
columnText = columnObject.ColumnName;
}
return base.Where(columnText, opperator, value);
}
private IColumnMap GetColumn(string name)
{
GetTableMap();
if (this.TableMap != null)
{
var columnObject = TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name);
if (columnObject == null)
columnObject = TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == name);
if (columnObject != null)
{
return columnObject;
}
}
return null;
}
public IDataCommand<T> FromWhereColumnsMap2Model(string tableName = "", bool onlymapped = true)
{
this.From(tableName);
//TODO test
GetTableMap();
var columns = GetColumnAttributes();
foreach (var columnMap in columns)
{
bool addColumn = true;
if (onlymapped)
{
if (this.TableMap == null)
addColumn = false;
var column = this.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnMap.ColumnName);
if (column == null)
addColumn = false;
}
if (addColumn)
Column( columnMap.ColumnName);
}
this.SelectAll = false;
return this;
}
protected internal void BuildSqlParameters(IDbCommand command)
{
foreach (var dataParameter in this.Parameters)
{
var sqlparameter = dataParameter as SqlDataParameter;
if (sqlparameter == null)
throw new ApplicationException("Parameter is no SqlDataParameter");
var columnText = dataParameter.ColumnName.Replace("[", "").Replace("]", "");
if (this.TableMap != null)
{
var column = this.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnText);
if (column == null)
{
column = this.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == columnText);
if (column == null)
{
}
}
if (column != null)
{
var col = column as SqlColumnMap;
if (col != null)
{
sqlparameter.DbType = col.DbType;
sqlparameter.Size = col.Size;
sqlparameter.IsNullable = col.IsNullable;
sqlparameter.Size = col.Size;
sqlparameter.IsForeinKey = col.IsForeinKey;
sqlparameter.IsPrimaryKey = col.IsPrimaryKey;
}
}
}
if (sqlparameter.DbType != SqlDbType.Timestamp)
{
var value = sqlparameter.Value;
if (sqlparameter.Size > 0)
{
var valuestring = value.ToStringValue();
if (!string.IsNullOrEmpty(valuestring))
{
if (valuestring.Length > sqlparameter.Size)
{
throw new ApplicationException(string.Format("Property {0} value is bigger than database size {1} column name in {2} {3} Value {4} length is {5} column length is {6}"
, sqlparameter.PropertyName, sqlparameter.ColumnName, this.TabelName, valuestring, valuestring.Length, sqlparameter.Size, valuestring.Length));
}
}
}
if (sqlparameter.Value == null)
{
value = DBNull.Value;
}
else
{
switch (sqlparameter.DbType)
{
case SqlDbType.BigInt:
break;
case SqlDbType.Binary:
break;
case SqlDbType.Bit:
value = value
.ToStringValue()
.ToLower();
break;
case SqlDbType.Char:
break;
case SqlDbType.DateTime:
break;
case SqlDbType.Decimal:
break;
case SqlDbType.Float:
break;
case SqlDbType.Image:
break;
case SqlDbType.Int:
value = value.ToInt();
break;
case SqlDbType.Money:
break;
case SqlDbType.NChar:
break;
case SqlDbType.NText:
break;
case SqlDbType.NVarChar:
break;
case SqlDbType.Real:
break;
case SqlDbType.UniqueIdentifier:
if (value is string)
{
value = new Guid(value.ToStringValue());
}
break;
case SqlDbType.SmallDateTime:
break;
case SqlDbType.SmallInt:
break;
case SqlDbType.SmallMoney:
break;
case SqlDbType.Text:
break;
case SqlDbType.Timestamp:
break;
case SqlDbType.TinyInt:
break;
case SqlDbType.VarBinary:
break;
case SqlDbType.VarChar:
break;
case SqlDbType.Variant:
break;
case SqlDbType.Xml:
break;
case SqlDbType.Udt:
break;
case SqlDbType.Structured:
break;
case SqlDbType.Date:
break;
case SqlDbType.Time:
break;
case SqlDbType.DateTime2:
break;
case SqlDbType.DateTimeOffset:
break;
default:
break;
}
}
if (command is DbCommand)
{
var parameters = command.Parameters as DbParameterCollection;
var parameter = parameters.GetParameter(dataParameter.Name);
if (parameter != null)
{
parameter.Value = value;
}
else
{
parameter = new SqlParameter
{
ParameterName = sqlparameter.Name,
Value = value,
IsNullable = sqlparameter.IsNullable,
Direction = sqlparameter.Direction,
SourceColumn = sqlparameter.ColumnName,
SqlDbType = sqlparameter.DbType,
Size = dataParameter.Size
};
if (parameters != null)
{
parameters.Add(parameter);
}
}
}
}
else
{
this.Columns.Remove(dataParameter.ColumnName);
}
}
}
}
}
| |
// 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.Reflection;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Diagnostics.Tracing;
using Xunit;
using Sdt = SdtEventSources;
namespace BasicEventSourceTests
{
public class TestsManifestNegative
{
#region Message string building
public static string GetResourceString(string key, params object[] args)
{
string fmt = GetResourceStringFromReflection(key);
if (fmt != null)
return string.Format(fmt, args);
return key + " (" + string.Join(", ", args) + ")";
}
private static string GetResourceStringFromReflection(string key)
{
BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
if (!PlatformDetection.IsFullFramework)
{
Type sr = typeof(EventSource).Assembly.GetType("System.SR", throwOnError: true, ignoreCase: false);
PropertyInfo resourceProp = sr.GetProperty(key, flags);
return (string)resourceProp.GetValue(null);
}
Type[] paramsType = new Type[] { typeof(string) };
MethodInfo getResourceString = typeof(Environment).GetMethod("GetResourceString", flags, null, paramsType, null);
return (string)getResourceString.Invoke(null, new object[] { key });
}
#endregion
/// <summary>
/// These tests use the NuGet EventSource to validate *both* NuGet and BCL user-defined EventSources
/// For NuGet EventSources we validate both "runtime" and "validation" behavior
/// </summary>
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19091")]
[Fact]
public void Test_GenerateManifest_InvalidEventSources()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
// specify AllowEventSourceOverride - this is needed for Sdt event sources and won't make a difference for Sdt ones
var strictOptions = EventManifestOptions.Strict | EventManifestOptions.AllowEventSourceOverride;
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty));
Exception e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
// starting with NuGet we allow non-void returning methods as long as they have the [Event] attribute
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty));
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, strictOptions));
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.OutOfRangeKwdEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalKeywordsValue", "Kwd1", "0x100000000000"),
GetResourceString("EventSource_KeywordCollision", "Session3", "Kwd1", "0x100000000000")),
e.Message);
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
e = Assert.Throws<ArgumentException>(GetResourceString("EventSource_MaxChannelExceeded"),
() => EventSource.GenerateManifest(typeof(Sdt.TooManyChannelsEventSource), string.Empty));
#endif
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
e = Assert.Throws<ArgumentException>(GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage", "WriteInteger", "Admin"),
() => EventSource.GenerateManifest(typeof(Sdt.EventWithAdminChannelNoMessageEventSource), string.Empty, strictOptions));
#endif // USE_ETW
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty));
Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EnumKindMismatch", "Op1", "EventKeywords", "Opcodes"),
GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger")),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty));
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
Assert.Equal(String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
e = Assert.Throws<ArgumentException>(() => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using LeaflyTest.Areas.HelpPage.ModelDescriptions;
using LeaflyTest.Areas.HelpPage.Models;
namespace LeaflyTest.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using NUnit.Framework;
using System;
/// <summary>
/// Tests generated according to the W3C-Test.org page:
/// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-checkValidity.html
/// </summary>
[TestFixture]
public class ValidityCheckTests
{
static IDocument Html(String code)
{
return code.ToHtmlDocument();
}
[Test]
public void GetSubmissionReturnsNullWithInvalidForm()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.SetAttribute("maxLength", "4");
element.Value = "abcde";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
Assert.IsNotNull(fm);
fm.AppendChild(element);
document.Body.AppendChild(fm);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
Assert.IsNull(fm.GetSubmission(element));
}
[Test]
public void TestCheckvalidityInputText1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("text", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputText2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcdef";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputText3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "[A-Z]");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputText4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "text";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("text", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputSearch1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("search", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputSearch2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcdef";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputSearch3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "[A-Z]");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputSearch4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "search";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("search", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTel1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTel2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcdef";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTel3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "[A-Z]");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTel4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "tel";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("tel", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputPassword1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("password", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputPassword2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "4");
element.Value = "abcdef";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputPassword3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "[A-Z]");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputPassword4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "password";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("password", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputUrl1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("url", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputUrl2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "20");
element.Value = "http://www.example.com";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputUrl3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "http://www.example.com");
element.Value = "http://www.example.net";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputUrl4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputUrl5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "url";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("url", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputEmail1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("email", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputEmail2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("maxLength", "10");
element.Value = "test@example.com";
element.IsDirty = true;
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true) as HtmlInputElement;
fm.AppendChild(element2);
document.Body.AppendChild(fm);
element2.IsDirty = true;
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputEmail3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("pattern", "test@example.com");
element.Value = "test@example.net";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputEmail4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.Value = "abc";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputEmail5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "email";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("email", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDatetime1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDatetime2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "2000-01-01T12:00:00Z");
element.Value = "2001-01-01T12:00:00Z";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDatetime3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01T12:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDatetime4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "120000");
element.Value = "2001-01-01T12:03:00Z";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDatetime5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDate1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("date", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDate2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "2000-01-01");
element.Value = "2001-01-01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDate3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01");
element.Value = "2000-01-01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDate4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "172800000");
element.Value = "2001-01-03";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputDate5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputMonth1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("month", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputMonth2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "2000-01");
element.Value = "2001-01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputMonth3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01");
element.Value = "2000-01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputMonth4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "3");
element.Value = "2001-03";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputMonth5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputWeek1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("week", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputWeek2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "2000-W01");
element.Value = "2001-W01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputWeek3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W01");
element.Value = "2000-W01";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputWeek4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "1209600000");
element.Value = "2001-W03";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputWeek5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTime1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTime2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "12:00:00");
element.Value = "13:00:00";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTime3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "11:00:00";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTime4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "120000");
element.Value = "12:03:00";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputTime5()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputNumber1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("max", "5");
element.Value = "6";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputNumber2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5");
element.Value = "4";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputNumber3()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("step", "2");
element.Value = "3";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputNumber4()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputCheckbox1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "checkbox";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("checkbox", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputCheckbox2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "checkbox";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.SetAttribute("checked", null);
element.SetAttribute("name", "test1");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("checkbox", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputRadio1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "radio";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("radio", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputRadio2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "radio";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.SetAttribute("checked", null);
element.SetAttribute("name", "test1");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("radio", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputFile1()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "file";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("file", element.Type);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityInputFile2()
{
var document = Html("");
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "file";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.SetAttribute("files", "null");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual("file", element.Type);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvaliditySelect1()
{
var document = Html("");
var element = document.CreateElement("select") as HtmlSelectElement;
Assert.IsNotNull(element);
var option1 = document.CreateElement<IHtmlOptionElement>();
option1.Text = "test1";
option1.Value = "";
var option2 = document.CreateElement<IHtmlOptionElement>();
option2.Text = "test1";
option2.Value = "1";
element.AddOption(option1);
element.AddOption(option2);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvaliditySelect2()
{
var document = Html("");
var element = document.CreateElement("select") as HtmlSelectElement;
Assert.IsNotNull(element);
var option1 = document.CreateElement<IHtmlOptionElement>();
option1.Text = "test1";
option1.Value = "";
var option2 = document.CreateElement<IHtmlOptionElement>();
option2.Text = "test1";
option2.Value = "1";
element.AddOption(option1);
element.AddOption(option2);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityTextarea1()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual(true, element.CheckValidity());
Assert.AreEqual(true, fm.CheckValidity());
}
[Test]
public void TestCheckvalidityTextarea2()
{
var document = Html("");
var element = document.CreateElement("textarea") as HtmlTextAreaElement;
Assert.IsNotNull(element);
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("required", "required");
element.Value = "";
var fm = document.CreateElement("form") as IHtmlFormElement;
var element2 = element.Clone(true);
fm.AppendChild(element2);
document.Body.AppendChild(fm);
Assert.AreEqual(false, element.CheckValidity());
Assert.AreEqual(false, fm.CheckValidity());
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.Runtime.Controlling;
using Microsoft.Research.Naiad.DataStructures;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Frameworks.Reduction;
using Microsoft.Research.Naiad.Frameworks;
using Microsoft.Research.Naiad.Diagnostics;
namespace Microsoft.Research.Naiad.Dataflow
{
namespace Reporting
{
/// <summary>
/// The type of aggregation that is performed on a set of integers or doubles during reporting
/// </summary>
internal enum AggregateType
{
Sum, Min, Max, Average
}
/// <summary>
/// Interface used by vertex code to log messages and counters that are aggregated
/// and written out by centralized logging code when reporting is enabled.
/// </summary>
internal interface IReporting<T> where T : Time<T>
{
/// <summary>
/// Sends a log message to be written immediately to the 'out-of-band' logging subsystem. If
/// Configuration.DomainReporting is true, this will be written to a file called rtdomain.txt
/// at the root vertex's computer, otherwise it will be written to the console at the vertex's
/// local computer.
/// </summary>
void Log(string entry);
/// <summary>
/// Sends a log message to be written immediately to the inline logging subsystem that uses the graph's
/// time domain. If Configuration.InlineReporting is true, this will be written to a file called rtinline.txt
/// at the root vertex's computer, otherwise it will be written to the console at the vertex's
/// local computer. The log message is written out in the form "time.entry"
/// </summary>
void Log(string entry, T time);
/// <summary>
/// Incorporates value into the logical-time-based aggregation called name. If Configuration.InlineReporting and
/// Configuration.AggregateReporting are both true, then the final aggregate of all values with the same time will
/// be written to rtinline.txt at the root vertex's computer once all computation with that time has drained from
/// the system. This call is identical to logging an integer aggregate with a count of 1.
/// </summary>
void LogAggregate(string name, Reporting.AggregateType type, Int64 value, T time);
/// <summary>
/// Incorporates (value,count) into the logical-time-based aggregation called name. If Configuration.InlineReporting and
/// Configuration.AggregateReporting are both true, then the final aggregate of all values with the same time will
/// be written to rtinline.txt at the root vertex's computer once all computation with that time has drained from
/// the system. count is used only for aggregates of type Reporting.AggregateType.Average, for which the final
/// aggregate is Sum(values)/Sum(counts).
/// </summary>
void LogAggregate(string name, Reporting.AggregateType type, Int64 value, Int64 count, T time);
/// <summary>
/// Incorporates value into the logical-time-based aggregation called name. If Configuration.InlineReporting and
/// Configuration.AggregateReporting are both true, then the final aggregate of all values with the same time will
/// be written to rtinline.txt at the root vertex's computer once all computation with that time has drained from
/// the system. This call is identical to logging a double aggregate with a count of 1.0.
/// </summary>
void LogAggregate(string name, Reporting.AggregateType type, double value, T time);
/// <summary>
/// Incorporates (value,count) into the logical-time-based aggregation called name. If Configuration.InlineReporting and
/// Configuration.AggregateReporting are both true, then the final aggregate of all values with the same time will
/// be written to rtinline.txt at the root vertex's computer once all computation with that time has drained from
/// the system. count is used only for aggregates of type Reporting.AggregateType.Average, for which the final
/// aggregate is Sum(values)/Sum(counts).
/// </summary>
void LogAggregate(string name, Reporting.AggregateType type, double value, Int64 count, T time);
/// <summary>
/// Writes an array of log messages. This is equivalent to calling Log(entry, time) for every element in message,
/// but has better performance.
/// </summary>
void ForwardLog(Pair<string, T>[] message);
}
internal interface IReportingConnector<T> where T : Time<T>
{
void ConnectInline(Stream<string, T> sender);
void ConnectIntAggregator(Stream<Pair<string, ReportingRecord<Int64>>, T> sender);
void ConnectDoubleAggregator(Stream<Pair<string, ReportingRecord<double>>, T> sender);
}
internal interface IRootReporting : IReportingConnector<Epoch>
{
bool HasDomain { get; }
bool HasInline { get; }
bool HasAggregate { get; }
}
internal struct ReportingRecord<R>
{
public R payload;
public Int64 count;
public Reporting.AggregateType type;
public ReportingRecord(R r, Int64 c, Reporting.AggregateType t)
{
payload = r;
count = c;
type = t;
}
}
internal class IntReportingReducer : Microsoft.Research.Naiad.Frameworks.Reduction.IReducer<ReportingRecord<Int64>, ReportingRecord<Int64>, ReportingRecord<Int64>>
{
ReportingRecord<Int64> value;
public void InitialAdd(ReportingRecord<Int64> r)
{
value = r;
}
public void Add(ReportingRecord<Int64> r)
{
switch (r.type)
{
case Reporting.AggregateType.Sum:
case Reporting.AggregateType.Average:
value.payload += r.payload;
value.count += r.count;
break;
case Reporting.AggregateType.Min:
value.payload = Math.Min(value.payload, r.payload);
break;
case Reporting.AggregateType.Max:
value.payload = Math.Max(value.payload, r.payload);
break;
}
}
public void InitialCombine(ReportingRecord<Int64> r)
{
InitialAdd(r);
}
public void Combine(ReportingRecord<Int64> r)
{
Add(r);
}
public ReportingRecord<Int64> State()
{
return value;
}
public ReportingRecord<Int64> Value()
{
if (value.type == Reporting.AggregateType.Average)
{
value.payload /= value.count;
value.count = 1;
}
return value;
}
}
internal class DoubleReportingReducer : Microsoft.Research.Naiad.Frameworks.Reduction.IReducer<ReportingRecord<double>, ReportingRecord<double>, ReportingRecord<double>>
{
ReportingRecord<double> value;
public void InitialAdd(ReportingRecord<double> r)
{
value = r;
}
public void Add(ReportingRecord<double> r)
{
switch (r.type)
{
case Reporting.AggregateType.Sum:
case Reporting.AggregateType.Average:
value.payload += r.payload;
value.count += r.count;
break;
case Reporting.AggregateType.Min:
value.payload = Math.Min(value.payload, r.payload);
break;
case Reporting.AggregateType.Max:
value.payload = Math.Max(value.payload, r.payload);
break;
}
}
public void InitialCombine(ReportingRecord<double> r)
{
InitialAdd(r);
}
public void Combine(ReportingRecord<double> r)
{
Combine(r);
}
public ReportingRecord<double> State()
{
return value;
}
public ReportingRecord<double> Value()
{
if (value.type == Reporting.AggregateType.Average)
{
value.payload /= value.count;
value.count = 1;
}
return value;
}
}
internal class Reporting<T> : IReporting<T> where T : Time<T>
{
private readonly VertexContext<T> context;
private readonly InputVertex<string> rootVertex;
private readonly VertexOutputBuffer<string, T> inlineStatistics;
private readonly VertexOutputBuffer<Pair<string, ReportingRecord<double>>, T> aggregateDouble;
private readonly VertexOutputBuffer<Pair<string, ReportingRecord<Int64>>, T> aggregateInt;
public void Log(string s)
{
if (rootVertex == null)
{
Console.WriteLine(s);
}
else
{
rootVertex.OnNext(new[] { s });
}
}
public void Log(string s, T t)
{
string decorated = context.Vertex.ToString() + "<" + t.ToString() + ">" + ":" + s;
if (inlineStatistics == null)
{
Console.WriteLine(decorated);
}
else
{
inlineStatistics.GetBufferForTime(t).Send(decorated);
}
}
public void ForwardLog(Pair<string, T>[] message)
{
for (int i = 0; i < message.Length; i++)
this.inlineStatistics.GetBufferForTime(message[i].Second).Send(message[i].First);
this.inlineStatistics.Flush();
}
public void LogAggregate(string name, Reporting.AggregateType type, Int64 value, Int64 count, T time)
{
if (this.aggregateInt != null)
{
this.aggregateInt.GetBufferForTime(time).Send(name.PairWith(new ReportingRecord<Int64>(value, count, type)));
}
}
public void LogAggregate(string name, Reporting.AggregateType type, Int64 value, T time)
{
this.LogAggregate(name, type, value, 1, time);
}
public void LogAggregate(string name, Reporting.AggregateType type, double value, Int64 count, T time)
{
if (this.aggregateDouble != null)
{
this.aggregateDouble.GetBufferForTime(time).Send(name.PairWith(new ReportingRecord<double>(value, count, type)));
}
}
public void LogAggregate(string name, Reporting.AggregateType type, double value, T time)
{
this.LogAggregate(name, type, value, 1, time);
}
public Reporting(
VertexContext<T> c, Stream<string, T> inlineStats,
Stream<Pair<string, ReportingRecord<Int64>>, T> aggInt, Stream<Pair<string, ReportingRecord<double>>, T> aggDouble)
{
context = c;
if (c.parent.parent.manager.Reporting.HasDomain)
{
rootVertex = c.parent.parent.manager.Reporting.RootDomainVertex(c.Vertex.VertexId);
}
else
{
rootVertex = null;
}
if (inlineStats == null)
{
inlineStatistics = null;
}
else
{
inlineStatistics = new VertexOutputBuffer<string, T>(c.Vertex);
inlineStats.StageOutput.Register(inlineStatistics);
}
if (aggInt == null)
{
aggregateInt = null;
aggregateDouble = null;
}
else
{
aggregateInt = new VertexOutputBuffer<Pair<string, ReportingRecord<long>>, T>(c.Vertex);
aggInt.StageOutput.Register(aggregateInt);
aggregateDouble = new VertexOutputBuffer<Pair<string, ReportingRecord<double>>, T>(c.Vertex);
aggDouble.StageOutput.Register(aggregateDouble);
}
}
}
internal class RootReporting : IRootReporting
{
private readonly bool doingAggregate;
private readonly RootStatisticsStage domainReporter;
private readonly RootStatisticsStage inlineReporter;
internal readonly InputStage<string> domainReportingIngress;
public bool HasDomain
{
get { return domainReporter != null; }
}
public bool HasInline
{
get { return inlineReporter != null; }
}
public bool HasAggregate
{
get { return HasInline && doingAggregate; }
}
public void ConnectInline(Stream<string, Epoch> sender)
{
inlineReporter.ConnectInline(sender);
}
public void ConnectIntAggregator(Stream<Pair<string, ReportingRecord<Int64>>, Epoch> sender)
{
// do nothing since this is the head of the chain
}
public void ConnectDoubleAggregator(Stream<Pair<string, ReportingRecord<double>>, Epoch> sender)
{
// do nothing since this is the head of the chain
}
public InputVertex<string> RootDomainVertex(int index)
{
return domainReportingIngress.GetInputVertex(index);
}
public void ShutDown()
{
if (domainReporter != null)
{
if (!domainReportingIngress.IsCompleted)
{
Logging.Error("Statistics shutting down before domain input is completed");
}
domainReporter.ShutDown();
}
if (inlineReporter != null)
{
inlineReporter.ShutDown();
}
}
public RootReporting(TimeContextManager manager, bool makeDomain, bool makeInline, bool doAggregate)
{
if (makeDomain)
{
domainReportingIngress = manager.InternalComputation.NewInput<string>();
domainReporter = new RootStatisticsStage(
manager.MakeRawContextForScope<Epoch>("Domain Root"), "Domain Root Statistics", "rtdomain.txt");
domainReporter.ConnectInline(domainReportingIngress.Stream);
}
else
{
domainReportingIngress = null;
domainReporter = null;
}
if (makeInline)
{
inlineReporter = new RootStatisticsStage(
manager.MakeRawContextForScope<Epoch>("Inline Root"), "Inline Root Statistics", "rtinline.txt");
doingAggregate = doAggregate;
}
else
{
inlineReporter = null;
doingAggregate = false;
}
}
}
internal class RootStatisticsVertex : Microsoft.Research.Naiad.Dataflow.Vertex<Epoch>
{
private readonly StreamWriter output;
private readonly System.Diagnostics.Stopwatch timer;
public void OnRecv(Message<string, Epoch> message)
{
for (int i = 0; i < message.length; i++)
{
output.WriteLine("{0:D8}: {1}", timer.ElapsedMilliseconds, message.payload[i]);
}
}
public override void OnNotify(Epoch time)
{
// do nothing since epochs mean nothing in this context
}
public void FinalizeReporting()
{
output.Close();
}
public RootStatisticsVertex(int index, Stage<Epoch> parent, string outputFileName)
: base(index, parent)
{
output = new StreamWriter(outputFileName);
timer = new System.Diagnostics.Stopwatch();
timer.Start();
}
}
internal class RootStatisticsStage : IReportingConnector<Epoch>
{
private Stage<RootStatisticsVertex, Epoch> stage;
private readonly List<StageInput<string, Epoch>> receivers;
public IEnumerable<StageInput<string, Epoch>> Receivers
{
get { return receivers; }
}
public void ShutDown()
{
foreach (var s in stage.Vertices)
{
stage.GetVertex(s.VertexId).FinalizeReporting();
}
}
public void ConnectInline(Stream<string, Epoch> sender)
{
this.stage.NewInput(sender, (message, vertex) => vertex.OnRecv(message), null);
}
public void ConnectIntAggregator(Stream<Pair<string, ReportingRecord<Int64>>, Epoch> sender)
{
// do nothing since this is the head of the chain
}
public void ConnectDoubleAggregator(Stream<Pair<string, ReportingRecord<double>>, Epoch> sender)
{
// do nothing since this is the head of the chain
}
internal RootStatisticsStage(ITimeContext<Epoch> context, string name, string outputFile)
{
this.stage = new Stage<RootStatisticsVertex, Epoch>(new Placement.SingleVertex(0, 0), new TimeContext<Epoch>(context), Stage.OperatorType.Default, (i, v) => new RootStatisticsVertex(i, v, outputFile), name);
receivers = new List<StageInput<string, Epoch>>();
}
}
internal class AggregateStatisticsVertex<R, T> : Microsoft.Research.Naiad.Dataflow.Vertex<T>
where T : Time<T>
{
internal readonly VertexOutputBuffer<Pair<string, ReportingRecord<R>>, T> output;
public void OnRecv(Message<Pair<string, ReportingRecord<R>>, T> message)
{
for (int i = 0; i < message.length; i++)
{
string name = message.payload[i].First;
ReportingRecord<R> r = message.payload[i].Second;
if (r.type == Microsoft.Research.Naiad.Dataflow.Reporting.AggregateType.Average)
{
Context.Reporting.Log(name + ": " + r.payload + "," + r.count, message.time);
}
else
{
Context.Reporting.Log(name + ": " + r.payload, message.time);
}
}
output.Send(message);
}
public override void OnNotify(T time)
{
// do nothing since epochs mean nothing in this context
}
public AggregateStatisticsVertex(int index, Stage<T> parent)
: base(index, parent)
{
output = new VertexOutputBuffer<Pair<string, ReportingRecord<R>>, T>(this);
}
}
internal class AggregateStatisticsStage<R, T>
where T : Time<T>
{
private readonly Stage<AggregateStatisticsVertex<R, T>, T> stage;
private readonly List<StageInput<Pair<string, ReportingRecord<R>>, T>> inputs;
public IEnumerable<StageInput<Pair<string, ReportingRecord<R>>, T>> Inputs
{
get { return inputs; }
}
public Stream<Pair<string, ReportingRecord<R>>, T> Output;
public void ConnectTo(Stream<Pair<string, ReportingRecord<R>>, T> i)
{
//inputs.Add(this.NewInput(i));
inputs.Add(stage.NewInput(i, (message, vertex) => vertex.OnRecv(message), null));
}
internal AggregateStatisticsStage(ITimeContext<T> context, string name)
{
this.stage = new Stage<AggregateStatisticsVertex<R, T>, T>(new TimeContext<T>(context), (i, v) => new AggregateStatisticsVertex<R, T>(i, v), name);
Output = this.stage.NewOutputWithoutSealing(vertex => vertex.output, null);
inputs = new List<StageInput<Pair<string, ReportingRecord<R>>, T>>();
}
}
}
internal interface ITimeContextManager
{
InternalComputation InternalComputation { get; }
ITimeContext<T> MakeContextForScope<T>(string name, Reporting.IReportingConnector<T> downstreamConnector) where T : Time<T>;
ITimeContext<T> MakeRawContextForScope<T>(string name) where T : Time<T>;
ITimeContext<Epoch> RootContext { get; }
Reporting.IRootReporting RootStatistics { get; }
void ShutDown();
}
internal interface ITimeContext<T> where T : Time<T>
{
bool HasReporting { get; }
bool HasAggregate { get; }
IStageContext<T> MakeStageContext(string name);
IStageContext<T> MakeStageContext(string name, Stream<string, T> inlineStatsSender);
IStageContext<T> MakeStageContext(
string name, Stream<string, T> inlineStatsSender,
Stream<Pair<string, Reporting.ReportingRecord<Int64>>, T> aggInt, Stream<Pair<string, Reporting.ReportingRecord<double>>, T> aggDouble);
string Scope { get; }
ITimeContextManager Manager { get; }
}
/// <summary>
/// Represents a potentially nested scope in a dataflow computation, in which all messages have the same time type.
/// </summary>
/// <typeparam name="TTime">time type</typeparam>
public struct TimeContext<TTime> where TTime : Time<TTime>
{
internal ITimeContext<TTime> Context;
internal TimeContext(ITimeContext<TTime> context) { this.Context = context; }
}
internal interface IStageContext<T> where T : Time<T>
{
IVertexContext<T> MakeVertexContext(Vertex vertex);
ITimeContext<T> Parent { get; }
}
internal interface IVertexContext<T> where T : Time<T>
{
IStageContext<T> Parent { get; }
Reporting.IReporting<T> Reporting { get; }
}
internal class TimeContextManager : ITimeContextManager
{
private readonly InternalComputation internalComputation;
public InternalComputation InternalComputation { get { return this.internalComputation; } }
private ITimeContext<Epoch> rootContext;
public ITimeContext<Epoch> RootContext { get { return rootContext; } }
private Reporting.RootReporting reporting;
public Reporting.IRootReporting RootStatistics { get { return reporting; } }
internal Reporting.RootReporting Reporting { get { return reporting; } }
internal void InitializeReporting(bool makeDomain, bool makeInline, bool doAggregate)
{
this.reporting = new Reporting.RootReporting(this, makeDomain, makeInline, doAggregate);
this.rootContext = MakeContextForScope<Epoch>("Root", this.reporting);
}
public void ShutDown()
{
if (this.reporting != null)
{
this.reporting.ShutDown();
}
}
public ITimeContext<T> MakeRawContextForScope<T>(string name) where T : Time<T>
{
return new InternalTimeContext<T>(this, name, null, false);
}
public ITimeContext<T> MakeContextForScope<T>(string name, Reporting.IReportingConnector<T> downstreamConnector) where T : Time<T>
{
bool hasAggregate = this.reporting != null && this.reporting.HasAggregate;
return new InternalTimeContext<T>(this, name, downstreamConnector, hasAggregate);
}
internal TimeContextManager(InternalComputation g)
{
this.internalComputation = g;
this.rootContext = null;
this.reporting = null;
}
}
internal class InternalTimeContext<T> : ITimeContext<T>
where T : Time<T>
{
private Reporting.IReportingConnector<T> downstreamConnector;
internal Reporting.AggregateStatisticsStage<Int64, T> intAggregator;
internal Reporting.AggregateStatisticsStage<double, T> doubleAggregator;
private readonly string scope;
internal readonly TimeContextManager manager;
public ITimeContextManager Manager { get { return manager; } }
public bool HasAggregate
{
get { return intAggregator != null; }
}
public bool HasReporting
{
get { return downstreamConnector != null; }
}
public string Scope
{
get { return scope; }
}
public IStageContext<T> MakeStageContext(string name)
{
return new StageContext<T>(name, this, null, null, null);
}
public IStageContext<T> MakeStageContext(string name, Stream<string, T> inlineStats)
{
downstreamConnector.ConnectInline(inlineStats);
return new StageContext<T>(name, this, inlineStats, null, null);
}
public IStageContext<T> MakeStageContext(
string name, Stream<string, T> inlineStats,
Stream<Pair<string, Reporting.ReportingRecord<Int64>>, T> aggInt, Stream<Pair<string, Reporting.ReportingRecord<double>>, T> aggDouble)
{
downstreamConnector.ConnectInline(inlineStats);
return new StageContext<T>(name, this, inlineStats, aggInt, aggDouble);
}
public InternalTimeContext<T> CloneWithoutAggregate()
{
return new InternalTimeContext<T>(this.manager, this.scope, this.downstreamConnector, false);
}
void MakeAggregates()
{
var safeContext = this.CloneWithoutAggregate();
intAggregator = new Reporting.AggregateStatisticsStage<Int64, T>(safeContext, scope + ".IRI");
//intAggregator.Factory = (i => new Reporting.AggregateStatisticsVertex<Int64, T>(i, intAggregator));
downstreamConnector.ConnectIntAggregator(intAggregator.Output);
doubleAggregator = new Reporting.AggregateStatisticsStage<double, T>(safeContext, scope + ".IRD");
//doubleAggregator.Factory = (i => new Reporting.AggregateStatisticsVertex<double, T>(i, doubleAggregator));
downstreamConnector.ConnectDoubleAggregator(doubleAggregator.Output);
}
public InternalTimeContext(TimeContextManager m, string s, Reporting.IReportingConnector<T> downstreamConn, bool hasAgg)
{
scope = s;
manager = m;
downstreamConnector = downstreamConn;
if (hasAgg)
{
MakeAggregates();
}
else
{
intAggregator = null;
doubleAggregator = null;
}
}
}
internal class StageContext<T> : IStageContext<T> where T : Time<T>
{
internal readonly InternalTimeContext<T> parent;
internal readonly Stream<string, T> inlineStatistics;
internal readonly Stream<Pair<string, Reporting.ReportingRecord<Int64>>, T> aggregateInt;
internal readonly Stream<Pair<string, Reporting.ReportingRecord<double>>, T> aggregateDouble;
public ITimeContext<T> Parent
{
get { return parent; }
}
public IVertexContext<T> MakeVertexContext(Vertex parentVertex)
{
return new VertexContext<T>(this, parentVertex);
}
private void MakeAggregates(string name)
{
var safeContext = parent.CloneWithoutAggregate();
var intReduced = aggregateInt
.LocalTimeReduce<
Reporting.IntReportingReducer, Reporting.ReportingRecord<Int64>, Reporting.ReportingRecord<Int64>, Reporting.ReportingRecord<Int64>,
string, Pair<string, Reporting.ReportingRecord<Int64>>, T>(x => x.First, x => x.Second, () => new Reporting.IntReportingReducer(),
name + ".IRILR", null, null)
.LocalTimeCombine<
Reporting.IntReportingReducer, Reporting.ReportingRecord<Int64>, Reporting.ReportingRecord<Int64>, Reporting.ReportingRecord<Int64>,
string, T>(() => new Reporting.IntReportingReducer(), name + ".IRILC", x => x.First.GetHashCode());
var intReporter = new Reporting.AggregateStatisticsStage<Int64, T>(safeContext, name + ".IRI");
//intReporter.Factory = (i => new Reporting.AggregateStatisticsVertex<Int64, T>(i, intReporter));
intReporter.ConnectTo(intReduced);
parent.intAggregator.ConnectTo(intReduced);
var doubleReduced = aggregateDouble
.LocalTimeReduce<
Reporting.DoubleReportingReducer, Reporting.ReportingRecord<double>, Reporting.ReportingRecord<double>, Reporting.ReportingRecord<double>,
string, Pair<string, Reporting.ReportingRecord<double>>, T>(x => x.First, x => x.Second, () => new Reporting.DoubleReportingReducer(),
name + ".IRDLR", null, null)
.LocalTimeCombine<
Reporting.DoubleReportingReducer, Reporting.ReportingRecord<double>, Reporting.ReportingRecord<double>, Reporting.ReportingRecord<double>,
string, T>(() => new Reporting.DoubleReportingReducer(), name + ".IRDLC", x => x.First.GetHashCode());
var doubleReporter = new Reporting.AggregateStatisticsStage<double, T>(safeContext, name + ".IRD");
//doubleReporter.Factory = (i => new Reporting.AggregateStatisticsVertex<double, T>(i, doubleReporter));
doubleReporter.ConnectTo(doubleReduced);
parent.doubleAggregator.ConnectTo(doubleReduced);
}
public StageContext(
string name, InternalTimeContext<T> p, Stream<string, T> inlineStats,
Stream<Pair<string, Reporting.ReportingRecord<Int64>>, T> aggInt, Stream<Pair<string, Reporting.ReportingRecord<double>>, T> aggDouble)
{
parent = p;
inlineStatistics = inlineStats;
aggregateInt = aggInt;
aggregateDouble = aggDouble;
if (aggregateInt != null)
{
MakeAggregates(name);
}
}
}
internal class VertexContext<T> : IVertexContext<T> where T : Time<T>
{
private readonly Vertex vertex;
internal readonly StageContext<T> parent;
private readonly Reporting.Reporting<T> reporting;
public Vertex Vertex
{
get { return vertex; }
}
public IStageContext<T> Parent
{
get { return parent; }
}
public Reporting.IReporting<T> Reporting
{
get { return reporting; }
}
public VertexContext(StageContext<T> p, Vertex s)
{
parent = p;
vertex = s;
if (parent.parent.manager.Reporting == null)
{
reporting = null;
}
else
{
reporting = new Reporting.Reporting<T>(this, parent.inlineStatistics, parent.aggregateInt, parent.aggregateDouble);
}
}
}
}
| |
// 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.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Microsoft.SqlServer.Server
{
public class SqlDataRecord
{
private SmiRecordBuffer _recordBuffer;
private SmiExtendedMetaData[] _columnSmiMetaData;
private SmiEventSink_Default _eventSink;
private SqlMetaData[] _columnMetaData;
private FieldNameLookup _fieldNameLookup;
private bool _usesStringStorageForXml;
private static readonly SmiMetaData s_maxNVarCharForXml = new SmiMetaData(SqlDbType.NVarChar, SmiMetaData.UnlimitedMaxLengthIndicator,
SmiMetaData.DefaultNVarChar_NoCollation.Precision,
SmiMetaData.DefaultNVarChar_NoCollation.Scale,
SmiMetaData.DefaultNVarChar.LocaleId,
SmiMetaData.DefaultNVarChar.CompareOptions
);
public virtual int FieldCount
{
get
{
EnsureSubclassOverride();
return _columnMetaData.Length;
}
}
public virtual String GetName(int ordinal)
{
EnsureSubclassOverride();
return GetSqlMetaData(ordinal).Name;
}
public virtual String GetDataTypeName(int ordinal)
{
EnsureSubclassOverride();
SqlMetaData metaData = GetSqlMetaData(ordinal);
if (SqlDbType.Udt == metaData.SqlDbType)
{
Debug.Assert(false, "Udt is not supported");
return null;
}
else
{
return MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, false).TypeName;
}
}
public virtual Type GetFieldType(int ordinal)
{
EnsureSubclassOverride();
{
SqlMetaData md = GetSqlMetaData(ordinal);
return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).ClassType;
}
}
public virtual Object GetValue(int ordinal)
{
EnsureSubclassOverride();
SmiMetaData metaData = GetSmiMetaData(ordinal);
return ValueUtilsSmi.GetValue200(
_eventSink,
_recordBuffer,
ordinal,
metaData
);
}
public virtual int GetValues(object[] values)
{
EnsureSubclassOverride();
if (null == values)
{
throw ADP.ArgumentNull(nameof(values));
}
int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount;
for (int i = 0; i < copyLength; i++)
{
values[i] = GetValue(i);
}
return copyLength;
}
public virtual int GetOrdinal(string name)
{
EnsureSubclassOverride();
if (null == _fieldNameLookup)
{
string[] names = new string[FieldCount];
for (int i = 0; i < names.Length; i++)
{
names[i] = GetSqlMetaData(i).Name;
}
_fieldNameLookup = new FieldNameLookup(names, -1);
}
return _fieldNameLookup.GetOrdinal(name);
}
public virtual object this[int ordinal]
{
get
{
EnsureSubclassOverride();
return GetValue(ordinal);
}
}
public virtual object this[String name]
{
get
{
EnsureSubclassOverride();
return GetValue(GetOrdinal(name));
}
}
public virtual bool GetBoolean(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual byte GetByte(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length, true);
}
public virtual char GetChar(int ordinal)
{
EnsureSubclassOverride();
throw ADP.NotSupported();
}
public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
}
public virtual Guid GetGuid(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual Int16 GetInt16(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual Int32 GetInt32(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual Int64 GetInt64(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual float GetFloat(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual double GetDouble(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual string GetString(int ordinal)
{
EnsureSubclassOverride();
SmiMetaData colMeta = GetSmiMetaData(ordinal);
if (_usesStringStorageForXml && SqlDbType.Xml == colMeta.SqlDbType)
{
return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, s_maxNVarCharForXml);
}
else
{
return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
}
public virtual Decimal GetDecimal(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual DateTime GetDateTime(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual DateTimeOffset GetDateTimeOffset(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual TimeSpan GetTimeSpan(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual bool IsDBNull(int ordinal)
{
EnsureSubclassOverride();
ThrowIfInvalidOrdinal(ordinal);
return ValueUtilsSmi.IsDBNull(_eventSink, _recordBuffer, ordinal);
}
//
// ISqlRecord implementation
//
public virtual SqlMetaData GetSqlMetaData(int ordinal)
{
EnsureSubclassOverride();
return _columnMetaData[ordinal];
}
public virtual Type GetSqlFieldType(int ordinal)
{
EnsureSubclassOverride();
SqlMetaData md = GetSqlMetaData(ordinal);
return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).SqlType;
}
public virtual object GetSqlValue(int ordinal)
{
EnsureSubclassOverride();
SmiMetaData metaData = GetSmiMetaData(ordinal);
return ValueUtilsSmi.GetSqlValue200(_eventSink, _recordBuffer, ordinal, metaData);
}
public virtual int GetSqlValues(object[] values)
{
EnsureSubclassOverride();
if (null == values)
{
throw ADP.ArgumentNull(nameof(values));
}
int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount;
for (int i = 0; i < copyLength; i++)
{
values[i] = GetSqlValue(i);
}
return copyLength;
}
public virtual SqlBinary GetSqlBinary(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlBytes GetSqlBytes(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlXml GetSqlXml(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlBoolean GetSqlBoolean(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlByte GetSqlByte(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlChars GetSqlChars(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlInt16 GetSqlInt16(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlInt32 GetSqlInt32(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlInt64 GetSqlInt64(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlSingle GetSqlSingle(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlDouble GetSqlDouble(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlMoney GetSqlMoney(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlDateTime GetSqlDateTime(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlDecimal GetSqlDecimal(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlString GetSqlString(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
public virtual SqlGuid GetSqlGuid(int ordinal)
{
EnsureSubclassOverride();
return ValueUtilsSmi.GetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
}
//
// ISqlUpdateableRecord Implementation
//
public virtual int SetValues(params object[] values)
{
EnsureSubclassOverride();
if (null == values)
{
throw ADP.ArgumentNull(nameof(values));
}
// Allow values array longer than FieldCount, just ignore the extra cells.
int copyLength = (values.Length > FieldCount) ? FieldCount : values.Length;
ExtendedClrTypeCode[] typeCodes = new ExtendedClrTypeCode[copyLength];
// Verify all data values as acceptable before changing current state.
for (int i = 0; i < copyLength; i++)
{
SqlMetaData metaData = GetSqlMetaData(i);
typeCodes[i] = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
metaData.SqlDbType, false /* isMultiValued */, values[i]
);
if (ExtendedClrTypeCode.Invalid == typeCodes[i])
{
throw ADP.InvalidCast();
}
}
// Now move the data (it'll only throw if someone plays with the values array between
// the validation loop and here, or if an invalid UDT was sent).
for (int i = 0; i < copyLength; i++)
{
ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, i, GetSmiMetaData(i), values[i], typeCodes[i], 0, 0, null);
}
return copyLength;
}
public virtual void SetValue(int ordinal, object value)
{
EnsureSubclassOverride();
SqlMetaData metaData = GetSqlMetaData(ordinal);
ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
metaData.SqlDbType, false /* isMultiValued */, value
);
if (ExtendedClrTypeCode.Invalid == typeCode)
{
throw ADP.InvalidCast();
}
ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value, typeCode, 0, 0, null);
}
public virtual void SetBoolean(int ordinal, bool value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetByte(int ordinal, byte value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
}
public virtual void SetChar(int ordinal, char value)
{
EnsureSubclassOverride();
throw ADP.NotSupported();
}
public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
}
public virtual void SetInt16(int ordinal, System.Int16 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetInt32(int ordinal, System.Int32 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetInt64(int ordinal, System.Int64 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetFloat(int ordinal, float value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetDouble(int ordinal, double value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetString(int ordinal, string value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetDecimal(int ordinal, Decimal value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetDateTime(int ordinal, DateTime value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetTimeSpan(int ordinal, TimeSpan value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetDateTimeOffset(int ordinal, DateTimeOffset value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetDBNull(int ordinal)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetDBNull(_eventSink, _recordBuffer, ordinal, true);
}
public virtual void SetGuid(int ordinal, Guid value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlBoolean(int ordinal, SqlBoolean value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlByte(int ordinal, SqlByte value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlInt16(int ordinal, SqlInt16 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlInt32(int ordinal, SqlInt32 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlInt64(int ordinal, SqlInt64 value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlSingle(int ordinal, SqlSingle value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlDouble(int ordinal, SqlDouble value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlMoney(int ordinal, SqlMoney value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlDateTime(int ordinal, SqlDateTime value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlXml(int ordinal, SqlXml value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlDecimal(int ordinal, SqlDecimal value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlString(int ordinal, SqlString value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlBinary(int ordinal, SqlBinary value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlGuid(int ordinal, SqlGuid value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlChars(int ordinal, SqlChars value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
public virtual void SetSqlBytes(int ordinal, SqlBytes value)
{
EnsureSubclassOverride();
ValueUtilsSmi.SetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
}
//
// SqlDataRecord public API
//
public SqlDataRecord(params SqlMetaData[] metaData)
{
// Initial consistency check
if (null == metaData)
{
throw ADP.ArgumentNull(nameof(metaData));
}
_columnMetaData = new SqlMetaData[metaData.Length];
_columnSmiMetaData = new SmiExtendedMetaData[metaData.Length];
for (int i = 0; i < _columnSmiMetaData.Length; i++)
{
if (null == metaData[i])
{
throw ADP.ArgumentNull($"{nameof(metaData)}[{i}]");
}
_columnMetaData[i] = metaData[i];
_columnSmiMetaData[i] = MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(_columnMetaData[i]);
}
_eventSink = new SmiEventSink_Default();
_recordBuffer = new MemoryRecordBuffer(_columnSmiMetaData);
_usesStringStorageForXml = true;
_eventSink.ProcessMessagesAndThrow();
}
internal SqlDataRecord(SmiRecordBuffer recordBuffer, params SmiExtendedMetaData[] metaData)
{
Debug.Assert(null != recordBuffer, "invalid attempt to instantiate SqlDataRecord with null SmiRecordBuffer");
Debug.Assert(null != metaData, "invalid attempt to instantiate SqlDataRecord with null SmiExtendedMetaData[]");
_columnMetaData = new SqlMetaData[metaData.Length];
_columnSmiMetaData = new SmiExtendedMetaData[metaData.Length];
for (int i = 0; i < _columnSmiMetaData.Length; i++)
{
_columnSmiMetaData[i] = metaData[i];
_columnMetaData[i] = MetaDataUtilsSmi.SmiExtendedMetaDataToSqlMetaData(_columnSmiMetaData[i]);
}
_eventSink = new SmiEventSink_Default();
_recordBuffer = recordBuffer;
_eventSink.ProcessMessagesAndThrow();
}
//
// SqlDataRecord private members
//
internal SmiRecordBuffer RecordBuffer
{ // used by SqlPipe
get
{
return _recordBuffer;
}
}
internal SqlMetaData[] InternalGetMetaData()
{
return _columnMetaData;
}
internal SmiExtendedMetaData[] InternalGetSmiMetaData()
{
return _columnSmiMetaData;
}
internal SmiExtendedMetaData GetSmiMetaData(int ordinal)
{
return _columnSmiMetaData[ordinal];
}
internal void ThrowIfInvalidOrdinal(int ordinal)
{
if (0 > ordinal || FieldCount <= ordinal)
{
throw ADP.IndexOutOfRange(ordinal);
}
}
private void EnsureSubclassOverride()
{
if (null == _recordBuffer)
{
throw SQL.SubclassMustOverride();
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DifferenceFinders.cs" company="NFluent">
// Copyright 2021 Cyrille DUPUYDAUBY
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NFluent.Helpers
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Extensions;
using Kernel;
internal static class DifferenceFinders
{
[Flags]
internal enum Option
{
Detailed=1,
Fast = 2,
Equivalence = 4
}
private class ReferenceEqualityComparer : IEqualityComparer<object>
{
public new bool Equals(object x, object y) => ReferenceEquals(x, y);
public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
}
private static readonly IEqualityComparer<object> ReferenceComparer = new ReferenceEqualityComparer();
internal static DifferenceDetails ValueDifference<TA, TE>(TA firstItem,
string firstName,
TE otherItem,
Option options = Option.Detailed)
{
return ValueDifference(firstItem,
firstName,
otherItem,
EnumerableExtensions.NullIndex,
EnumerableExtensions.NullIndex,
new Dictionary<object, object>(1, ReferenceComparer),
options);
}
/// <summary>
/// Check Equality between actual and expected and provides details regarding differences, if any.
/// </summary>
/// <remarks>
/// Is recursive.
/// Algorithm focuses on value comparison, to better match expectations. Here is a summary of the logic:
/// 1. deals with expected = null case
/// 2. tries Equals, if success, values are considered equals
/// 3. if there is recursion (self referencing object), values are assumed as different
/// 4. if both values are numerical, compare them after conversion if needed.
/// 5. if expected is an anonymous type, use a property based comparison
/// 6. if both are enumerations, perform enumeration comparison
/// 7. report values as different.
/// </remarks>
/// <typeparam name="TA">type of the actual value</typeparam>
/// <typeparam name="TE">type of the expected value</typeparam>
/// <param name="actual">actual value</param>
/// <param name="firstName">name/label to use for messages</param>
/// <param name="expected">expected value</param>
/// <param name="refIndex">reference index (for collections)</param>
/// <param name="expectedIndex">index in the expected collections</param>
/// <param name="firstSeen">track recursion</param>
/// <param name="options">scan options <see cref="Option"/></param>
/// <returns></returns>
private static DifferenceDetails ValueDifference<TA, TE>(TA actual,
string firstName,
TE expected,
long refIndex,
long expectedIndex,
IDictionary<object, object> firstSeen,
Option options)
{
// handle expected null case first
if (expected == null)
{
return actual == null
? null
: DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, null, refIndex, expectedIndex);
}
// if both equals from a BCL perspective, we are done.
if (EqualityHelper.CustomEquals(actual, expected))
{
return null;
}
// handle actual is null
if (actual == null)
{
return DifferenceDetails.DoesNotHaveExpectedValue(firstName, null, expected, refIndex, expectedIndex);
}
// do not recurse
if (firstSeen.ContainsKey(actual))
{
return ReferenceEquals(firstSeen[actual], expected) ? null : DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, refIndex, expectedIndex);
}
firstSeen = new Dictionary<object, object>(firstSeen, ReferenceComparer) {[actual] = expected};
// deals with numerical values
var type = expected.GetType();
var commonType = actual.GetType().FindCommonNumericalType(type);
// we silently convert numerical values
if (commonType != null)
{
return NumericalValueDifference(actual, firstName, expected, refIndex, expectedIndex, commonType);
}
if (type.TypeIsAnonymous())
{
return AnonymousTypeDifference(actual, firstName, expected, type);
}
// handle enumeration
if (actual.IsAnEnumeration(false) && expected.IsAnEnumeration(false))
{
return ValueDifferenceEnumerable(actual as IEnumerable,
firstName,
expected as IEnumerable,
refIndex,
expectedIndex,
firstSeen,
options);
}
return DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, refIndex , expectedIndex);
}
// compare to an expected anonymous type
private static DifferenceDetails AnonymousTypeDifference<TA, TE>(TA actual, string firstname, TE expected, Type type)
{
var criteria = new ClassMemberCriteria(BindingFlags.Instance|BindingFlags.Public);
// anonymous types only have public properties
criteria.CaptureProperties();
// use field based comparison
var wrapper = ReflectionWrapper.BuildFromInstance(type, expected, criteria);
var actualWrapped = ReflectionWrapper.BuildFromInstance(actual.GetType(), actual, criteria);
var differences = actualWrapped.MemberMatches(wrapper).Where(match => !match.DoValuesMatches).Select(DifferenceDetails.FromMatch).ToList();
return DifferenceDetails.DoesNotHaveExpectedDetails(firstname, actual, expected, 0, 0, differences);
}
// compare to a numerical difference
private static DifferenceDetails NumericalValueDifference<TA, TE>(TA actual,
string firstName,
TE expected,
long refIndex,
long expectedIndex,
Type commonType)
{
var convertedActual = Convert.ChangeType(actual, commonType);
var convertedExpected = Convert.ChangeType(expected, commonType);
return convertedExpected.Equals(convertedActual) ? null :
DifferenceDetails.DoesNotHaveExpectedValue(firstName, actual, expected, refIndex, expectedIndex);
}
private static DifferenceDetails ValueDifferenceDictionary(IReadOnlyDictionary<object, object> sutDictionary,
string sutName,
IReadOnlyDictionary<object, object> expectedDictionary,
long refIndex,
long expectedIndex,
IDictionary<object, object> firstItemsSeen,
Option options)
{
var index = 0L;
var valueDifferences = new List<DifferenceDetails>();
var equivalent = true;
var unexpectedKeys = sutDictionary.Keys.Where(k => !expectedDictionary.ContainsKey(k)).ToList();
if (options.HasFlag(Option.Fast) && unexpectedKeys.Count > 0)
{
return DifferenceDetails.DoesNotHaveExpectedValue(sutName, sutDictionary, expectedDictionary, refIndex, expectedIndex);
}
var sutIndexes = new Dictionary<object, long>(sutDictionary.Count);
var sutIndex= 0;
foreach (var sutDictionaryKey in sutDictionary.Keys)
{
sutIndexes[sutDictionaryKey] = sutIndex++;
}
foreach (var keyValuePair in expectedDictionary)
{
if (!sutDictionary.ContainsKey(keyValuePair.Key))
{
if (unexpectedKeys.Count > 0)
{
var unexpectedKey = unexpectedKeys[0];
valueDifferences.Add(DifferenceDetails.WasFoundInsteadOf(
sutName,
new DictionaryEntry(unexpectedKey, sutDictionary[unexpectedKey]),
new DictionaryEntry(keyValuePair.Key, keyValuePair.Value),
index));
unexpectedKeys.RemoveAt(0);
}
else
{
valueDifferences.Add(DifferenceDetails.WasNotFound(
$"{sutName}[{keyValuePair.Key.ToStringProperlyFormatted()}]",
new DictionaryEntry(keyValuePair.Key, keyValuePair.Value),
index));
}
equivalent = false;
}
else
{
var itemDiffs = ValueDifference(sutDictionary[keyValuePair.Key],
$"{sutName}[{keyValuePair.Key.ToStringProperlyFormatted()}]",
keyValuePair.Value,
sutIndexes[keyValuePair.Key],
index,
firstItemsSeen,
options);
if (itemDiffs != null)
{
if (options.HasFlag(Option.Fast))
{
return DifferenceDetails.DoesNotHaveExpectedValue(sutName, sutDictionary, expectedDictionary, refIndex, expectedIndex);
}
if (!itemDiffs.IsEquivalent())
{
equivalent = false;
}
valueDifferences.Add(itemDiffs);
}
}
index++;
}
foreach (var unexpectedKey in unexpectedKeys)
{
equivalent = false;
valueDifferences.Add(DifferenceDetails.WasNotExpected(
$"{sutName}[{unexpectedKey.ToStringProperlyFormatted()}]",
sutDictionary[unexpectedKey], index));
}
if (valueDifferences.Count == 0)
{
return null;
}
return equivalent ?
DifferenceDetails.DoesNotHaveExpectedDetailsButIsEquivalent(sutName, sutDictionary, expectedDictionary, refIndex, expectedIndex, valueDifferences)
: DifferenceDetails.DoesNotHaveExpectedDetails(sutName, sutDictionary, expectedDictionary, refIndex, expectedIndex, valueDifferences);
}
private static DifferenceDetails ValueDifferenceArray(Array firstArray,
string firstName,
Array secondArray,
long sutIndex,
long expectedIndex,
IDictionary<object, object> firstSeen,
Option options)
{
if (firstArray.Rank != secondArray.Rank)
{
return DifferenceDetails.DoesNotHaveExpectedAttribute($"{firstName}.Rank",
firstArray.Rank, secondArray.Rank);
}
for (var i = 0; i < firstArray.Rank; i++)
{
if (firstArray.SizeOfDimension(i) == secondArray.SizeOfDimension(i))
{
continue;
}
return DifferenceDetails.DoesNotHaveExpectedAttribute($"{firstName}.Dimension({i})",
firstArray.SizeOfDimension(i),
secondArray.SizeOfDimension(i));
}
return ScanEnumeration(firstArray, secondArray, firstName, index =>
{
var temp = index;
var indices = new long[firstArray.Rank];
for (var j = 0; j < firstArray.Rank; j++)
{
var currentIndex = temp % firstArray.SizeOfDimension(j);
indices[firstArray.Rank - j - 1] = currentIndex;
temp /= firstArray.SizeOfDimension(j);
}
return $"{firstName}[{string.Join(",", indices.Select(x => x.ToString()).ToArray())}]";
},
sutIndex,
expectedIndex,
firstSeen,
options);
}
private static DifferenceDetails ValueDifferenceEnumerable(IEnumerable firstItem,
string firstName,
IEnumerable otherItem,
long sutIndex,
long expectedIndex,
IDictionary<object, object> firstSeen,
Option options)
{
if (firstItem.GetType().IsArray && otherItem.GetType().IsArray)
{
return ValueDifferenceArray(firstItem as Array,
firstName,
otherItem as Array,
sutIndex,
expectedIndex,
firstSeen,
options);
}
var dictionary = DictionaryExtensions.WrapDictionary<object, object>(otherItem);
if (dictionary != null)
{
var wrapDictionary = DictionaryExtensions.WrapDictionary<object, object>(firstItem);
if (wrapDictionary != null)
{
return ValueDifferenceDictionary(wrapDictionary, firstName, dictionary, sutIndex, expectedIndex, firstSeen, options);
}
}
return ScanEnumeration(firstItem, otherItem, firstName, x => $"{firstName}[{x}]", sutIndex, expectedIndex, firstSeen, options);
}
private static DifferenceDetails ScanEnumeration(
IEnumerable actualEnumerable,
IEnumerable expectedEnumerable,
string firstName,
Func<long, string> namingCallback,
long sutIndex,
long expectedIndex,
IDictionary<object, object> firstSeen,
Option options)
{
var index = 0L;
var expected = new Dictionary<long, object>();
var unexpected = new Dictionary<long, object>();
var aggregatedDifferences = new Dictionary<long, DifferenceDetails>();
var aggregatedEquivalenceErrors = new Dictionary<long, DifferenceDetails>();
var valueDifferences = new List<DifferenceDetails>();
var scanner = expectedEnumerable.GetEnumerator();
var isEquivalent = true;
var ordered = !options.HasFlag(Option.Equivalence) && (!expectedEnumerable.GetType().IsACollection() || expectedEnumerable.GetType().IsAList());
foreach (var actualItem in actualEnumerable)
{
var firstItemName = namingCallback(index);
if (!scanner.MoveNext())
{
valueDifferences.Add(DifferenceDetails.WasNotExpected(firstItemName, actualItem, index));
unexpected.Add(index, actualItem);
if (options.HasFlag(Option.Fast))
{
return DifferenceDetails.DoesNotHaveExpectedValue(firstName, actualEnumerable, expectedEnumerable, sutIndex, expectedIndex);
}
continue;
}
var aggregatedDifference = ValueDifference(actualItem, firstItemName, scanner.Current, index, index, firstSeen, options);
if (aggregatedDifference != null)
{
if (ordered)
{
if (options.HasFlag(Option.Fast))
{
return DifferenceDetails.DoesNotHaveExpectedValue(firstName, actualEnumerable, expectedEnumerable, sutIndex, expectedIndex);
}
aggregatedDifferences.Add(index, aggregatedDifference);
}
if (!aggregatedDifference.IsEquivalent())
{
// try to see it was at a different position
var entryInCache = expected.Where(pair => EqualityHelper.FluentEquivalent(pair.Value, actualItem));
if (entryInCache.Any())
{
var expectedEntryIndex = entryInCache.First().Key;
if (ordered)
{
// we found the value at another index
aggregatedEquivalenceErrors.Add(index,
DifferenceDetails.WasFoundElseWhere(firstItemName, actualItem, expectedEntryIndex, index));
aggregatedDifferences.Remove(index);
}
expected.Remove(expectedEntryIndex);
}
else
{
// store it in case this is a needed entry
unexpected.Add(index, actualItem);
}
// what about the expected value
var indexInCache = unexpected.Where(pair => EqualityHelper.FluentEquivalent(pair.Value, scanner.Current));
if (indexInCache.Any())
{
var actualIndex = indexInCache.First().Key;
if (ordered)
{
aggregatedEquivalenceErrors.Add(actualIndex, DifferenceDetails.WasFoundElseWhere(
namingCallback(actualIndex),
scanner.Current, index, actualIndex));
aggregatedDifferences.Remove(actualIndex);
}
unexpected.Remove(actualIndex);
}
else
{
expected.Add(index, scanner.Current);
}
}
}
index++;
}
// several entries appear to be missing
while (scanner.MoveNext())
{
if (options.HasFlag(Option.Fast))
{
return DifferenceDetails.DoesNotHaveExpectedValue(firstName, actualEnumerable, expectedEnumerable, sutIndex, expectedIndex);
}
valueDifferences.Add(DifferenceDetails.WasNotFound(namingCallback(index), scanner.Current, index));
isEquivalent = false;
}
if (isEquivalent)
{
isEquivalent = expected.Count == 0 && unexpected.Count == 0;
}
// for equivalency, we have a bunch of different entries
if (!ordered)
{
while (expected.Count > 0 && unexpected.Count > 0)
{
var unexpectedEntry = unexpected.First();
var expectedEntryIndex = unexpectedEntry.Key;
if (!expected.TryGetValue(unexpectedEntry.Key, out var expectedEntryObject))
{
expectedEntryIndex = expected.Keys.First();
expectedEntryObject = expected[expectedEntryIndex];
}
var differenceDetails = ValueDifference(unexpectedEntry.Value, namingCallback(unexpectedEntry.Key), expectedEntryObject, unexpectedEntry.Key, expectedIndex, firstSeen, options);
if (differenceDetails.Count == 0)
{
// if there is no detailed difference, just describe a general one
differenceDetails = DifferenceDetails.WasFoundInsteadOf(namingCallback(unexpectedEntry.Key),
unexpectedEntry.Value, expectedEntryObject, unexpectedEntry.Key, expectedEntryIndex);
}
valueDifferences.Add(differenceDetails);
expected.Remove(expectedEntryIndex);
unexpected.Remove(unexpectedEntry.Key);
}
}
valueDifferences.AddRange(aggregatedDifferences.Values);
valueDifferences.AddRange(aggregatedEquivalenceErrors.Values);
if (valueDifferences.Count == 0)
{
return null;
}
valueDifferences = valueDifferences.OrderBy(d => d.ActualIndex).ToList();
return isEquivalent ?
DifferenceDetails.DoesNotHaveExpectedDetailsButIsEquivalent(firstName, actualEnumerable, expectedEnumerable, sutIndex, expectedIndex, valueDifferences)
: DifferenceDetails.DoesNotHaveExpectedDetails(firstName, actualEnumerable, expectedEnumerable, sutIndex, expectedIndex, valueDifferences);
}
}
}
| |
#region License, Terms and Conditions
//
// Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
// Written by Atif Aziz (atif.aziz@skybow.com)
// Copyright (c) 2005 Atif Aziz. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace EZOper.NetSiteUtilities.Jayrock
{
#region Imports
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
#endregion
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only
/// access to JSON data over JSON text (RFC 4627).
/// </summary>
public sealed class JsonTextReader : JsonReaderBase
{
private BufferedCharReader _reader;
private Stack _stack;
private delegate JsonToken Continuation();
private Continuation _methodParse;
private Continuation _methodParseArrayFirst;
private Continuation _methodParseArrayNext;
private Continuation _methodParseObjectMember;
private Continuation _methodParseObjectMemberValue;
private Continuation _methodParseNextMember;
public JsonTextReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = new BufferedCharReader(reader);
Push(ParseMethod);
}
/// <summary>
/// Reads the next token and returns it.
/// </summary>
protected override JsonToken ReadTokenImpl()
{
if (_stack == null)
{
return JsonToken.EOF();
}
else if (_stack.Count == 0)
{
_stack = null;
_reader = null;
return JsonToken.EOF();
}
else
{
return Pop()();
}
}
/// <summary>
/// Parses the next token from the input and returns it.
/// </summary>
private JsonToken Parse()
{
char ch = NextClean();
//
// String
//
if (ch == '"' || ch == '\'')
{
return Yield(JsonToken.String(NextString(ch)));
}
//
// Object
//
if (ch == '{')
{
_reader.Back();
return ParseObject();
}
//
// Array
//
if (ch == '[')
{
_reader.Back();
return ParseArray();
}
//
// Handle unquoted text. This could be the values true, false, or
// null, or it can be a number. An implementation (such as this one)
// is allowed to also accept non-standard forms.
//
// Accumulate characters until we reach the end of the text or a
// formatting character.
//
StringBuilder sb = new StringBuilder();
char b = ch;
while (ch >= ' ' && ",:]}/\\\"[{;=#".IndexOf(ch) < 0)
{
sb.Append(ch);
ch = _reader.Next();
}
_reader.Back();
string s = sb.ToString().Trim();
if (s.Length == 0)
throw new JsonException("Missing value.");
//
// Boolean
//
if (s == JsonBoolean.TrueText || s == JsonBoolean.FalseText)
return Yield(JsonToken.Boolean(s == JsonBoolean.TrueText));
//
// Null
//
if (s == JsonNull.Text)
return Yield(JsonToken.Null());
//
// Number
//
if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+')
{
double unused;
if (!double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out unused))
throw new JsonException(string.Format("The text '{0}' has the incorrect syntax for a number.", s));
return Yield(JsonToken.Number(s));
}
//
// Treat as String in all other cases, e.g. when unquoted.
//
return Yield(JsonToken.String(s));
}
private Continuation ParseMethod
{
get
{
if (_methodParse == null) _methodParse = new Continuation(Parse);
return _methodParse;
}
}
/// <summary>
/// Parses expecting an array in the source.
/// </summary>
private JsonToken ParseArray()
{
if (NextClean() != '[')
throw new JsonException("An array must start with '['.");
return Yield(JsonToken.Array(), ParseArrayFirstMethod);
}
/// <summary>
/// Parses the first element of an array or the end of the array if
/// it is empty.
/// </summary>
private JsonToken ParseArrayFirst()
{
if (NextClean() == ']')
return Yield(JsonToken.EndArray());
_reader.Back();
Push(ParseArrayNextMethod);
return Parse();
}
private Continuation ParseArrayFirstMethod
{
get
{
if (_methodParseArrayFirst == null) _methodParseArrayFirst = new Continuation(ParseArrayFirst);
return _methodParseArrayFirst;
}
}
/// <summary>
/// Parses the next element in the array.
/// </summary>
private JsonToken ParseArrayNext()
{
switch (NextClean())
{
case ';':
case ',':
{
if (NextClean() == ']')
return Yield(JsonToken.EndArray());
else
_reader.Back();
break;
}
case ']':
{
return Yield(JsonToken.EndArray());
}
default:
throw new JsonException("Expected a ',' or ']'.");
}
Push(ParseArrayNextMethod);
return Parse();
}
private Continuation ParseArrayNextMethod
{
get
{
if (_methodParseArrayNext == null) _methodParseArrayNext = new Continuation(ParseArrayNext);
return _methodParseArrayNext;
}
}
/// <summary>
/// Parses expecting an object in the source.
/// </summary>
private JsonToken ParseObject()
{
if (NextClean() != '{')
throw new JsonException("An object must begin with '{'.");
return Yield(JsonToken.Object(), ParseObjectMemberMethod);
}
/// <summary>
/// Parses the first member name of the object or the end of the array
/// in case of an empty object.
/// </summary>
private JsonToken ParseObjectMember()
{
char ch = NextClean();
if (ch == '}')
return Yield(JsonToken.EndObject());
if (ch == BufferedCharReader.EOF)
throw new JsonException("An object must end with '}'.");
_reader.Back();
string name = Parse().Text;
return Yield(JsonToken.Member(name), ParseObjectMemberValueMethod);
}
private Continuation ParseObjectMemberMethod
{
get
{
if (_methodParseObjectMember == null) _methodParseObjectMember = new Continuation(ParseObjectMember);
return _methodParseObjectMember;
}
}
private JsonToken ParseObjectMemberValue()
{
char ch = NextClean();
if (ch == '=')
{
if (_reader.Next() != '>')
_reader.Back();
}
else if (ch != ':')
throw new JsonException("Expected a ':' after a key.");
Push(ParseNextMemberMethod);
return Parse();
}
private Continuation ParseObjectMemberValueMethod
{
get
{
if (_methodParseObjectMemberValue == null) _methodParseObjectMemberValue = new Continuation(ParseObjectMemberValue);
return _methodParseObjectMemberValue;
}
}
private JsonToken ParseNextMember()
{
switch (NextClean())
{
case ';':
case ',':
{
if (NextClean() == '}')
return Yield(JsonToken.EndObject());
break;
}
case '}':
return Yield(JsonToken.EndObject());
default:
throw new JsonException("Expected a ',' or '}'.");
}
_reader.Back();
string name = Parse().Text;
return Yield(JsonToken.Member(name), ParseObjectMemberValueMethod);
}
private Continuation ParseNextMemberMethod
{
get
{
if (_methodParseNextMember == null) _methodParseNextMember = new Continuation(ParseNextMember);
return _methodParseNextMember;
}
}
/// <summary>
/// Yields control back to the reader's user while updating the
/// reader with the new found token and its text.
/// </summary>
private JsonToken Yield(JsonToken token)
{
return Yield(token, null);
}
/// <summary>
/// Yields control back to the reader's user while updating the
/// reader with the new found token, its text and the next
/// continuation point into the reader.
/// </summary>
/// <remarks>
/// By itself, this method cannot affect the stack such tha control
/// is returned back to the reader's user. This must be done by
/// Yield's caller by way of explicit return.
/// </remarks>
private JsonToken Yield(JsonToken token, Continuation continuation)
{
if (continuation != null)
Push(continuation);
return token;
}
/// <summary>
/// Get the next char in the string, skipping whitespace
/// and comments (slashslash and slashstar).
/// </summary>
/// <returns>A character, or 0 if there are no more characters.</returns>
private char NextClean()
{
Debug.Assert(_reader != null);
while (true)
{
char ch = _reader.Next();
if (ch == '/')
{
switch (_reader.Next())
{
case '/':
{
do
{
ch = _reader.Next();
} while (ch != '\n' && ch != '\r' && ch != BufferedCharReader.EOF);
break;
}
case '*':
{
while (true)
{
ch = _reader.Next();
if (ch == BufferedCharReader.EOF)
throw new JsonException("Unclosed comment.");
if (ch == '*')
{
if (_reader.Next() == '/')
break;
_reader.Back();
}
}
break;
}
default:
{
_reader.Back();
return '/';
}
}
}
else if (ch == '#')
{
do
{
ch = _reader.Next();
}
while (ch != '\n' && ch != '\r' && ch != BufferedCharReader.EOF);
}
else if (ch == BufferedCharReader.EOF || ch > ' ')
{
return ch;
}
}
}
private string NextString(char quote)
{
try
{
return JsonString.Dequote(_reader, quote);
}
catch (FormatException e)
{
throw new JsonException(e.Message, e);
}
}
private void Push(Continuation continuation)
{
Debug.Assert(continuation != null);
if (_stack == null)
_stack = new Stack(6);
_stack.Push(continuation);
}
private Continuation Pop()
{
Debug.Assert(_stack != null);
return (Continuation) _stack.Pop();
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="FrameworkElement.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections;
using System.Linq;
using Avalonia.Core;
using Avalonia.Data.Data;
namespace Avalonia
{
[RuntimeNameProperty("Name")]
public class FrameworkElement : UIElement, ISupportInitialize
{
public static readonly DependencyProperty DataContextProperty =
DependencyProperty.Register(
"DataContext",
typeof(object),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.Inherits));
public static readonly DependencyProperty DefaultStyleKeyProperty =
DependencyProperty.Register(
"DefaultStyleKey",
typeof(object),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty HeightProperty =
DependencyProperty.Register(
"Height",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty HorizontalAlignmentProperty =
DependencyProperty.Register(
"HorizontalAlignment",
typeof(HorizontalAlignment),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
HorizontalAlignment.Stretch,
FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty MarginProperty =
DependencyProperty.Register(
"Margin",
typeof(Thickness),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
new Thickness(),
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MaxHeightProperty =
DependencyProperty.Register(
"MaxHeight",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.PositiveInfinity,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MaxWidthProperty =
DependencyProperty.Register(
"MaxWidth",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.PositiveInfinity,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MinHeightProperty =
DependencyProperty.Register(
"MinHeight",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MinWidthProperty =
DependencyProperty.Register(
"MinWidth",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty StyleProperty =
DependencyProperty.Register(
"Style",
typeof(Style),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsMeasure,
StyleChanged));
public static readonly DependencyProperty VerticalAlignmentProperty =
DependencyProperty.Register(
"VerticalAlignment",
typeof(VerticalAlignment),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
VerticalAlignment.Stretch,
FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty WidthProperty =
DependencyProperty.Register(
"Width",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure));
internal static readonly DependencyProperty TemplatedParentProperty =
DependencyProperty.Register(
"TemplatedParent",
typeof(DependencyObject),
typeof(FrameworkElement),
new PropertyMetadata(TemplatedParentChanged));
private bool isInitialized;
public FrameworkElement()
{
this.Resources = new ResourceDictionary();
}
public event EventHandler Initialized;
public double ActualWidth
{
get { return this.RenderSize.Width; }
}
public double ActualHeight
{
get { return this.RenderSize.Height; }
}
public object DataContext
{
get { return this.GetValue(DataContextProperty); }
set { this.SetValue(DataContextProperty, value); }
}
public double Height
{
get { return (double)this.GetValue(HeightProperty); }
set { this.SetValue(HeightProperty, value); }
}
public HorizontalAlignment HorizontalAlignment
{
get { return (HorizontalAlignment)this.GetValue(HorizontalAlignmentProperty); }
set { this.SetValue(HorizontalAlignmentProperty, value); }
}
public bool IsInitialized
{
get
{
return this.isInitialized;
}
internal set
{
this.isInitialized = value;
if (this.isInitialized)
{
this.OnInitialized(EventArgs.Empty);
}
}
}
public Thickness Margin
{
get { return (Thickness)this.GetValue(MarginProperty); }
set { this.SetValue(MarginProperty, value); }
}
public double MaxHeight
{
get { return (double)this.GetValue(MaxHeightProperty); }
set { this.SetValue(MaxHeightProperty, value); }
}
public double MaxWidth
{
get { return (double)this.GetValue(MaxWidthProperty); }
set { this.SetValue(MaxWidthProperty, value); }
}
public double MinHeight
{
get { return (double)this.GetValue(MinHeightProperty); }
set { this.SetValue(MinHeightProperty, value); }
}
public double MinWidth
{
get { return (double)this.GetValue(MinWidthProperty); }
set { this.SetValue(MinWidthProperty, value); }
}
public string Name
{
get;
set;
}
public DependencyObject Parent
{
get;
private set;
}
// TODO: [Ambient]
public ResourceDictionary Resources
{
get;
set;
}
public Style Style
{
get { return (Style)this.GetValue(StyleProperty); }
set { this.SetValue(StyleProperty, value); }
}
public DependencyObject TemplatedParent
{
get { return (DependencyObject)this.GetValue(TemplatedParentProperty); }
internal set { this.SetValue(TemplatedParentProperty, value); }
}
public VerticalAlignment VerticalAlignment
{
get { return (VerticalAlignment)this.GetValue(VerticalAlignmentProperty); }
set { this.SetValue(VerticalAlignmentProperty, value); }
}
public double Width
{
get { return (double)this.GetValue(WidthProperty); }
set { this.SetValue(WidthProperty, value); }
}
protected internal object DefaultStyleKey
{
get { return this.GetValue(DefaultStyleKeyProperty); }
set { this.SetValue(DefaultStyleKeyProperty, value); }
}
protected internal virtual IEnumerator LogicalChildren
{
get { return new object[0].GetEnumerator(); }
}
public virtual bool ApplyTemplate()
{
// NOTE: this isn't virtual in WPF, but the Template property isn't defined until
// Control so I don't see how it is applied at this level. Making it virtual makes
// the most sense for now.
return false;
}
public object FindName(string name)
{
INameScope nameScope = this.FindNameScope(this);
return (nameScope != null) ? nameScope.FindName(name) : null;
}
public object FindResource(object resourceKey)
{
object resource = this.TryFindResource(resourceKey);
if (resource != null)
{
return resource;
}
else
{
throw new ResourceReferenceKeyNotFoundException(
string.Format("'{0}' resource not found", resourceKey),
resourceKey);
}
}
public virtual void OnApplyTemplate()
{
}
public object TryFindResource(object resourceKey)
{
FrameworkElement element = this;
object resource = null;
while (resource == null && element != null)
{
resource = element.Resources[resourceKey];
element = (FrameworkElement)VisualTreeHelper.GetParent(element);
}
if (resource == null && ApplicationBase.Current != null)
{
resource = ApplicationBase.Current.Resources[resourceKey];
}
if (resource == null)
{
resource = ApplicationBase.GenericTheme[resourceKey];
}
return resource;
}
void ISupportInitialize.BeginInit()
{
}
void ISupportInitialize.EndInit()
{
this.IsInitialized = true;
}
protected internal void AddLogicalChild(object child)
{
FrameworkElement fe = child as FrameworkElement;
if (fe != null)
{
if (fe.Parent != null)
{
throw new InvalidOperationException("FrameworkElement already has a parent.");
}
fe.Parent = this;
if (this.TemplatedParent != null)
{
this.PropagateTemplatedParent(fe, this.TemplatedParent);
}
this.InvalidateMeasure();
}
}
protected internal void RemoveLogicalChild(object child)
{
FrameworkElement fe = child as FrameworkElement;
if (fe != null)
{
if (fe.Parent != this)
{
throw new InvalidOperationException("FrameworkElement is not a child of this object.");
}
fe.Parent = null;
this.InvalidateMeasure();
}
}
protected internal virtual DependencyObject GetTemplateChild(string childName)
{
return null;
}
protected internal virtual void OnStyleChanged(Style oldStyle, Style newStyle)
{
if (oldStyle != null)
{
oldStyle.Detach(this);
}
if (newStyle != null)
{
newStyle.Attach(this);
}
}
protected internal override void OnVisualParentChanged(DependencyObject oldParent)
{
if (this.VisualParent != null)
{
this.IsInitialized = true;
}
}
protected sealed override Size MeasureCore(Size availableSize)
{
this.ApplyTemplate();
availableSize = new Size(
Math.Max(0, availableSize.Width - this.Margin.Left - this.Margin.Right),
Math.Max(0, availableSize.Height - this.Margin.Top - this.Margin.Bottom));
Size size = this.MeasureOverride(availableSize);
size = new Size(
Math.Min(availableSize.Width, size.Width + this.Margin.Left + this.Margin.Right),
Math.Min(availableSize.Height, size.Height + this.Margin.Top + this.Margin.Bottom));
return size;
}
protected virtual Size MeasureOverride(Size constraint)
{
return new Size();
}
protected sealed override void ArrangeCore(Rect finalRect)
{
Point origin = new Point(
finalRect.Left + this.Margin.Left,
finalRect.Top + this.Margin.Top);
Size size = new Size(
Math.Max(0, finalRect.Width - this.Margin.Left - this.Margin.Right),
Math.Max(0, finalRect.Height - this.Margin.Top - this.Margin.Bottom));
if (this.HorizontalAlignment != HorizontalAlignment.Stretch)
{
size = new Size(Math.Min(size.Width, this.DesiredSize.Width), size.Height);
}
if (this.VerticalAlignment != VerticalAlignment.Stretch)
{
size = new Size(size.Width, Math.Min(size.Height, this.DesiredSize.Height));
}
Size taken = this.ArrangeOverride(size);
size = new Size(
Math.Min(taken.Width, size.Width),
Math.Min(taken.Height, size.Height));
switch (this.HorizontalAlignment)
{
case HorizontalAlignment.Center:
origin.X += (finalRect.Width - size.Width) / 2;
break;
case HorizontalAlignment.Right:
origin.X += finalRect.Width - size.Width;
break;
}
switch (this.VerticalAlignment)
{
case VerticalAlignment.Center:
origin.Y += (finalRect.Height - size.Height) / 2;
break;
case VerticalAlignment.Bottom:
origin.Y += finalRect.Height - size.Height;
break;
}
base.ArrangeCore(new Rect(origin, size));
}
protected virtual Size ArrangeOverride(Size finalSize)
{
return finalSize;
}
protected virtual void OnInitialized(EventArgs e)
{
if (this.Initialized != null)
{
this.Initialized(this, e);
}
}
private static void StyleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((FrameworkElement)sender).OnStyleChanged((Style)e.OldValue, (Style)e.NewValue);
}
private static void TemplatedParentChanged(object sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
element.PropagateTemplatedParent(element, element.TemplatedParent);
}
private INameScope FindNameScope(FrameworkElement e)
{
while (e != null)
{
INameScope nameScope = e as INameScope ?? NameScope.GetNameScope(e);
if (nameScope != null)
{
return nameScope;
}
e = LogicalTreeHelper.GetParent(e) as FrameworkElement;
}
return null;
}
private void PropagateTemplatedParent(FrameworkElement element, DependencyObject templatedParent)
{
element.TemplatedParent = templatedParent;
foreach (FrameworkElement child in LogicalTreeHelper.GetChildren(element).OfType<FrameworkElement>())
{
child.TemplatedParent = templatedParent;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using UnityEngine;
namespace InControl
{
/// <summary>
/// An action set represents a set of actions, usually for a single player. This class must be subclassed to be used.
/// An action set can contain both explicit, bindable single value actions (for example, "Jump", "Left" and "Right") and implicit,
/// aggregate actions which combine together other actions into one or two axes, for example "Move", which might consist
/// of "Left", "Right", "Up" and "Down" filtered into a single two-axis control with its own applied circular deadzone,
/// queryable vector value, etc.
/// </summary>
public abstract class PlayerActionSet
{
/// <summary>
/// The device which this set should query from, if applicable.
/// When set to <c>null</c> this set will query <see cref="InputManager.ActiveDevice" /> when required.
/// </summary>
public InputDevice Device { get; set; }
/// <summary>
/// Gets the actions in this set as a readonly collection.
/// </summary>
public ReadOnlyCollection<PlayerAction> Actions { get; private set; }
/// <summary>
/// The last update tick on which any action in this set changed value.
/// </summary>
public ulong UpdateTick { get; protected set; }
/// <summary>
/// The binding source type that provided input to this action set.
/// </summary>
public BindingSourceType LastInputType = BindingSourceType.None;
/// <summary>
/// Whether this action set should produce input. Default: <c>true</c>
/// </summary>
public bool Enabled { get; set; }
List<PlayerAction> actions = new List<PlayerAction>();
List<PlayerOneAxisAction> oneAxisActions = new List<PlayerOneAxisAction>();
List<PlayerTwoAxisAction> twoAxisActions = new List<PlayerTwoAxisAction>();
Dictionary<string, PlayerAction> actionsByName = new Dictionary<string, PlayerAction>();
BindingListenOptions listenOptions = new BindingListenOptions();
internal PlayerAction listenWithAction;
protected PlayerActionSet()
{
Actions = new ReadOnlyCollection<PlayerAction>( actions );
Enabled = true;
InputManager.AttachPlayerActionSet( this );
}
/// <summary>
/// Properly dispose of this action set. You should make sure to call this when the action set
/// will no longer be used or it will result in unnecessary internal processing every frame.
/// </summary>
public void Destroy()
{
InputManager.DetachPlayerActionSet( this );
}
/// <summary>
/// Create an action on this set. This should be performed in the constructor of your PlayerActionSet subclass.
/// </summary>
/// <param name="name">A unique identifier for this action within the context of this set.</param>
/// <exception cref="InControlException">Thrown when trying to create an action with a non-unique name for this set.</exception>
protected PlayerAction CreatePlayerAction( string name )
{
var action = new PlayerAction( name, this );
action.Device = Device ?? InputManager.ActiveDevice;
if (actionsByName.ContainsKey( name ))
{
throw new InControlException( "Action '" + name + "' already exists in this set." );
}
actions.Add( action );
actionsByName.Add( name, action );
return action;
}
/// <summary>
/// Create an aggregate, single-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass.
/// </summary>
/// <example>
/// <code>
/// Throttle = CreateOneAxisPlayerAction( Brake, Accelerate );
/// </code>
/// </example>
/// <param name="negativeAction">The action to query for the negative component of the axis.</param>
/// <param name="positiveAction">The action to query for the positive component of the axis.</param>
protected PlayerOneAxisAction CreateOneAxisPlayerAction( PlayerAction negativeAction, PlayerAction positiveAction )
{
var action = new PlayerOneAxisAction( negativeAction, positiveAction );
oneAxisActions.Add( action );
return action;
}
/// <summary>
/// Create an aggregate, double-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass.
/// </summary>
/// <example>
/// Note that, due to Unity's positive up-vector, the parameter order of <c>negativeYAction</c> and <c>positiveYAction</c> might seem counter-intuitive.
/// <code>
/// Move = CreateTwoAxisPlayerAction( Left, Right, Down, Up );
/// </code>
/// </example>
/// <param name="negativeXAction">The action to query for the negative component of the X axis.</param>
/// <param name="positiveXAction">The action to query for the positive component of the X axis.</param>
/// <param name="negativeYAction">The action to query for the negative component of the Y axis.</param>
/// <param name="positiveYAction">The action to query for the positive component of the Y axis.</param>
protected PlayerTwoAxisAction CreateTwoAxisPlayerAction( PlayerAction negativeXAction, PlayerAction positiveXAction, PlayerAction negativeYAction, PlayerAction positiveYAction )
{
var action = new PlayerTwoAxisAction( negativeXAction, positiveXAction, negativeYAction, positiveYAction );
twoAxisActions.Add( action );
return action;
}
internal void Update( ulong updateTick, float deltaTime )
{
var device = Device ?? InputManager.ActiveDevice;
var actionsCount = actions.Count;
for (int i = 0; i < actionsCount; i++)
{
var action = actions[i];
action.Update( updateTick, deltaTime, device );
if (action.UpdateTick > UpdateTick)
{
UpdateTick = action.UpdateTick;
LastInputType = action.LastInputType;
}
}
var oneAxisActionsCount = oneAxisActions.Count;
for (int i = 0; i < oneAxisActionsCount; i++)
{
oneAxisActions[i].Update( updateTick, deltaTime );
}
var twoAxisActionsCount = twoAxisActions.Count;
for (int i = 0; i < twoAxisActionsCount; i++)
{
twoAxisActions[i].Update( updateTick, deltaTime );
}
}
/// <summary>
/// Reset the bindings on all actions in this set.
/// </summary>
public void Reset()
{
var actionCount = actions.Count;
for (int i = 0; i < actionCount; i++)
{
actions[i].ResetBindings();
}
}
public void ClearInputState()
{
var actionsCount = actions.Count;
for (int i = 0; i < actionsCount; i++)
{
actions[i].ClearInputState();
}
var oneAxisActionsCount = oneAxisActions.Count;
for (int i = 0; i < oneAxisActionsCount; i++)
{
oneAxisActions[i].ClearInputState();
}
var twoAxisActionsCount = twoAxisActions.Count;
for (int i = 0; i < twoAxisActionsCount; i++)
{
twoAxisActions[i].ClearInputState();
}
}
internal bool HasBinding( BindingSource binding )
{
if (binding == null)
{
return false;
}
var actionsCount = actions.Count;
for (int i = 0; i < actionsCount; i++)
{
if (actions[i].HasBinding( binding ))
{
return true;
}
}
return false;
}
internal void RemoveBinding( BindingSource binding )
{
if (binding == null)
{
return;
}
var actionsCount = actions.Count;
for (int i = 0; i < actionsCount; i++)
{
actions[i].FindAndRemoveBinding( binding );
}
}
/// <summary>
/// Configures how in an action in this set listens for new bindings when the action does not
/// explicitly define its own listen options.
/// </summary>
public BindingListenOptions ListenOptions
{
get
{
return listenOptions;
}
set
{
listenOptions = value ?? new BindingListenOptions();
}
}
/// <summary>
/// Returns the state of this action set and all bindings encoded into a string
/// that you can save somewhere.
/// Pass this string to Load() to restore the state of this action set.
/// </summary>
public string Save()
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter( stream, System.Text.Encoding.UTF8 ))
{
// Write header.
writer.Write( (byte) 'B' );
writer.Write( (byte) 'I' );
writer.Write( (byte) 'N' );
writer.Write( (byte) 'D' );
// Write version.
writer.Write( (UInt16) 1 );
// Write actions.
var actionCount = actions.Count;
writer.Write( actionCount );
for (int i = 0; i < actionCount; i++)
{
actions[i].Save( writer );
}
}
return Convert.ToBase64String( stream.ToArray() );
}
}
/// <summary>
/// Load a state returned by calling Dump() at a prior time.
/// </summary>
/// <param name="data">The data string.</param>
public void Load( string data )
{
if (data == null)
{
return;
}
try
{
using (var stream = new MemoryStream( Convert.FromBase64String( data ) ))
{
using (var reader = new BinaryReader( stream ))
{
if (reader.ReadUInt32() != 0x444E4942)
{
throw new Exception( "Unknown data format." );
}
if (reader.ReadUInt16() != 1)
{
throw new Exception( "Unknown data version." );
}
var actionCount = reader.ReadInt32();
for (int i = 0; i < actionCount; i++)
{
PlayerAction action;
if (actionsByName.TryGetValue( reader.ReadString(), out action ))
{
action.Load( reader );
}
}
}
}
}
catch (Exception e)
{
Debug.LogError( "Provided state could not be loaded:\n" + e.Message );
Reset();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.