context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Runtime.CompilerServices;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using System.Linq;
namespace umbraco.cms.businesslogic.macro
{
/// <summary>
/// The Macro component are one of the umbraco essentials, used for drawing dynamic content in the public website of umbraco.
///
/// A Macro is a placeholder for either a xsl transformation, a custom .net control or a .net usercontrol.
///
/// The Macro is representated in templates and content as a special html element, which are being parsed out and replaced with the
/// output of either the .net control or the xsl transformation when a page is being displayed to the visitor.
///
/// A macro can have a variety of properties which are used to transfer userinput to either the usercontrol/custom control or the xsl
///
/// </summary>
public class Macro
{
int _id;
bool _useInEditor;
bool _renderContent;
bool _cachePersonalized;
bool _cacheByPage;
int _refreshRate;
string _alias;
string _name;
string _assembly;
string _type;
string _xslt;
string _scriptingFile;
MacroProperty[] _properties;
bool m_propertiesLoaded = false;
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
/// <summary>
/// id
/// </summary>
public int Id
{
get {return _id;}
}
/// <summary>
/// If set to true, the macro can be inserted on documents using the richtexteditor.
/// </summary>
public bool UseInEditor
{
get {return _useInEditor;}
set
{
_useInEditor = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroUseInEditor = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The cache refreshrate - the maximum amount of time the macro should remain cached in the umbraco
/// runtime layer.
///
/// The macro caches are refreshed whenever a document is changed
/// </summary>
public int RefreshRate
{
get {return _refreshRate;}
set
{
_refreshRate = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroRefreshRate = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The alias of the macro - are used for retrieving the macro when parsing the {?UMBRACO_MACRO}{/?UMBRACO_MACRO} element,
/// by using the alias instead of the Id, it's possible to distribute macroes from one installation to another - since the id
/// is given by an autoincrementation in the database table, and might be used by another macro in the foreing umbraco
/// </summary>
public string Alias
{
get {return _alias;}
set
{
_alias = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroAlias = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The userfriendly name
/// </summary>
public string Name
{
get {return _name;}
set
{
_name = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroName = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// If the macro is a wrapper for a custom control, this is the assemly name from which to load the macro
///
/// specified like: /bin/mydll (without the .dll extension)
/// </summary>
public string Assembly
{
get {return _assembly;}
set
{
_assembly = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroScriptAssembly = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The relative path to the usercontrol or the assembly type of the macro when using .Net custom controls
/// </summary>
/// <remarks>
/// When using a user control the value is specified like: /usercontrols/myusercontrol.ascx (with the .ascx postfix)
/// </remarks>
public string Type
{
get {return _type;}
set
{
_type = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroScriptType = @macroAlias where id = @id", SqlHelper.CreateParameter("@macroAlias", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The xsl file used to transform content
///
/// Umbraco assumes that the xslfile is present in the "/xslt" folder
/// </summary>
public string Xslt
{
get {return _xslt;}
set
{
_xslt = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroXSLT = @macroXslt where id = @id", SqlHelper.CreateParameter("@macroXslt", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// This field is used to store the file value for any scripting macro such as python, ruby, razor macros or Partial View Macros
/// </summary>
/// <remarks>
/// Depending on how the file is stored depends on what type of macro it is. For example if the file path is a full virtual path
/// starting with the ~/Views/MacroPartials then it is deemed to be a Partial View Macro, otherwise the file extension of the file
/// saved will determine which macro engine will be used to execute the file.
/// </remarks>
public string ScriptingFile {
get { return _scriptingFile; }
set {
_scriptingFile = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroPython = @macroPython where id = @id", SqlHelper.CreateParameter("@macroPython", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// The python file used to be executed
///
/// Umbraco assumes that the python file is present in the "/python" folder
/// </summary>
public bool RenderContent {
get { return _renderContent; }
set {
_renderContent = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroDontRender = @macroDontRender where id = @id", SqlHelper.CreateParameter("@macroDontRender", !value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// Gets or sets a value indicating whether [cache personalized].
/// </summary>
/// <value><c>true</c> if [cache personalized]; otherwise, <c>false</c>.</value>
public bool CachePersonalized {
get { return _cachePersonalized; }
set {
_cachePersonalized = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroCachePersonalized = @macroCachePersonalized where id = @id", SqlHelper.CreateParameter("@macroCachePersonalized", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// Gets or sets a value indicating whether the macro is cached for each individual page.
/// </summary>
/// <value><c>true</c> if [cache by page]; otherwise, <c>false</c>.</value>
public bool CacheByPage {
get { return _cacheByPage; }
set {
_cacheByPage = value;
SqlHelper.ExecuteNonQuery("update cmsMacro set macroCacheByPage = @macroCacheByPage where id = @id", SqlHelper.CreateParameter("@macroCacheByPage", value), SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// Properties which are used to send parameters to the xsl/usercontrol/customcontrol of the macro
/// </summary>
public MacroProperty[] Properties
{
get {
// Add lazy loading
if (!m_propertiesLoaded)
{
LoadProperties();
}
return _properties;
}
}
private void LoadProperties()
{
_properties = MacroProperty.GetProperties(Id);
m_propertiesLoaded = true;
}
/// <summary>
/// Macro initializer
/// </summary>
public Macro() {}
/// <summary>
/// Macro initializer
/// </summary>
/// <param name="Id">The id of the macro</param>
public Macro(int Id)
{
_id = Id;
setup();
}
/// <summary>
/// Initializes a new instance of the <see cref="Macro"/> class.
/// </summary>
/// <param name="alias">The alias.</param>
public Macro(string alias)
{
using (IRecordsReader dr = SqlHelper.ExecuteReader("select id from cmsMacro where macroAlias = @alias", SqlHelper.CreateParameter("@alias", alias)))
{
if (dr.Read())
{
_id = dr.GetInt("id");
setup();
}
else
{
throw new IndexOutOfRangeException(string.Format("Alias '{0}' does not match an existing macro", alias));
}
}
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public virtual void Save()
{
//event
var e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel) {
FireAfterSave(e);
}
}
/// <summary>
/// Deletes the current macro
/// </summary>
public void Delete()
{
//event
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel) {
foreach (MacroProperty p in this.Properties)
p.Delete();
SqlHelper.ExecuteNonQuery("delete from cmsMacro where id = @id", SqlHelper.CreateParameter("@id", this._id));
FireAfterDelete(e);
}
}
public static Macro Import(XmlNode n)
{
Macro m = null;
string alias = xmlHelper.GetNodeValue(n.SelectSingleNode("alias"));
try
{
//check to see if the macro alreay exists in the system
//it's better if it does and we keep using it, alias *should* be unique remember
m = new Macro(alias);
Macro.GetByAlias(alias);
}
catch (IndexOutOfRangeException)
{
m = MakeNew(xmlHelper.GetNodeValue(n.SelectSingleNode("name")));
}
try
{
m.Alias = alias;
m.Assembly = xmlHelper.GetNodeValue(n.SelectSingleNode("scriptAssembly"));
m.Type = xmlHelper.GetNodeValue(n.SelectSingleNode("scriptType"));
m.Xslt = xmlHelper.GetNodeValue(n.SelectSingleNode("xslt"));
m.RefreshRate = int.Parse(xmlHelper.GetNodeValue(n.SelectSingleNode("refreshRate")));
// we need to validate if the usercontrol is missing the tilde prefix requirement introduced in v6
if (String.IsNullOrEmpty(m.Assembly) && !String.IsNullOrEmpty(m.Type) && !m.Type.StartsWith("~"))
m.Type = "~/" + m.Type;
if (n.SelectSingleNode("scriptingFile") != null)
m.ScriptingFile = xmlHelper.GetNodeValue(n.SelectSingleNode("scriptingFile"));
try
{
m.UseInEditor = bool.Parse(xmlHelper.GetNodeValue(n.SelectSingleNode("useInEditor")));
}
catch (Exception macroExp)
{
LogHelper.Error<Macro>("Error creating macro property", macroExp);
}
// macro properties
foreach (XmlNode mp in n.SelectNodes("properties/property"))
{
try
{
string propertyAlias = mp.Attributes.GetNamedItem("alias").Value;
var property = m.Properties.SingleOrDefault(p => p.Alias == propertyAlias);
if (property != null)
{
property.Public = bool.Parse(mp.Attributes.GetNamedItem("show").Value);
property.Name = mp.Attributes.GetNamedItem("name").Value;
property.Type = new MacroPropertyType(mp.Attributes.GetNamedItem("propertyType").Value);
property.Save();
}
else
{
MacroProperty.MakeNew(
m,
bool.Parse(mp.Attributes.GetNamedItem("show").Value),
propertyAlias,
mp.Attributes.GetNamedItem("name").Value,
new MacroPropertyType(mp.Attributes.GetNamedItem("propertyType").Value)
);
}
}
catch (Exception macroPropertyExp)
{
LogHelper.Error<Macro>("Error creating macro property", macroPropertyExp);
}
}
m.Save();
}
catch { return null; }
return m;
}
private void setup()
{
using (IRecordsReader dr = SqlHelper.ExecuteReader("select id, macroUseInEditor, macroRefreshRate, macroAlias, macroName, macroScriptType, macroScriptAssembly, macroXSLT, macroPython, macroDontRender, macroCacheByPage, macroCachePersonalized from cmsMacro where id = @id", SqlHelper.CreateParameter("@id", _id)))
{
if (dr.Read())
{
PopulateMacroInfo(dr);
}
else
{
throw new ArgumentException("No macro found for the id specified");
}
}
}
private void PopulateMacroInfo(IRecordsReader dr)
{
_useInEditor = dr.GetBoolean("macroUseInEditor");
_refreshRate = dr.GetInt("macroRefreshRate");
_alias = dr.GetString("macroAlias");
_id = dr.GetInt("id");
_name = dr.GetString("macroName");
_assembly = dr.GetString("macroScriptAssembly");
_type = dr.GetString("macroScriptType");
_xslt = dr.GetString("macroXSLT");
_scriptingFile = dr.GetString("macroPython");
_cacheByPage = dr.GetBoolean("macroCacheByPage");
_cachePersonalized = dr.GetBoolean("macroCachePersonalized");
_renderContent = !dr.GetBoolean("macroDontRender");
}
/// <summary>
/// Get an xmlrepresentation of the macro, used for exporting the macro to a package for distribution
/// </summary>
/// <param name="xd">Current xmldocument context</param>
/// <returns>An xmlrepresentation of the macro</returns>
public XmlNode ToXml(XmlDocument xd) {
XmlNode doc = xd.CreateElement("macro");
// info section
doc.AppendChild(xmlHelper.addTextNode(xd, "name", this.Name));
doc.AppendChild(xmlHelper.addTextNode(xd, "alias", this.Alias));
doc.AppendChild(xmlHelper.addTextNode(xd, "scriptType", this.Type));
doc.AppendChild(xmlHelper.addTextNode(xd, "scriptAssembly", this.Assembly));
doc.AppendChild(xmlHelper.addTextNode(xd, "xslt", this.Xslt));
doc.AppendChild(xmlHelper.addTextNode(xd, "useInEditor", this.UseInEditor.ToString()));
doc.AppendChild(xmlHelper.addTextNode(xd, "refreshRate", this.RefreshRate.ToString()));
doc.AppendChild(xmlHelper.addTextNode(xd, "scriptingFile", this.ScriptingFile));
// properties
XmlNode props = xd.CreateElement("properties");
foreach (MacroProperty p in this.Properties)
props.AppendChild(p.ToXml(xd));
doc.AppendChild(props);
return doc;
}
public void RefreshProperties()
{
m_propertiesLoaded = false;
}
#region STATICS
/// <summary>
/// Creates a new macro given the name
/// </summary>
/// <param name="Name">Userfriendly name</param>
/// <returns>The newly macro</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static Macro MakeNew(string Name)
{
int macroId = 0;
// The method is synchronized
SqlHelper.ExecuteNonQuery("INSERT INTO cmsMacro (macroAlias, macroName) values (@macroAlias, @macroName)",
SqlHelper.CreateParameter("@macroAlias", Name.Replace(" ", String.Empty)),
SqlHelper.CreateParameter("@macroName", Name));
macroId = SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsMacro");
Macro newMacro = new Macro(macroId);
//fire new event
NewEventArgs e = new NewEventArgs();
newMacro.OnNew(e);
return newMacro;
}
/// <summary>
/// Retrieve all macroes
/// </summary>
/// <returns>A list of all macroes</returns>
public static Macro[] GetAll()
{
// zb-00001 #29927 : refactor
IRecordsReader dr = SqlHelper.ExecuteReader("select id from cmsMacro order by macroName");
var list = new System.Collections.Generic.List<Macro>();
while (dr.Read()) list.Add(new Macro(dr.GetInt("id")));
return list.ToArray();
}
/// <summary>
/// Static contructor for retrieving a macro given an alias
/// </summary>
/// <param name="alias">The alias of the macro</param>
/// <returns>If the macro with the given alias exists, it returns the macro, else null</returns>
public static Macro GetByAlias(string alias)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(alias),
TimeSpan.FromMinutes(30),
delegate
{
try
{
return new Macro(alias);
}
catch
{
return null;
}
});
}
public static Macro GetById(int id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(string.Format("macro_via_id_{0}", id)),
TimeSpan.FromMinutes(30),
delegate
{
try
{
return new Macro(id);
}
catch
{
return null;
}
});
}
public static MacroTypes FindMacroType(string xslt, string scriptFile, string scriptType, string scriptAssembly)
{
if (!string.IsNullOrEmpty(xslt))
return MacroTypes.XSLT;
if (!string.IsNullOrEmpty(scriptFile))
{
//we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is
//a partial view macro, not a script macro
//we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view.
return (scriptFile.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/")
|| (Regex.IsMatch(scriptFile, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase)))
? MacroTypes.PartialView
: MacroTypes.Script;
}
if (!string.IsNullOrEmpty(scriptType) && scriptType.InvariantContains(".ascx"))
return MacroTypes.UserControl;
if (!string.IsNullOrEmpty(scriptType) && !string.IsNullOrEmpty(scriptAssembly))
return MacroTypes.CustomControl;
return MacroTypes.Unknown;
}
public static string GenerateCacheKeyFromCode(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentNullException("input", "An MD5 hash cannot be generated when 'input' parameter is null!");
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
#region Macro Refactor
private static string GetCacheKey(string alias)
{
return CacheKeys.MacroCacheKey + alias;
}
#endregion
//Macro events
//Delegates
public delegate void SaveEventHandler(Macro sender, SaveEventArgs e);
public delegate void NewEventHandler(Macro sender, NewEventArgs e);
public delegate void DeleteEventHandler(Macro sender, DeleteEventArgs e);
/// <summary>
/// Occurs when a macro is saved.
/// </summary>
public static event SaveEventHandler BeforeSave;
protected virtual void FireBeforeSave(SaveEventArgs e) {
if (BeforeSave != null)
BeforeSave(this, e);
}
public static event SaveEventHandler AfterSave;
protected virtual void FireAfterSave(SaveEventArgs e) {
if (AfterSave != null)
AfterSave(this, e);
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e) {
if (New != null)
New(this, e);
}
public static event DeleteEventHandler BeforeDelete;
protected virtual void FireBeforeDelete(DeleteEventArgs e) {
if (BeforeDelete != null)
BeforeDelete(this, e);
}
public static event DeleteEventHandler AfterDelete;
protected virtual void FireAfterDelete(DeleteEventArgs e) {
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
/*
Copyright (c) 2010 - 2012 Jordan "Earlz/hckr83" Earls <http://lastyearswishes.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.Configuration;
using System.Web.Security;
using System.Security;
namespace Earlz.LucidMVC.Authentication.Experimental
{
/// <summary>
/// The main FSCAuth class
/// </summary>
/// <remarks>
/// To opt-in for authentication, all that is needed is an IUserStore to be made and SiteName initialized.
/// </remarks>
public class FSCAuth : IAuthMechanism
{
public FSCAuth(IServerContext server, FSCAuthConfig config, IUserStore store, bool defaultbasic=false)
{
Server=server;
Config=config;
if(Config.HasherInvoker==null)
{
Config.HasherInvoker=DefaultHasher;
}
BasicByDefault=defaultbasic;
UserStore=store;
}
bool BasicByDefault=false;
public void RequiresAuthentication ()
{
if(IsAuthenticated){
return;
}
if(BasicByDefault){
SendHttp401();
}
if (string.IsNullOrEmpty(Config.LoginPage))
{
throw new ArgumentNullException("Config.LoginPage", "LoginPage must be set");
}
else
{
Server.Redirect(Config.LoginPage); //this will cause an exception, but the redirect will work fine
}
}
public bool Login (string username, string password, DateTime expiration)
{
var user = UserStore.GetUserByName(username);
if (user == null)
{
return false;
}
string hash = PasswordHash(user,password).Text;
if (hash == user.PasswordHash)
{
LoginFromHash(user, expiration);
return true;
}
else
{
return false;
}
}
public bool Login (string username, string password, TimeSpan expires, DateTime? timeout)
{
throw new NotSupportedException();
}
public bool Login (string username, string password)
{
var user = UserStore.GetUserByName(username);
if (user == null)
{
return false;
}
string hash = PasswordHash(user,password).Text;
if (hash == user.PasswordHash)
{
LoginFromHash(user, null);
return true;
}
else
{
return false;
}
}
public FSCAuthConfig Config{get; private set;}
public IServerContext Server{get;private set;}
static bool SupportsUnmanagedCrypto;
static FSCAuth(){
try
{
SupportsUnmanagedCrypto=true;
new SHA256CryptoServiceProvider();
}
catch (PlatformNotSupportedException)
{ //Windows XP doesn't support native
SupportsUnmanagedCrypto=false;
}
}
HashWithSalt DefaultHasher(string plain, string salt)
{
var v=new HashWithSalt();
if(salt==null){
v.Salt=HashHelper.GetSalt(Config.SaltLength);
}else{
v.Salt=salt;
}
HashAlgorithm hash;
if(SupportsUnmanagedCrypto){
hash=new SHA256CryptoServiceProvider();
}else{
hash=new SHA256Managed();
}
v.Text=HashHelper.FromBytes(hash.ComputeHash(HashHelper.ToRawBytes(plain+v.Salt)));
return v;
}
/// <summary>
/// The IUserStore to use. This must be populated before Authenticate or anything else can be used in this class.
/// </summary>
public IUserStore UserStore{get;private set;}
bool formlogin;
/// <summary>
/// Is true if the current user was authenticated with Forms Authentication(cookie based).
/// If false, then no user is logged in, or they were logged in with HTTP Basic Authentication.
/// </summary>
public bool FormLogin
{
get
{
Authenticate();
return formlogin;
}
private set
{
formlogin=value;
}
}
UserData currentuser;
bool TriedToAuthenticate=false;
/// <summary>
/// The current user logged in for the HTTP request. If there is not a user logged in, this will be null.
/// </summary>
public UserData CurrentUser{
get
{
if(currentuser==null)
{
Authenticate();
}
return currentuser;
}
private set
{
currentuser=value;
}
}
public bool IsAuthenticated{get { return CurrentUser!=null; }}
/// <summary>
/// Returns true if a user is "probably" logged in. This is true when a valid cookie or HttpAuthentication is used(but not verified)
/// DO NOT USE THIS TO SAFE-GUARD ANYTHING IMPORTANT! This is only intended to be used in things such as views
/// where you'd want to display a link to a control panel or some such.
/// The purpose of this is that this will not try to look up the user in the database, making it so that
/// you can display aesthetic items such as profile or administration links on non-authenticated pages which don't hide anything important
/// </summary>
/// <value>
/// <c>true</c> if probably logged in; otherwise, <c>false</c>.
/// </value>
public bool ProbablyLoggedIn
{
get
{
return ProbableUserName!=null;
}
}
string probableusername;
bool TriedProbableLogin=false;
/// <summary>
/// Returns the name of the person "probably" logged in. This is true when a valid cookie or HttpAuthentication is used(but not verified)
/// DO NOT USE THIS TO SAFE-GUARD ANYTHING IMPORTANT! This is only intended to be used in things such as views
/// where you'd want to display a link to a control panel or some such.
/// The purpose of this is that this will not try to look up the user in the database, so that
/// you can display aesthetic items such as profile or administration links on non-authenticated pages which don't hide anything important
/// </summary>
/// <value>
/// The name of the probable user.
/// </value>
public string ProbableUserName
{
get
{
if(currentuser!=null) //if we're already authenticated, don't bother with this
{
return currentuser.Username;
}
if(probableusername==null)
{
return ProbableUserName=ProbablyLoggedInName();
}
return probableusername;
}
private set
{
probableusername=value;
}
}
/// <summary>
/// Will lookup who is "probably" looked in without hitting the database.
/// This is not secure and should not guard anything important
/// </summary>
/// <returns>
/// The logged in name.
/// </returns>
string ProbablyLoggedInName()
{
if(TriedProbableLogin)
{
return probableusername;
}
TriedProbableLogin=true;
string username=null;
string authHeader=Server.GetHeader("Authorization");
if(Config.SiteName!=null && string.IsNullOrEmpty(authHeader))
{
string userNameAndPassword = Encoding.Default.GetString(Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
return parts[0];
}
var cookie=Server.GetCookie(Config.SiteName+"_login");
if(cookie==null)
{
return null;
}
DateTime expires=ConvertFromUnixTimestamp(long.Parse(cookie["expire"]));
if(expires<DateTime.Now){
ForceCookieExpiration();
return null;
}
if(string.IsNullOrEmpty(cookie["secret"]))
{
return null;
}
return cookie["name"];
}
/// <summary>
/// This will check for a login cookie and check that it is valid. It will then assign CurrentUser.
/// </summary>
/// <exception cref="ArgumentException">Throws if UniqueHash is not complete </exception>
public void Authenticate(){
if(TriedToAuthenticate)
{
return;
}
TriedToAuthenticate=true;
if(Config.UniqueHash==null){
throw new ArgumentException("You MUST fill in UniqueHash before using the AuthenticationModule!");
}
string username;
string hash;
string password;
UserData user;
string authHeader = Server.GetHeader("Authorization");
if(Config.SiteName!=null && !string.IsNullOrEmpty(authHeader)){ //try HTTP basic auth
string userNameAndPassword = Encoding.Default.GetString(Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
username=parts[0];
password=parts[1];
user=UserStore.GetUserByName(username);
if(user!=null){
hash=PasswordHash(user,password).Text;
if(hash==user.PasswordHash){
CurrentUser=user;
FormLogin = false;
return;
}else{
CurrentUser=null; //just drop through and try cookies instead.
}
}
}
//try forms/cookie auth
HttpCookie cookie=Server.GetCookie(Config.SiteName+"_login");
if(cookie==null){
return;
}
username=cookie.Values["name"];
username=username.Trim();
hash=cookie.Values["secret"];
user=UserStore.GetUserByName(username);
if(user==null){ //user wasn't found in the database
ForceCookieExpiration();
return;
}
DateTime expires=ConvertFromUnixTimestamp(long.Parse(cookie["expire"]));
string hash2=ComputeLoginHash(user.PasswordHash,user.Salt,expires);
if(expires<DateTime.Now){
ForceCookieExpiration();
return;
}
if(hash==hash2){
CurrentUser=user;
FormLogin = true;
return;
}else{
CurrentUser=null;
ForceCookieExpiration();
return;
}
}
/// <summary>
/// Will delete the current login cookie, if it exists.
/// </summary>
public void Logout(){
if (FormLogin==false)
{
throw new NotSupportedException("Can not log out a user logged in using HTTP Basic Authentication");
}
var c=Server.GetCookie(Config.SiteName+"_login");
if(c!=null){
ForceCookieExpiration();
}
}
HashWithSalt PasswordHash(UserData user, string password)
{
/**Note: The way this hash is computed can not be changed without breaking all password hashes.
* DO NOT TOUCH unless absolutely needed!. We do not use SiteName here because UniqueID is already a salt, and
* SiteName could change in the future, so don't want to limit that flexibility. We DO use UniqueHash however.
* It is also used in generating login cookies. This makes it so if you wanted, you could publish your user database and you're still 99.9% protected
* from hackers figuring out someone's password, or even enough to figure out enough to login.
*/
string text="fscauth"+password+user.UniqueID+Config.UniqueHash;
if(user.Salt==null){
var v=NewHash(text);
return v;
}else{
return new HashWithSalt(){Text=ComputeHash(text, user.Salt), Salt=user.Salt};
}
}
/// <summary>
/// Computes a password hash.
/// </summary>
/// <param name="password">The plain text password</param>
/// <param name="username">The user's username</param>
/// <param name="uniqueid">The user's unique ID</param>
/// <returns></returns>
public void ComputePasswordHash(UserData user, string password)
{
user.Salt=null;
var v=PasswordHash(user, password);
user.PasswordHash=v.Text;
user.Salt=v.Salt;
}
private void LoginFromHash(UserData user, DateTime? expires)
{
var c = new HttpCookie(Config.SiteName + "_login");
if (expires.HasValue)
{
c.Expires = (DateTime)expires;
}
else
{
expires = DateTime.Now.AddHours(4);
}
c.HttpOnly = Config.CookieHttpOnly;
c.Secure = Config.CookieSecure;
c.Values["name"] = user.Username;
c.Values["secret"] = ComputeLoginHash(user.PasswordHash,user.Salt, expires.Value);
c.Values["expire"] = ConvertToUnixTimestamp(expires.Value).ToString();
Server.SetCookie(c);
CurrentUser = user;
}
string ComputeLoginHash(string passwordhash,string salt,DateTime expires){
StringBuilder sb=new StringBuilder();
sb.Append(passwordhash);
if(Config.CookieUseIP){
sb.Append(Server.UserIP);
}
if(Config.CookieUseBrowserInfo){
sb.Append(Server.UserAgent);
}
sb.Append(ConvertToUnixTimestamp(expires).ToString());
sb.Append(Config.UniqueHash);
sb.Append(Config.SiteName);
Debug.Assert(salt!=null);
return ComputeHash(sb.ToString(),salt);
}
/// <summary>
/// Computes a hash using an existing salt
/// </summary>
string ComputeHash(string input, string salt)
{
Debug.Assert(salt != null);
HashWithSalt v=new HashWithSalt();
v.Text=input;
v.Salt=salt;
v=Config.HasherInvoker(v.Text,v.Salt);
return v.Text;
}
/// <summary>
/// Computes a new hash and gets a new salt
/// </summary>
HashWithSalt NewHash(string input)
{
HashWithSalt v=new HashWithSalt();
v.Text=input;
v.Salt=null;
v=Config.HasherInvoker(v.Text,v.Salt);
return v;
}
void ForceCookieExpiration(){
var tmp=new HttpCookie(Config.SiteName+"_login");
tmp.Expires=DateTime.Now.AddYears(-10); //force expiration
HttpContext.Current.Response.Cookies.Add(tmp);
}
static string GetUniqueHash()
{
return ConfigurationManager.AppSettings["FSCAuth_UniqueHash"];
}
static long ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date - origin;
return (long)Math.Floor(diff.TotalSeconds);
}
static DateTime ConvertFromUnixTimestamp(long timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(Convert.ToDouble(timestamp));
}
void SendHttp401(){
Server.HttpStatus="401 Not Authenticated";
if(Config.SiteName==null){
throw new ArgumentNullException("Config.SiteName", "SiteName must be set");
}
Server.SetHeader("WWW-Authenticate", "Basic Realm=\""+Config.SiteName+"\"");
throw new HttpException(401, "Must authenticate");
}
}
}
| |
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System;
class HtmlElement : IElement
{
private ICollection<IElement> childElements;
public HtmlElement(string name)
{
this.Name = name;
this.childElements = new List<IElement>();
}
public HtmlElement(string name, string textContent)
: this(name)
{
this.TextContent = textContent;
}
public string Name { get; private set; }
public virtual string TextContent { get; set; }
public virtual IEnumerable<IElement> ChildElements
{
get { return this.childElements; }
}
public virtual void AddElement(IElement element)
{
this.childElements.Add(element);
}
public virtual void Render(StringBuilder output)
{
output.AppendFormat(!string.IsNullOrEmpty(this.Name) ? "<" + this.Name + ">" : string.Empty);
output.Append(!string.IsNullOrEmpty(this.TextContent) ? this.Encode(this.TextContent) : string.Empty);
foreach (var child in this.ChildElements)
{
child.Render(output);
}
output.AppendFormat(!string.IsNullOrEmpty(this.Name) ? "</" + this.Name + ">" : string.Empty);
}
public override string ToString()
{
var output = new StringBuilder();
this.Render(output);
return output.ToString();
}
protected string Encode(string textContent)
{
return textContent.Replace("&", "&").Replace("<", "<").Replace(">", ">");
}
}
public class HTMLElementFactory : IElementFactory
{
public IElement CreateElement(string name)
{
return new HtmlElement(name);
}
public IElement CreateElement(string name, string content)
{
return new HtmlElement(name, content);
}
public ITable CreateTable(int rows, int cols)
{
return new HtmlTable(rows, cols);
}
}
public class HTMLRendererCommandExecutor
{
static void Main()
{
string csharpCode = ReadInputCSharpCode();
CompileAndRun(csharpCode);
}
private static string ReadInputCSharpCode()
{
StringBuilder result = new StringBuilder();
string line;
while ((line = Console.ReadLine()) != "")
{
result.AppendLine(line);
}
return result.ToString();
}
static void CompileAndRun(string csharpCode)
{
// Prepare a C# program for compilation
string[] csharpClass =
{
@"using System;
public class RuntimeCompiledClass
{
public static void Main()
{" +
csharpCode + @"
}
}"
};
// Compile the C# program
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.GenerateInMemory = true;
compilerParams.TempFiles = new TempFileCollection(".");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
CSharpCodeProvider csharpProvider = new CSharpCodeProvider();
CompilerResults compile = csharpProvider.CompileAssemblyFromSource(
compilerParams, csharpClass);
// Check for compilation errors
if (compile.Errors.HasErrors)
{
string errorMsg = "Compilation error: ";
foreach (CompilerError ce in compile.Errors)
{
errorMsg += "\r\n" + ce.ToString();
}
throw new Exception(errorMsg);
}
// Invoke the Main() method of the compiled class
Assembly assembly = compile.CompiledAssembly;
Module module = assembly.GetModules()[0];
Type type = module.GetType("RuntimeCompiledClass");
MethodInfo methInfo = type.GetMethod("Main");
methInfo.Invoke(null, null);
}
}
class HtmlTable : HtmlElement, ITable
{
private const string TableName = "table";
private const string TableRowOpenTag = "<tr>";
private const string TableRowCloseTag = "</tr>";
private const string TableCellOpenTag = "<td>";
private const string TableCellCloseTag = "</td>";
private IElement[,] childElements;
public HtmlTable(int rows, int cols)
: base(TableName)
{
this.Rows = rows;
this.Cols = cols;
this.childElements = new IElement[this.Rows, this.Cols];
}
public int Rows { get; set; }
public int Cols { get; set; }
public IElement this[int row, int col]
{
get { return this.childElements[row, col]; }
set { this.childElements[row, col] = value; }
}
public override void Render(StringBuilder output)
{
output.AppendFormat("<{0}>", TableName);
for (int row = 0; row < this.Rows; row++)
{
output.Append(TableRowOpenTag);
for (int col = 0; col < this.Cols; col++)
{
output.Append(TableCellOpenTag);
output.Append(this.childElements[row, col]);
output.Append(TableCellCloseTag);
}
output.Append(TableRowCloseTag);
}
output.AppendFormat("</{0}>", TableName);
}
public override string ToString()
{
var output = new StringBuilder();
this.Render(output);
return output.ToString();
}
}
public interface IElement
{
string Name { get; }
string TextContent { get; set; }
IEnumerable<IElement> ChildElements { get; }
void AddElement(IElement element);
void Render(StringBuilder output);
string ToString();
}
public interface IElementFactory
{
IElement CreateElement(string name);
IElement CreateElement(string name, string content);
ITable CreateTable(int rows, int cols);
}
public interface ITable : IElement
{
int Rows { get; }
int Cols { get; }
IElement this[int row, int col] { get; set; }
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
#if !MONO && !NETSTANDARD
namespace NLog.UnitTests.Targets
{
using System.Collections.Generic;
using System.Messaging;
using NLog.Targets;
using Xunit;
public class MessageQueueTargetTests : NLogTestBase
{
[Fact]
public void QueueExists_Write_MessageIsWritten()
{
var messageQueueTestProxy = new MessageQueueTestProxy
{
QueueExists = true,
};
var target = CreateTarget(messageQueueTestProxy, false);
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.Equal(1, messageQueueTestProxy.SentMessages.Count);
}
[Fact]
public void QueueDoesNotExistsAndDoNotCreate_Write_NothingIsWritten()
{
var messageQueueTestProxy = new MessageQueueTestProxy
{
QueueExists = false,
};
var target = CreateTarget(messageQueueTestProxy, false);
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.Equal(0, messageQueueTestProxy.SentMessages.Count);
}
[Fact]
public void QueueDoesNotExistsAndCreatedQueue_Write_QueueIsCreated()
{
var messageQueueTestProxy = new MessageQueueTestProxy
{
QueueExists = false,
};
var target = CreateTarget(messageQueueTestProxy, true);
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.True(messageQueueTestProxy.QueueCreated);
}
[Fact]
public void QueueDoesNotExistsAndCreatedQueue_Write_MessageIsWritten()
{
var messageQueueTestProxy = new MessageQueueTestProxy
{
QueueExists = false,
};
var target = CreateTarget(messageQueueTestProxy, true);
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.Equal(1, messageQueueTestProxy.SentMessages.Count);
}
[Fact]
public void FormatQueueName_Write_DoesNotCheckIfQueueExists()
{
var messageQueueTestProxy = new MessageQueueTestProxy();
var target = CreateTarget(messageQueueTestProxy, false, "DIRECT=http://test.com/MSMQ/queue");
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.False(messageQueueTestProxy.QueueExistsCalled);
}
[Fact]
public void DoNotCheckIfQueueExists_Write_DoesNotCheckIfQueueExists()
{
var messageQueueTestProxy = new MessageQueueTestProxy();
var target = CreateTarget(messageQueueTestProxy, false, checkIfQueueExists: false);
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(_ => { }));
Assert.False(messageQueueTestProxy.QueueExistsCalled);
}
/// <summary>
/// Checks if setting the CheckIfQueueExists is working
/// </summary>
[Fact]
public void MessageQueueTarget_CheckIfQueueExists_setting_should_work()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(string.Format(@"
<nlog throwExceptions='true' >
<targets>
<target type='MSMQ'
name='q'
checkIfQueueExists='False'
queue='queue1' >
</target>
</targets>
<rules>
<logger name='*' writeTo='q'>
</logger>
</rules>
</nlog>"));
LogManager.Configuration = configuration;
var messageQueueTarget = configuration.FindTargetByName("q") as MessageQueueTarget;
Assert.NotNull(messageQueueTarget);
Assert.False(messageQueueTarget.CheckIfQueueExists);
}
private static MessageQueueTarget CreateTarget(MessageQueueProxy messageQueueTestProxy, bool createQueue, string queueName = "Test", bool checkIfQueueExists = true)
{
var target = new MessageQueueTarget
{
MessageQueueProxy = messageQueueTestProxy,
Queue = queueName,
CreateQueueIfNotExists = createQueue,
CheckIfQueueExists = checkIfQueueExists,
};
target.Initialize(null);
return target;
}
internal class MessageQueueTestProxy : MessageQueueProxy
{
public IList<Message> SentMessages { get; private set; }
public bool QueueExists { get; set; }
public bool QueueCreated { get; private set; }
public bool QueueExistsCalled { get; private set; }
public MessageQueueTestProxy()
{
SentMessages = new List<Message>();
}
public override bool Exists(string queue)
{
QueueExistsCalled = true;
return QueueExists;
}
public override void Create(string queue)
{
QueueCreated = true;
}
public override void Send(string queue, Message message)
{
SentMessages.Add(message);
}
}
}
}
#endif
| |
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.VersioningAndUnification.AppConfig
{
public sealed class SpecificVersionPrimary : ResolveAssemblyReferenceTestFixture
{
public SpecificVersionPrimary(ITestOutputHelper output) : base(output)
{
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Exists()
{
// This WriteLine is a hack. On a slow machine, the Tasks unittest fails because remoting
// times out the object used for remoting console writes. Adding a write in the middle of
// keeps remoting from timing out the object.
Console.WriteLine("Performing VersioningAndUnification.Prerequisite.SpecificVersionPrimary.Exists() test");
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
t.ResolvedFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", StringCompareShould.IgnoreCase);
t.ResolvedFiles[0].GetMetadata("ResolvedFrom").ShouldBe(@"{Registry:Software\Microsoft\.NetFramework,v2.0,AssemblyFoldersEx}", StringCompareShould.IgnoreCase);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes a *different* assembly version name from
// 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ExistsDifferentName()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='DontUnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
t.ResolvedFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", StringCompareShould.IgnoreCase);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from range 0.0.0.0-1.5.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ExistsOldVersionRange()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-1.5.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
t.ResolvedFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", StringCompareShould.IgnoreCase);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 4.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 4.0.0.0 of the file *does not* exist.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void HighVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
t.ResolvedFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", StringCompareShould.IgnoreCase);
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary version-strict reference was passed in to assembly version 0.5.0.0
/// - An app.config was passed in that promotes assembly version from 0.0.0.0-2.0.0.0 to 2.0.0.0
/// - Version 0.5.0.0 of the file *does not* exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The reference is not resolved.
/// Rationale:
/// Primary references are never unified--even those that don't exist on disk. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void LowVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=0.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "true");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Empty(t.ResolvedFiles);
// Cleanup.
File.Delete(appConfigFile);
}
}
}
| |
// 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.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.XPath;
using MS.Internal.Xml.XPath;
using System.Globalization;
namespace System.Xml
{
// Represents a single node in the document.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
{
internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly.
internal XmlNode()
{
}
internal XmlNode(XmlDocument doc)
{
if (doc == null)
throw new ArgumentException(SR.Xdom_Node_Null_Doc);
this.parentNode = doc;
}
public virtual XPathNavigator CreateNavigator()
{
XmlDocument thisAsDoc = this as XmlDocument;
if (thisAsDoc != null)
{
return thisAsDoc.CreateNavigator(this);
}
XmlDocument doc = OwnerDocument;
Debug.Assert(doc != null);
return doc.CreateNavigator(this);
}
// Selects the first node that matches the xpath expression
public XmlNode SelectSingleNode(string xpath)
{
XmlNodeList list = SelectNodes(xpath);
// SelectNodes returns null for certain node types
return list != null ? list[0] : null;
}
// Selects the first node that matches the xpath expression and given namespace context.
public XmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp))[0];
}
// Selects all nodes that match the xpath expression
public XmlNodeList SelectNodes(string xpath)
{
XPathNavigator n = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (n == null)
return null;
return new XPathNodeList(n.Select(xpath));
}
// Selects all nodes that match the xpath expression and given namespace context.
public XmlNodeList SelectNodes(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp));
}
// Gets the name of the node.
public abstract string Name
{
get;
}
// Gets or sets the value of the node.
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); }
}
// Gets the type of the current node.
public abstract XmlNodeType NodeType
{
get;
}
// Gets the parent of this node (for nodes that can have parents).
public virtual XmlNode ParentNode
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType != XmlNodeType.Document)
{
return parentNode;
}
// Linear lookup through the children of the document
XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode;
if (firstChild != null)
{
XmlLinkedNode node = firstChild;
do
{
if (node == this)
{
return parentNode;
}
node = node.next;
}
while (node != null
&& node != firstChild);
}
return null;
}
}
// Gets all children of this node.
public virtual XmlNodeList ChildNodes
{
get { return new XmlChildNodes(this); }
}
// Gets the node immediately preceding this node.
public virtual XmlNode PreviousSibling
{
get { return null; }
}
// Gets the node immediately following this node.
public virtual XmlNode NextSibling
{
get { return null; }
}
// Gets a XmlAttributeCollection containing the attributes
// of this node.
public virtual XmlAttributeCollection Attributes
{
get { return null; }
}
// Gets the XmlDocument that contains this node.
public virtual XmlDocument OwnerDocument
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType == XmlNodeType.Document)
return (XmlDocument)parentNode;
return parentNode.OwnerDocument;
}
}
// Gets the first child of this node.
public virtual XmlNode FirstChild
{
get
{
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null)
return linkedNode.next;
return null;
}
}
// Gets the last child of this node.
public virtual XmlNode LastChild
{
get { return LastNode; }
}
internal virtual bool IsContainer
{
get { return false; }
}
internal virtual XmlLinkedNode LastNode
{
get { return null; }
set { }
}
internal bool AncestorNode(XmlNode node)
{
XmlNode n = this.ParentNode;
while (n != null && n != this)
{
if (n == node)
return true;
n = n.ParentNode;
}
return false;
}
//trace to the top to find out its parent node.
internal bool IsConnected()
{
XmlNode parent = ParentNode;
while (parent != null && !(parent.NodeType == XmlNodeType.Document))
parent = parent.ParentNode;
return parent != null;
}
// Inserts the specified node immediately before the specified reference node.
public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return AppendChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertBefore(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
if (node != null)
{
newChild.RemoveChild(node);
InsertBefore(node, refChild);
// insert the rest of the children after this one.
InsertAfter(newChild, node);
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == FirstChild)
{
newNode.next = refNode;
LastNode.next = newNode;
newNode.SetParent(this);
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling;
newNode.next = refNode;
prevNode.next = newNode;
newNode.SetParent(this);
if (prevNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(prevNode, newNode);
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
else
{
if (refNode.IsText)
{
UnnestTextNodes(prevNode, refNode);
}
}
}
else
{
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Inserts the specified node immediately after the specified reference node.
public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return PrependChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertAfter(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode last = refChild;
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
InsertAfter(node, last);
last = node;
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == LastNode)
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
else
{
XmlLinkedNode nextNode = refNode.next;
newNode.next = nextNode;
refNode.next = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
else
{
if (nextNode.IsText)
{
UnnestTextNodes(refNode, nextNode);
}
}
}
else
{
if (newNode.IsText)
{
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Replaces the child node oldChild with newChild node.
public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode nextNode = oldChild.NextSibling;
RemoveChild(oldChild);
XmlNode node = InsertBefore(newChild, nextNode);
return oldChild;
}
// Removes specified child node.
public virtual XmlNode RemoveChild(XmlNode oldChild)
{
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain);
if (oldChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Remove_Child);
XmlLinkedNode oldNode = (XmlLinkedNode)oldChild;
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove);
if (args != null)
BeforeEvent(args);
XmlLinkedNode lastNode = LastNode;
if (oldNode == FirstChild)
{
if (oldNode == lastNode)
{
LastNode = null;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
lastNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
else
{
if (oldNode == lastNode)
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (prevNode.IsText)
{
NestTextNodes(prevNode, nextNode);
}
else
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
}
prevNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
if (args != null)
AfterEvent(args);
return oldChild;
}
// Adds the specified node to the beginning of the list of children of this node.
public virtual XmlNode PrependChild(XmlNode newChild)
{
return InsertBefore(newChild, FirstChild);
}
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode AppendChild(XmlNode newChild)
{
XmlDocument thisDoc = OwnerDocument;
if (thisDoc == null)
{
thisDoc = this as XmlDocument;
}
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
XmlDocument childDoc = newChild.OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
AppendChild(node);
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
//the function is provided only at Load time to speed up Load process
internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParentForLoad(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal virtual bool IsValidChildType(XmlNodeType type)
{
return false;
}
internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
return true;
}
internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
return true;
}
// Gets a value indicating whether this node has any child nodes.
public virtual bool HasChildNodes
{
get { return LastNode != null; }
}
// Creates a duplicate of this node.
public abstract XmlNode CloneNode(bool deep);
internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep)
{
for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling)
{
AppendChildForLoad(child.CloneNode(deep), doc);
}
}
// DOM Level 2
// Puts all XmlText nodes in the full depth of the sub-tree
// underneath this XmlNode into a "normal" form where only
// markup (e.g., tags, comments, processing instructions, CDATA sections,
// and entity references) separates XmlText nodes, that is, there
// are no adjacent XmlText nodes.
public virtual void Normalize()
{
XmlNode firstChildTextLikeNode = null;
StringBuilder sb = StringBuilderCache.Acquire();
for (XmlNode crtChild = this.FirstChild; crtChild != null;)
{
XmlNode nextChild = crtChild.NextSibling;
switch (crtChild.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
{
sb.Append(crtChild.Value);
XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
if (winner == firstChildTextLikeNode)
{
this.RemoveChild(crtChild);
}
else
{
if (firstChildTextLikeNode != null)
this.RemoveChild(firstChildTextLikeNode);
firstChildTextLikeNode = crtChild;
}
break;
}
case XmlNodeType.Element:
{
crtChild.Normalize();
goto default;
}
default:
{
if (firstChildTextLikeNode != null)
{
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
sb.Remove(0, sb.Length);
break;
}
}
crtChild = nextChild;
}
if (firstChildTextLikeNode != null && sb.Length > 0)
firstChildTextLikeNode.Value = sb.ToString();
StringBuilderCache.Release(sb);
}
private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode)
{
//first node has the priority
if (firstNode == null)
return secondNode;
Debug.Assert(firstNode.NodeType == XmlNodeType.Text
|| firstNode.NodeType == XmlNodeType.SignificantWhitespace
|| firstNode.NodeType == XmlNodeType.Whitespace
|| secondNode.NodeType == XmlNodeType.Text
|| secondNode.NodeType == XmlNodeType.SignificantWhitespace
|| secondNode.NodeType == XmlNodeType.Whitespace);
if (firstNode.NodeType == XmlNodeType.Text)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Text)
return secondNode;
if (firstNode.NodeType == XmlNodeType.SignificantWhitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.SignificantWhitespace)
return secondNode;
if (firstNode.NodeType == XmlNodeType.Whitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Whitespace)
return secondNode;
Debug.Assert(true, "shouldn't have fall through here.");
return null;
}
// Test if the DOM implementation implements a specific feature.
public virtual bool Supports(string feature, string version)
{
if (String.Equals("XML", feature, StringComparison.OrdinalIgnoreCase))
{
if (version == null || version == "1.0" || version == "2.0")
return true;
}
return false;
}
// Gets the namespace URI of this node.
public virtual string NamespaceURI
{
get { return string.Empty; }
}
// Gets or sets the namespace prefix of this node.
public virtual string Prefix
{
get { return string.Empty; }
set { }
}
// Gets the name of the node without the namespace prefix.
public abstract string LocalName
{
get;
}
// Microsoft extensions
// Gets a value indicating whether the node is read-only.
public virtual bool IsReadOnly
{
get
{
XmlDocument doc = OwnerDocument;
return HasReadOnlyParent(this);
}
}
internal static bool HasReadOnlyParent(XmlNode n)
{
while (n != null)
{
switch (n.NodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
n = ((XmlAttribute)n).OwnerElement;
break;
default:
n = n.ParentNode;
break;
}
}
return false;
}
// Creates a duplicate of this node.
public virtual XmlNode Clone()
{
return this.CloneNode(true);
}
object ICloneable.Clone()
{
return this.CloneNode(true);
}
// Provides a simple ForEach-style iteration over the
// collection of nodes in this XmlNamedNodeMap.
IEnumerator IEnumerable.GetEnumerator()
{
return new XmlChildEnumerator(this);
}
public IEnumerator GetEnumerator()
{
return new XmlChildEnumerator(this);
}
private void AppendChildText(StringBuilder builder)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.FirstChild == null)
{
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA
|| child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace)
builder.Append(child.InnerText);
}
else
{
child.AppendChildText(builder);
}
}
}
// Gets or sets the concatenated values of the node and
// all its children.
public virtual string InnerText
{
get
{
XmlNode fc = FirstChild;
if (fc == null)
{
return string.Empty;
}
if (fc.NextSibling == null)
{
XmlNodeType nodeType = fc.NodeType;
switch (nodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return fc.Value;
}
}
StringBuilder builder = StringBuilderCache.Acquire();
AppendChildText(builder);
return StringBuilderCache.GetStringAndRelease(builder);
}
set
{
XmlNode firstChild = FirstChild;
if (firstChild != null //there is one child
&& firstChild.NextSibling == null // and exactly one
&& firstChild.NodeType == XmlNodeType.Text)//which is a text node
{
//this branch is for perf reason and event fired when TextNode.Value is changed
firstChild.Value = value;
}
else
{
RemoveAll();
AppendChild(OwnerDocument.CreateTextNode(value));
}
}
}
// Gets the markup representing this node and all its children.
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
}
// Gets or sets the markup representing just the children of this node.
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteContentTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
set
{
throw new InvalidOperationException(SR.Xdom_Set_InnerXml);
}
}
public virtual IXmlSchemaInfo SchemaInfo
{
get
{
return XmlDocument.NotKnownSchemaInfo;
}
}
public virtual String BaseURI
{
get
{
XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref
while (curNode != null)
{
XmlNodeType nt = curNode.NodeType;
//EntityReference's children come from the dtd where they are defined.
//we need to investigate the same thing for entity's children if they are defined in an external dtd file.
if (nt == XmlNodeType.EntityReference)
return ((XmlEntityReference)curNode).ChildBaseURI;
if (nt == XmlNodeType.Document
|| nt == XmlNodeType.Entity
|| nt == XmlNodeType.Attribute)
return curNode.BaseURI;
curNode = curNode.ParentNode;
}
return String.Empty;
}
}
// Saves the current node to the specified XmlWriter.
public abstract void WriteTo(XmlWriter w);
// Saves all the children of the node to the specified XmlWriter.
public abstract void WriteContentTo(XmlWriter w);
// Removes all the children and/or attributes
// of the current node.
public virtual void RemoveAll()
{
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
RemoveChild(child);
child = sibling;
}
}
internal XmlDocument Document
{
get
{
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
return OwnerDocument;
}
}
// Looks up the closest xmlns declaration for the given
// prefix that is in scope for the current node and returns
// the namespace URI in the declaration.
public virtual string GetNamespaceOfPrefix(string prefix)
{
string namespaceName = GetNamespaceOfPrefixStrict(prefix);
return namespaceName != null ? namespaceName : string.Empty;
}
internal string GetNamespaceOfPrefixStrict(string prefix)
{
XmlDocument doc = Document;
if (doc != null)
{
prefix = doc.NameTable.Get(prefix);
if (prefix == null)
return null;
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
if (prefix.Length == 0)
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
return attr.Value; // found xmlns
}
}
}
}
else
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (Ref.Equal(attr.LocalName, prefix))
{
return attr.Value; // found xmlns:prefix
}
}
else if (Ref.Equal(attr.Prefix, prefix))
{
return attr.NamespaceURI; // found prefix:attr
}
}
}
}
if (Ref.Equal(node.Prefix, prefix))
{
return node.NamespaceURI;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strXml, prefix))
{ // xmlns:xml
return doc.strReservedXml;
}
else if (Ref.Equal(doc.strXmlns, prefix))
{ // xmlns:xmlns
return doc.strReservedXmlns;
}
}
return null;
}
// Looks up the closest xmlns declaration for the given namespace
// URI that is in scope for the current node and returns
// the prefix defined in that declaration.
public virtual string GetPrefixOfNamespace(string namespaceURI)
{
string prefix = GetPrefixOfNamespaceStrict(namespaceURI);
return prefix != null ? prefix : string.Empty;
}
internal string GetPrefixOfNamespaceStrict(string namespaceURI)
{
XmlDocument doc = Document;
if (doc != null)
{
namespaceURI = doc.NameTable.Add(namespaceURI);
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return string.Empty; // found xmlns="namespaceURI"
}
}
}
else if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return attr.LocalName; // found xmlns:prefix="namespaceURI"
}
}
else if (Ref.Equal(attr.NamespaceURI, namespaceURI))
{
return attr.Prefix; // found prefix:attr
// with prefix bound to namespaceURI
}
}
}
if (Ref.Equal(node.NamespaceURI, namespaceURI))
{
return node.Prefix;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strReservedXml, namespaceURI))
{ // xmlns:xml
return doc.strXml;
}
else if (Ref.Equal(doc.strReservedXmlns, namespaceURI))
{ // xmlns:xmlns
return doc.strXmlns;
}
}
return null;
}
// Retrieves the first child element with the specified name.
public virtual XmlElement this[string name]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.Name == name)
return (XmlElement)n;
}
return null;
}
}
// Retrieves the first child element with the specified LocalName and
// NamespaceURI.
public virtual XmlElement this[string localname, string ns]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns)
return (XmlElement)n;
}
return null;
}
}
internal virtual void SetParent(XmlNode node)
{
if (node == null)
{
this.parentNode = OwnerDocument;
}
else
{
this.parentNode = node;
}
}
internal virtual void SetParentForLoad(XmlNode node)
{
this.parentNode = node;
}
internal static void SplitName(string name, out string prefix, out string localName)
{
int colonPos = name.IndexOf(':'); // ordinal compare
if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos)
{
prefix = string.Empty;
localName = name;
}
else
{
prefix = name.Substring(0, colonPos);
localName = name.Substring(colonPos + 1);
}
}
internal virtual XmlNode FindChild(XmlNodeType type)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.NodeType == type)
{
return child;
}
}
return null;
}
internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
XmlDocument doc = OwnerDocument;
if (doc != null)
{
if (!doc.IsLoading)
{
if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly)))
throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly);
}
return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
return null;
}
internal virtual void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.BeforeEvent(args);
}
internal virtual void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.AfterEvent(args);
}
internal virtual XmlSpace XmlSpace
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null && elem.HasAttribute("xml:space"))
{
switch (XmlConvert.TrimString(elem.GetAttribute("xml:space")))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
//should we throw exception if value is otherwise?
break;
}
}
node = node.ParentNode;
}
while (node != null);
return XmlSpace.None;
}
}
internal virtual String XmlLang
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null)
{
if (elem.HasAttribute("xml:lang"))
return elem.GetAttribute("xml:lang");
}
node = node.ParentNode;
} while (node != null);
return String.Empty;
}
}
internal virtual XPathNodeType XPNodeType
{
get
{
return (XPathNodeType)(-1);
}
}
internal virtual string XPLocalName
{
get
{
return string.Empty;
}
}
internal virtual string GetXPAttribute(string localName, string namespaceURI)
{
return String.Empty;
}
internal virtual bool IsText
{
get
{
return false;
}
}
public virtual XmlNode PreviousText
{
get
{
return null;
}
}
internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode;
}
internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode.ParentNode;
}
}
}
| |
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
using System.Threading;
namespace RefactoringEssentials
{
#if NR6
public
#endif
static class SyntaxTokenExtensions
{
public static SyntaxNode GetAncestor(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.GetAncestor<SyntaxNode>(predicate);
}
public static T GetAncestor<T>(this SyntaxToken token, Func<T, bool> predicate = null)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.FirstAncestorOrSelf(predicate)
: default(T);
}
public static IEnumerable<T> GetAncestors<T>(this SyntaxToken token)
where T : SyntaxNode
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().OfType<T>()
: Enumerable.Empty<T>();
}
public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxToken token, Func<SyntaxNode, bool> predicate)
{
return token.Parent != null
? token.Parent.AncestorsAndSelf().Where(predicate)
: Enumerable.Empty<SyntaxNode>();
}
public static SyntaxNode GetCommonRoot(this SyntaxToken token1, SyntaxToken token2)
{
// Contract.ThrowIfTrue(token1.RawKind == 0 || token2.RawKind == 0);
// find common starting node from two tokens.
// as long as two tokens belong to same tree, there must be at least on common root (Ex, compilation unit)
if (token1.Parent == null || token2.Parent == null)
{
return null;
}
return token1.Parent.GetCommonRoot(token2.Parent);
}
public static bool CheckParent<T>(this SyntaxToken token, Func<T, bool> valueChecker) where T : SyntaxNode
{
var parentNode = token.Parent as T;
if (parentNode == null)
{
return false;
}
return valueChecker(parentNode);
}
public static int Width(this SyntaxToken token)
{
return token.Span.Length;
}
public static int FullWidth(this SyntaxToken token)
{
return token.FullSpan.Length;
}
public static SyntaxToken FindTokenFromEnd(this SyntaxNode root, int position, bool includeZeroWidth = true, bool findInsideTrivia = false)
{
var token = root.FindToken(position, findInsideTrivia);
var previousToken = token.GetPreviousToken(
includeZeroWidth, findInsideTrivia, findInsideTrivia, findInsideTrivia);
if (token.SpanStart == position &&
previousToken.RawKind != 0 &&
previousToken.Span.End == position)
{
return previousToken;
}
return token;
}
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (foo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// lock (expr)
// |
// for ( ; ; Foo(), |
if (token.Kind() == SyntaxKind.OpenBraceToken &&
token.Parent.IsKind(SyntaxKind.Block))
{
return true;
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var statement = token.GetAncestor<StatementSyntax>();
if (statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
if (token.Kind() == SyntaxKind.CloseBraceToken &&
token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Kind() == SyntaxKind.CloseBraceToken &&
token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (token.Kind() == SyntaxKind.ColonToken)
{
if (token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.LabeledStatement))
{
return true;
}
}
if (token.Kind() == SyntaxKind.DoKeyword &&
token.Parent.IsKind(SyntaxKind.DoStatement))
{
return true;
}
if (token.Kind() == SyntaxKind.CloseParenToken)
{
var parent = token.Parent;
if (parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
}
if (token.Kind() == SyntaxKind.ElseKeyword)
{
return true;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Foo;
// using System;
// |
// [assembly: Foo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
var parenExpr = token.Parent as ParenthesizedExpressionSyntax;
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfNode<T>(this SyntaxToken token)
where T : SyntaxNode
{
var node = token.GetAncestor<T>();
return node != null && token == node.GetLastToken(includeZeroWidth: true);
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if foo || |
// #if foo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax)
{
var prefix = targetToken.Parent as PrefixUnaryExpressionSyntax;
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax)
{
var binary = targetToken.Parent as BinaryExpressionSyntax;
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Foo( |
// Foo(expr, |
// Foo(bar: |
// new Foo( |
// new Foo(expr, |
// new Foo(bar: |
// Foo : base( |
// Foo : base(bar: |
// Foo : this( |
// Foo : ths(bar: |
// Foo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.IsParentKind(SyntaxKind.Argument) &&
targetToken.Parent.GetParent().IsParentKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.GetParent().GetParent().GetParent();
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
if (targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword))
{
return true;
}
return false;
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(SyntaxToken targetToken)
{
// cases:
// int Foo { |
// int Foo { private |
// int Foo { set { } |
// int Foo { set; |
// int Foo { [Bar]|
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Foo { |
// int Foo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Foo { set { } |
// int Foo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
{
return true;
}
// int Foo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Foo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
var decl = node.Parent as TypeDeclarationSyntax;
return decl.TypeParameterList == node;
}
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration))
{
var decl = node.Parent as DelegateDeclarationSyntax;
return decl.TypeParameterList == node;
}
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IFoo<|
// interface IFoo<A,|
// interface IFoo<[Bar]|
// deletate X D<|
// deletate X D<A,|
// deletate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.IsParentKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.GetParent().GetParent()))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as ArgumentSyntax;
if (node != null && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsKindOrHasMatchingText(this SyntaxToken token, SyntaxKind kind)
{
return token.Kind() == kind || token.HasMatchingText(kind);
}
public static bool IsKindOrHasMatchingText(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind)
{
return Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind || token.HasMatchingText(kind);
}
public static bool HasMatchingText(this SyntaxToken token, SyntaxKind kind)
{
return token.ToString() == SyntaxFacts.GetText(kind);
}
public static bool HasMatchingText(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind)
{
return token.ToString() == Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts.GetText(kind);
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind1, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind2)
{
return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind2;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind1, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind2)
{
return Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind2;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind1, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind2, Microsoft.CodeAnalysis.CSharp.SyntaxKind kind3)
{
return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind2
|| Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token) == kind3;
}
public static bool IsKind(this SyntaxToken token, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind1, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind2, Microsoft.CodeAnalysis.VisualBasic.SyntaxKind kind3)
{
return Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind1
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind2
|| Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token) == kind3;
}
public static bool IsKind(this SyntaxToken token, params Microsoft.CodeAnalysis.CSharp.SyntaxKind[] kinds)
{
return kinds.Contains(Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(token));
}
public static bool IsKind(this SyntaxToken token, params Microsoft.CodeAnalysis.VisualBasic.SyntaxKind[] kinds)
{
return kinds.Contains(Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions.Kind(token));
}
public static bool IsLiteral(this SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.FalseKeyword:
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.TrueKeyword:
return true;
default:
return false;
}
}
public static bool IntersectsWith(this SyntaxToken token, int position)
{
return token.Span.IntersectsWith(position);
}
public static SyntaxToken GetPreviousTokenIfTouchingWord(this SyntaxToken token, int position)
{
return token.IntersectsWith(position) && IsWord(token)
? token.GetPreviousToken(includeSkipped: true)
: token;
}
public static bool IsWord(this SyntaxToken token)
{
return token.IsKind(SyntaxKind.IdentifierToken)
|| SyntaxFacts.IsKeywordKind(token.Kind())
|| SyntaxFacts.IsContextualKeyword(token.Kind())
|| SyntaxFacts.IsPreprocessorKeyword(token.Kind());
}
public static SyntaxToken GetNextNonZeroWidthTokenOrEndOfFile(this SyntaxToken token)
{
return token.GetNextTokenOrEndOfFile();
}
public static SyntaxToken GetNextTokenOrEndOfFile(
this SyntaxToken token,
bool includeZeroWidth = false,
bool includeSkipped = false,
bool includeDirectives = false,
bool includeDocumentationComments = false)
{
var nextToken = token.GetNextToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
return nextToken.Kind() == SyntaxKind.None
? token.GetAncestor<CompilationUnitSyntax>().EndOfFileToken
: nextToken;
}
public static SyntaxToken With(this SyntaxToken token, SyntaxTriviaList leading, SyntaxTriviaList trailing)
{
return token.WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
}
/// <summary>
/// Determines whether the given SyntaxToken is the first token on a line in the specified SourceText.
/// </summary>
public static bool IsFirstTokenOnLine(this SyntaxToken token, SourceText text)
{
var previousToken = token.GetPreviousToken(includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
if (previousToken.Kind() == SyntaxKind.None)
{
return true;
}
var tokenLine = text.Lines.IndexOf(token.SpanStart);
var previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart);
return tokenLine > previousTokenLine;
}
public static bool SpansPreprocessorDirective(this IEnumerable<SyntaxToken> tokens)
{
// we want to check all leading trivia of all tokens (except the
// first one), and all trailing trivia of all tokens (except the
// last one).
var first = true;
var previousToken = default(SyntaxToken);
foreach (var token in tokens)
{
if (first)
{
first = false;
}
else
{
// check the leading trivia of this token, and the trailing trivia
// of the previous token.
if (SpansPreprocessorDirective(token.LeadingTrivia) ||
SpansPreprocessorDirective(previousToken.TrailingTrivia))
{
return true;
}
}
previousToken = token;
}
return false;
}
private static bool SpansPreprocessorDirective(SyntaxTriviaList list)
{
return list.Any(t => t.GetStructure() is DirectiveTriviaSyntax);
}
public static SyntaxToken WithoutTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (!token.LeadingTrivia.Any() && !token.TrailingTrivia.Any())
{
return token;
}
return token.With(new SyntaxTriviaList(), new SyntaxTriviaList());
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
params SyntaxTrivia[] trivia)
{
if (trivia.Length == 0)
{
return token;
}
return token.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia);
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
SyntaxTriviaList trivia)
{
if (trivia.Count == 0)
{
return token;
}
return token.WithLeadingTrivia(trivia.Concat(token.LeadingTrivia));
}
public static SyntaxToken WithPrependedLeadingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithPrependedLeadingTrivia(trivia.ToSyntaxTriviaList());
}
public static SyntaxToken WithAppendedTrailingTrivia(
this SyntaxToken token,
IEnumerable<SyntaxTrivia> trivia)
{
return token.WithTrailingTrivia(token.TrailingTrivia.Concat(trivia));
}
/// <summary>
/// Retrieves all trivia after this token, including it's trailing trivia and
/// the leading trivia of the next token.
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllTrailingTrivia(this SyntaxToken token)
{
foreach (var trivia in token.TrailingTrivia)
{
yield return trivia;
}
var nextToken = token.GetNextTokenOrEndOfFile(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
foreach (var trivia in nextToken.LeadingTrivia)
{
yield return trivia;
}
}
public static bool TryParseGenericName(this SyntaxToken genericIdentifier, CancellationToken cancellationToken, out GenericNameSyntax genericName)
{
if (genericIdentifier.GetNextToken(includeSkipped: true).Kind() == SyntaxKind.LessThanToken)
{
var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName();
var syntaxTree = genericIdentifier.SyntaxTree;
var name = SyntaxFactory.ParseName(syntaxTree.GetText(cancellationToken).ToString(TextSpan.FromBounds(genericIdentifier.SpanStart, lastToken.Span.End)));
genericName = name as GenericNameSyntax;
return genericName != null;
}
genericName = null;
return false;
}
/// <summary>
/// Lexically, find the last token that looks like it's part of this generic name.
/// </summary>
/// <param name="genericIdentifier">The "name" of the generic identifier, last token before
/// the "&"</param>
/// <returns>The last token in the name</returns>
/// <remarks>This is related to the code in <see cref="SyntaxTreeExtensions.IsInPartiallyWrittenGeneric(SyntaxTree, int, CancellationToken)"/></remarks>
public static SyntaxToken FindLastTokenOfPartialGenericName(this SyntaxToken genericIdentifier)
{
//Contract.ThrowIfFalse(genericIdentifier.Kind() == SyntaxKind.IdentifierToken);
// advance to the "<" token
var token = genericIdentifier.GetNextToken(includeSkipped: true);
//Contract.ThrowIfFalse(token.Kind() == SyntaxKind.LessThanToken);
int stack = 0;
do
{
// look forward one token
{
var next = token.GetNextToken(includeSkipped: true);
if (next.Kind() == SyntaxKind.None)
{
return token;
}
token = next;
}
if (token.Kind() == SyntaxKind.GreaterThanToken)
{
if (stack == 0)
{
return token;
}
else
{
stack--;
continue;
}
}
switch (token.Kind())
{
case SyntaxKind.LessThanLessThanToken:
stack++;
goto case SyntaxKind.LessThanToken;
// fall through
case SyntaxKind.LessThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
case SyntaxKind.CommaToken:
break;
// If we see a member declaration keyword, we know we've gone too far
case SyntaxKind.ClassKeyword:
case SyntaxKind.StructKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.DelegateKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.VoidKeyword:
return token.GetPreviousToken(includeSkipped: true);
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk. Go back to the token before.
return token.GetPreviousToken(includeSkipped: true);
}
}
while (true);
}
public static bool IsRegularStringLiteral(this SyntaxToken token)
{
return token.Kind() == SyntaxKind.StringLiteralToken && !token.IsVerbatimStringLiteral();
}
public static bool IsValidAttributeTarget(this SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.FieldKeyword:
case SyntaxKind.EventKeyword:
case SyntaxKind.MethodKeyword:
case SyntaxKind.ParamKeyword:
case SyntaxKind.PropertyKeyword:
case SyntaxKind.ReturnKeyword:
case SyntaxKind.TypeKeyword:
return true;
default:
return false;
}
}
public static bool IsIdentifierOrAccessorOrAccessibilityModifier(this SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.IdentifierToken:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.PublicKeyword:
return true;
default:
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Axiom.Core;
using Axiom.Graphics;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using D3D = Microsoft.DirectX.Direct3D;
namespace Axiom.RenderSystems.DirectX9.HLSL {
public class HLSLInclude : Microsoft.DirectX.Direct3D.Include
{
public override System.IO.Stream Open(IncludeType includeType, string filename)
{
return GpuProgramManager.Instance.FindResourceData(filename);
}
}
/// <summary>
/// Summary description for HLSLProgram.
/// </summary>
public class HLSLProgram : HighLevelGpuProgram {
#region Fields
/// <summary>
/// Shader profile to target for the compile (i.e. vs1.1, etc).
/// </summary>
protected string target;
/// <summary>
/// Entry point to compile from the program.
/// </summary>
protected string entry;
/// <summary>
/// Determines how auto-bound matrices are passed the shader
/// </summary>
protected bool columnMajorMatrices = true;
/// <summary>
/// Normally shaders will be ogre/cg compatible and use the form mul(m,v), no matter
/// how columnMajorMatrices is set. Set this flag to true if your shader uses
/// the form mul(v,m), which is what the DirectX9 SDK, FXComposer and Mental Mill use.
/// </summary>
protected bool sdkMulCompat = false;
/// <summary>
/// Holds preprocessor defines to be fed to the compiler
/// </summary>
protected string preprocessorDefines = "";
/// <summary>
/// Holds the low level program instructions after the compile.
/// </summary>
protected Microsoft.DirectX.GraphicsStream microcode;
/// <summary>
/// Holds information about shader constants.
/// </summary>
protected D3D.ConstantTable constantTable;
#endregion Fields
#region Constructor
public HLSLProgram(string name, GpuProgramType type, string language)
: base(name, type, language) {
}
#endregion Constructor
#region GpuProgram Members
/// <summary>
/// Creates a low level implementation based on the results of the
/// high level shader compilation.
/// </summary>
protected override void CreateLowLevelImpl() {
// create a new program, without source since we are setting the microcode manually
assemblerProgram =
GpuProgramManager.Instance.CreateProgramFromString(name, "", type, target);
// set the microcode for this program
((D3DGpuProgram)assemblerProgram).ExternalMicrocode = microcode;
}
public override GpuProgramParameters CreateParameters() {
GpuProgramParameters parms = base.CreateParameters();
if (sdkMulCompat)
{
parms.TransposeMatrices = !columnMajorMatrices;
}
else
{
parms.TransposeMatrices = columnMajorMatrices;
}
return parms;
}
/// <summary>
/// Compiles the high level shader source to low level microcode.
/// </summary>
protected override void LoadFromSource() {
string errors;
Macro [] macros = null;
if (preprocessorDefines != "") {
string [] values = preprocessorDefines.Split(new char[] {',', ';'});
macros = new Macro[values.Length];
for (int i=0; i<values.Length; i++) {
string s = values[i].Trim();
string [] stm = s.Split(new char[] {'='});
Macro macro = new Macro();
if (stm.Length == 1)
macro.Name = s;
else {
macro.Name = stm[0].Trim();
macro.Definition = stm[1].Trim();
}
macros[i] = macro;
}
}
// compile the high level shader to low level microcode
// note, we need to pack matrices in row-major format for HLSL
microcode =
ShaderLoader.CompileShader(
source,
entry,
macros,
new HLSLInclude(),
target,
(columnMajorMatrices ? ShaderFlags.PackMatrixColumnMajor : ShaderFlags.PackMatrixRowMajor),
out errors,
out constantTable);
//LogManager.Instance.Write(ShaderLoader.DisassembleShader(microcode, false, null));
// check for errors
if(errors != null && errors.Length > 0) {
LogManager.Instance.Write("Error compiling HLSL shader {0}:\n{1}", name, errors);
// errors can include warnings, so don't throw unless the compile actually failed.
if (microcode == null)
{
throw new AxiomException("HLSL: Unable to compile high level shader {0}:\n{1}", name, errors);
}
}
}
/// <summary>
/// Dervices parameter names from the constant table.
/// </summary>
/// <param name="parms"></param>
protected override void PopulateParameterNames(GpuProgramParameters parms) {
Debug.Assert(constantTable != null);
D3D.ConstantTableDescription desc = constantTable.Description;
// iterate over the constants
for(int i = 0; i < desc.Constants; i++) {
// Recursively descend through the structure levels
// Since D3D9 has no nice 'leaf' method like Cg (sigh)
ProcessParamElement(null, "", i, parms);
}
}
/// <summary>
/// Unloads data that is no longer needed.
/// </summary>
protected override void UnloadHighLevelImpl() {
if (microcode != null) {
microcode.Close();
microcode = null;
}
if (constantTable != null) {
constantTable.Dispose();
constantTable = null;
}
}
public override bool IsSupported {
get {
// If skeletal animation is being done, we need support for UBYTE4
if(this.IsSkeletalAnimationIncluded &&
!Root.Instance.RenderSystem.Caps.CheckCap(Capabilities.VertexFormatUByte4)) {
return false;
}
return GpuProgramManager.Instance.IsSyntaxSupported(target);
}
}
#endregion GpuProgram Members
#region Methods
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="prefix"></param>
/// <param name="index"></param>
/// <param name="parms"></param>
protected void ProcessParamElement(D3D.EffectHandle parent, string prefix, int index, GpuProgramParameters parms) {
D3D.EffectHandle constant = constantTable.GetConstant(parent, index);
// Since D3D HLSL doesn't deal with naming of array and struct parameters
// automatically, we have to do it by hand
D3D.ConstantDescription[] descs = constantTable.GetConstantDescription(constant, 1);
D3D.ConstantDescription desc = descs[0];
string paramName = desc.Name;
// trim the odd '$' which appears at the start of the names in HLSL
if(paramName.StartsWith("$")) {
paramName = paramName.Remove(0, 1);
}
// If it's an array, elements will be > 1
for(int e = 0; e < desc.Elements; e++) {
if(desc.Class == ParameterClass.Struct) {
// work out a new prefix for the nextest members
// if its an array, we need the index
if(desc.Elements > 1) {
prefix += string.Format("{0}[{1}].", paramName, e);
}
else {
prefix += ".";
}
// cascade into the struct members
for(int i = 0; i < desc.StructMembers; i++) {
ProcessParamElement(constant, prefix, i, parms);
}
}
else {
// process params
if(desc.ParameterType == ParameterType.Float ||
desc.ParameterType == ParameterType.Integer ||
desc.ParameterType == ParameterType.Boolean) {
int paramIndex = desc.RegisterIndex;
string newName = prefix + paramName;
// if this is an array, we need to appent the element index
if(desc.Elements > 1) {
newName += string.Format("[{0}]", e);
}
// map the named param to the index
parms.MapParamNameToIndex(newName, paramIndex+e);
}
}
}
}
#endregion Methods
#region Properties
public override int SamplerCount
{
get
{
switch (target)
{
case "ps_1_1":
case "ps_1_2":
case "ps_1_3":
return 4;
case "ps_1_4":
return 6;
case "ps_2_0":
case "ps_2_a":
case "ps_2_x":
case "ps_3_0":
case "ps_3_x":
return 16;
default:
throw new AxiomException("Attempted to query sample count for unknown shader profile({0}).", target);
}
// return 0;
}
}
#endregion
#region IConfigurable Members
/// <summary>
/// Sets a param for this HLSL program.
/// </summary>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public override bool SetParam(string name, string val) {
bool handled = true;
switch(name) {
case "entry_point":
entry = val;
break;
case "target":
target = val.Split(' ')[0];
break;
case "column_major_matrices":
if (val.ToLower() == "false")
{
columnMajorMatrices = false;
}
break;
case "preprocessor_defines":
preprocessorDefines = val;
break;
case "sdk_mul_compat":
if (val.ToLower() == "true")
{
sdkMulCompat = true;
}
break;
default:
LogManager.Instance.Write("HLSLProgram: Unrecognized parameter '{0}'", name);
handled = false;
break;
}
return handled;
}
#endregion IConfigurable Members
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using FileStaging;
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : ITransportObjectProvider<Models.TaskAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<AffinityInformation> AffinityInformationProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<ComputeNodeInformation> ComputeNodeInformationProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<TaskDependencies> DependsOnProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<TaskExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<ExitConditions> ExitConditionsProperty;
public readonly PropertyAccessor<IList<IFileStagingProvider>> FilesToStageProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<MultiInstanceSettings> MultiInstanceSettingsProperty;
public readonly PropertyAccessor<IList<OutputFile>> OutputFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<TaskStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor<AffinityInformation>(nameof(AffinityInformation), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>(nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor<ComputeNodeInformation>(nameof(ComputeNodeInformation), BindingAccess.None);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.DependsOnProperty = this.CreatePropertyAccessor<TaskDependencies>(nameof(DependsOn), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<TaskExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None);
this.ExitConditionsProperty = this.CreatePropertyAccessor<ExitConditions>(nameof(ExitConditions), BindingAccess.Read | BindingAccess.Write);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(nameof(FilesToStage), BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor<MultiInstanceSettings>(nameof(MultiInstanceSettings), BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor<IList<OutputFile>>(nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.TaskState?>(nameof(PreviousState), BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.TaskState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<TaskStatistics>(nameof(Statistics), BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudTask protocolObject) : base(BindingState.Bound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AffinityInfo, o => new AffinityInformation(o).Freeze()),
nameof(AffinityInformation),
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollectionAndFreeze(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o).Freeze()),
nameof(AuthenticationTokenSettings),
BindingAccess.Read);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
nameof(CommandLine),
BindingAccess.Read);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodeInfo, o => new ComputeNodeInformation(o).Freeze()),
nameof(ComputeNodeInformation),
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()),
nameof(ContainerSettings),
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.DependsOnProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DependsOn, o => new TaskDependencies(o).Freeze()),
nameof(DependsOn),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.EnvironmentSettings),
nameof(EnvironmentSettings),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()),
nameof(ExecutionInformation),
BindingAccess.Read);
this.ExitConditionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExitConditions, o => new ExitConditions(o).Freeze()),
nameof(ExitConditions),
BindingAccess.Read);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(
nameof(FilesToStage),
BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.MultiInstanceSettings, o => new MultiInstanceSettings(o).Freeze()),
nameof(MultiInstanceSettings),
BindingAccess.Read);
this.OutputFilesProperty = this.CreatePropertyAccessor(
OutputFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.OutputFiles),
nameof(OutputFiles),
BindingAccess.Read);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.PreviousState),
nameof(PreviousState),
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
nameof(PreviousStateTransitionTime),
BindingAccess.Read);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.ResourceFiles),
nameof(ResourceFiles),
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new TaskStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o).Freeze()),
nameof(UserIdentity),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentJobId;
internal string ParentJobId
{
get
{
return this.parentJobId;
}
}
#region Constructors
internal CloudTask(
BatchClient parentBatchClient,
string parentJobId,
Models.CloudTask protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentJobId = parentJobId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudTask"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudTask
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service to select a node on which to start the task.
/// </summary>
public AffinityInformation AffinityInformation
{
get { return this.propertyContainer.AffinityInformationProperty.Value; }
set { this.propertyContainer.AffinityInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with an authentication token which can be used to
/// authenticate Batch service operations without requiring an account access key. The token is provided via the
/// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token
/// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job,
/// or check the status of the job or of other tasks.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets information about the compute node on which the task ran.
/// </summary>
public ComputeNodeInformation ComputeNodeInformation
{
get { return this.propertyContainer.ComputeNodeInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the settings for the container under which the task runs.
/// </summary>
/// <remarks>
/// If the pool that will run this task has <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> set,
/// this must be set as well. If the pool that will run this task doesn't have <see cref="VirtualMachineConfiguration.ContainerConfiguration"/>
/// set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR
/// (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables
/// are mapped into the container, and the task command line is executed in the container.
/// </remarks>
public TaskContainerSettings ContainerSettings
{
get { return this.propertyContainer.ContainerSettingsProperty.Value; }
set { this.propertyContainer.ContainerSettingsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the task.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets any other tasks that this <see cref="CloudTask"/> depends on. The task will not be scheduled until
/// all depended-on tasks have completed successfully.
/// </summary>
/// <remarks>
/// The job must set <see cref="CloudJob.UsesTaskDependencies"/> to true in order to use task dependencies. If UsesTaskDependencies
/// is false (the default), adding a task with dependencies will fail with an error.
/// </remarks>
public TaskDependencies DependsOn
{
get { return this.propertyContainer.DependsOnProperty.Value; }
set { this.propertyContainer.DependsOnProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the ETag for the task.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the task.
/// </summary>
public TaskExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets how the Batch service should respond when the task completes.
/// </summary>
public ExitConditions ExitConditions
{
get { return this.propertyContainer.ExitConditionsProperty.Value; }
set { this.propertyContainer.ExitConditionsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files to be staged for the task.
/// </summary>
public IList<IFileStagingProvider> FilesToStage
{
get { return this.propertyContainer.FilesToStageProperty.Value; }
set
{
this.propertyContainer.FilesToStageProperty.Value = ConcurrentChangeTrackedList<IFileStagingProvider>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the task.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets information about how to run the multi-instance task.
/// </summary>
public MultiInstanceSettings MultiInstanceSettings
{
get { return this.propertyContainer.MultiInstanceSettingsProperty.Value; }
set { this.propertyContainer.MultiInstanceSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will upload from the compute node after running the command
/// line.
/// </summary>
public IList<OutputFile> OutputFiles
{
get { return this.propertyContainer.OutputFilesProperty.Value; }
set
{
this.propertyContainer.OutputFilesProperty.Value = ConcurrentChangeTrackedModifiableList<OutputFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the previous state of the task.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousState property is not
/// defined.
/// </remarks>
public Common.TaskState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its previous state.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the current state of the task.
/// </summary>
public Common.TaskState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the task.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudTask"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public TaskStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the task.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // CloudTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.TaskAddParameter ITransportObjectProvider<Models.TaskAddParameter>.GetTransportObject()
{
Models.TaskAddParameter result = new Models.TaskAddParameter()
{
AffinityInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.AffinityInformation, (o) => o.GetTransportObject()),
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()),
DependsOn = UtilitiesInternal.CreateObjectWithNullCheck(this.DependsOn, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
ExitConditions = UtilitiesInternal.CreateObjectWithNullCheck(this.ExitConditions, (o) => o.GetTransportObject()),
Id = this.Id,
MultiInstanceSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.MultiInstanceSettings, (o) => o.GetTransportObject()),
OutputFiles = UtilitiesInternal.ConvertToProtocolCollection(this.OutputFiles),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace CodeUnderTest {
#region Contracts
[ContractClass(typeof(ContractForOverriddenInterface))]
interface IRewrittenInheritanceOverriddenInterface {
void ImplicitlyOverriddenInterfaceRequires(bool mustBeTrue);
void ImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue);
void ExplicitlyOverriddenInterfaceRequires(bool mustBeTrue);
void ExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue);
}
[ContractClassFor(typeof(IRewrittenInheritanceOverriddenInterface))]
abstract class ContractForOverriddenInterface : IRewrittenInheritanceOverriddenInterface {
void IRewrittenInheritanceOverriddenInterface.ImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
void IRewrittenInheritanceOverriddenInterface.ImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
public void ExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
public void ExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
}
[ContractClass(typeof(ContractForMultipleInheritanceInterface))]
public interface IRewrittenMultipleInheritanceInterface {
void MultiplyImplicitlyOverriddenInterfaceRequires(bool mustBeTrue);
void MultiplyImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue);
void MultiplyExplicitlyOverriddenInterfaceRequires(bool mustBeTrue);
void MultiplyExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue);
void MultiplyDifferentlyOverriddenInterfaceRequires(bool mustBeTrue);
void MultiplyDifferentlyOverriddenInterfaceEnsures(bool mustBeTrue);
}
[ContractClassFor(typeof(IRewrittenMultipleInheritanceInterface))]
abstract class ContractForMultipleInheritanceInterface : IRewrittenMultipleInheritanceInterface {
void IRewrittenMultipleInheritanceInterface.MultiplyImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
void IRewrittenMultipleInheritanceInterface.MultiplyImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
void IRewrittenMultipleInheritanceInterface.MultiplyDifferentlyOverriddenInterfaceRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
void IRewrittenMultipleInheritanceInterface.MultiplyDifferentlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
}
[ContractClass(typeof(ContractForInterfaceBase))]
public interface IRewrittenInheritanceInterfaceBase {
void InterfaceBaseRequires(bool mustBeTrue);
void InterfaceBaseEnsures(bool mustBeTrue);
}
[ContractClassFor(typeof(IRewrittenInheritanceInterfaceBase))]
abstract class ContractForInterfaceBase : IRewrittenInheritanceInterfaceBase {
void IRewrittenInheritanceInterfaceBase.InterfaceBaseRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
void IRewrittenInheritanceInterfaceBase.InterfaceBaseEnsures(bool mustBeTrue)
{
Contract.Ensures(mustBeTrue);
}
}
[ContractClass(typeof(ContractForInterfaceDerived1))]
public interface IRewrittenInheritanceInterfaceDerived1 : IRewrittenInheritanceInterfaceBase {
void InterfaceRequires(int value);
void InterfaceEnsures(int value);
void InterfaceRequiresMultipleOfTwo(int value);
void InterfaceEnsuresMultipleOfTwo(int value);
}
[ContractClassFor(typeof(IRewrittenInheritanceInterfaceDerived1))]
abstract class ContractForInterfaceDerived1 : IRewrittenInheritanceInterfaceDerived1 {
void IRewrittenInheritanceInterfaceDerived1.InterfaceRequires(int value)
{
Contract.Requires(value % 2 == 0);
}
void IRewrittenInheritanceInterfaceDerived1.InterfaceEnsures(int value)
{
Contract.Ensures(value % 2 == 0);
}
void IRewrittenInheritanceInterfaceDerived1.InterfaceRequiresMultipleOfTwo(int value)
{
Contract.Requires(value % 2 == 0);
}
void IRewrittenInheritanceInterfaceDerived1.InterfaceEnsuresMultipleOfTwo(int value)
{
Contract.Ensures(value % 2 == 0);
}
void IRewrittenInheritanceInterfaceBase.InterfaceBaseRequires(bool mustBeTrue) { }
void IRewrittenInheritanceInterfaceBase.InterfaceBaseEnsures(bool mustBeTrue) { }
}
[ContractClass(typeof(ContractForInterfaceDerived2))]
public interface IRewrittenInheritanceInterfaceDerived2 : IRewrittenInheritanceInterfaceBase {
void InterfaceRequires(int value);
void InterfaceEnsures(int value);
void InterfaceRequiresMultipleOfThree(int value);
void InterfaceEnsuresMultipleOfThree(int value);
}
[ContractClassFor(typeof(IRewrittenInheritanceInterfaceDerived2))]
abstract class ContractForInterfaceDerived2 : IRewrittenInheritanceInterfaceDerived2 {
void IRewrittenInheritanceInterfaceDerived2.InterfaceRequires(int value)
{
Contract.Requires(value % 3 == 0);
}
void IRewrittenInheritanceInterfaceDerived2.InterfaceEnsures(int value)
{
Contract.Ensures(value % 3 == 0);
}
void IRewrittenInheritanceInterfaceDerived2.InterfaceRequiresMultipleOfThree(int value)
{
Contract.Requires(value % 3 == 0);
}
void IRewrittenInheritanceInterfaceDerived2.InterfaceEnsuresMultipleOfThree(int value)
{
Contract.Ensures(value % 3 == 0);
}
void IRewrittenInheritanceInterfaceBase.InterfaceBaseRequires(bool mustBeTrue) { }
void IRewrittenInheritanceInterfaceBase.InterfaceBaseEnsures(bool mustBeTrue) { }
}
public class RewrittenInheritanceBase : IRewrittenInheritanceOverriddenInterface, IRewrittenMultipleInheritanceInterface {
public bool BaseValueMustBeTrue = true;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(BaseValueMustBeTrue);
}
public virtual void LegacyRequires(string mustBeNonNull)
{
#if LEGACY
if (mustBeNonNull == null) throw new ArgumentNullException("mustBeNonNull");
Contract.EndContractBlock();
#else
Contract.Requires<ArgumentNullException>(mustBeNonNull != null, "mustBeNonNull");
#endif
}
public virtual void RequiresWithException(string mustBeNonNull)
{
#if LEGACY
if (mustBeNonNull == null) throw new ArgumentNullException("mustBeNonNull != null");
Contract.EndContractBlock();
#else
Contract.Requires<ArgumentNullException>(mustBeNonNull != null);
#endif
}
public virtual void BareRequires(bool mustBeTrue)
{
Contract.Requires(mustBeTrue);
}
public virtual void AdditiveRequires(int mustBePositive)
{
Contract.Requires(mustBePositive > 0);
}
public virtual void SubtractiveRequires(int mustBeAbove100)
{
Contract.Requires(mustBeAbove100 > 100);
}
public virtual void AdditiveEnsures(int mustBePositive)
{
Contract.Ensures(mustBePositive > 0);
}
public virtual void SubtractiveEnsures(int mustBeAbove100)
{
Contract.Ensures(mustBeAbove100 > 100);
}
public virtual void ImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public virtual void ImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
void IRewrittenInheritanceOverriddenInterface.ExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
void IRewrittenInheritanceOverriddenInterface.ExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
public virtual void ExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public virtual void ExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
public virtual void MultiplyImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public virtual void MultiplyImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
public virtual void MultiplyDifferentlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public virtual void MultiplyDifferentlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
}
public class RewrittenInheritanceDerived : RewrittenInheritanceBase, IRewrittenInheritanceInterfaceDerived1, IRewrittenInheritanceInterfaceDerived2, IRewrittenMultipleInheritanceInterface {
public bool InheritedValueMustBeTrue = true;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(InheritedValueMustBeTrue);
}
public void SetInheritedValueMustBeTrue(bool value)
{
this.InheritedValueMustBeTrue = value;
}
public void SetBaseValueMustBeTrue(bool value)
{
this.BaseValueMustBeTrue = value;
}
public override void LegacyRequires(string mustBeNonNull)
{
#if LEGACY
if (mustBeNonNull == null) throw new ArgumentNullException("mustBeNonNull");
Contract.EndContractBlock();
#endif
}
public override void RequiresWithException(string mustBeNonNull)
{
#if LEGACY
if (mustBeNonNull == null) throw new ArgumentNullException("mustBeNonNull");
Contract.EndContractBlock();
#endif
}
public override void BareRequires(bool mustBeTrue)
{
}
public override void AdditiveRequires(int mustBePositive)
{
// test that preconditions are inherited
}
public override void AdditiveEnsures(int mustBeAbove100)
{
Contract.Ensures(mustBeAbove100 > 100);
}
public override void SubtractiveEnsures(int mustBePositive)
{
Contract.Ensures(mustBePositive > 0);
}
public void InterfaceBaseRequires(bool mustBeTrue)
{
}
public void InterfaceBaseEnsures(bool mustBeTrue)
{
}
public void InterfaceRequires(int value)
{
}
public void InterfaceEnsures(int value)
{
}
public void InterfaceRequiresMultipleOfTwo(int value)
{
}
public void InterfaceEnsuresMultipleOfTwo(int value)
{
}
void IRewrittenInheritanceInterfaceDerived2.InterfaceRequiresMultipleOfThree(int value)
{
}
void IRewrittenInheritanceInterfaceDerived2.InterfaceEnsuresMultipleOfThree(int value)
{
}
public void InterfaceRequiresMultipleOfThree(int value)
{
}
public void InterfaceEnsuresMultipleOfThree(int value)
{
}
public override void ImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public override void ImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
public override void ExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public override void ExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
#if CrashTheWriterFixups
public override void MultiplyImplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
public override void MultiplyImplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
#endif
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
void IRewrittenMultipleInheritanceInterface.MultiplyExplicitlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
void IRewrittenMultipleInheritanceInterface.MultiplyDifferentlyOverriddenInterfaceRequires(bool mustBeTrue)
{
}
void IRewrittenMultipleInheritanceInterface.MultiplyDifferentlyOverriddenInterfaceEnsures(bool mustBeTrue)
{
}
}
[ContractClass(typeof(QuantifierTest_Contract_ImplicitImplementations))]
public interface IQuantifierTest1 {
bool ModifyArray(int[] xs, int x, bool shouldBeCorrect);
int[] CopyArray(int[] xs, bool shouldBeCorrect);
}
[ContractClassFor(typeof(IQuantifierTest1))]
abstract class QuantifierTest_Contract_ImplicitImplementations : IQuantifierTest1 {
bool IQuantifierTest1.ModifyArray(int[] xs, int x, bool shouldBeCorrect)
{
Contract.Requires(xs != null && 0 < xs.Length);
Contract.Ensures(Contract.Result<bool>() ==
Contract.ForAll<int>(xs, delegate(int i) { return i < x; })
);
return default(bool);
}
int[] IQuantifierTest1.CopyArray(int[] xs, bool shouldBeCorrect)
{
Contract.Requires(xs != null && 0 < xs.Length);
Contract.Ensures(Contract.Exists<int>(xs,
delegate(int i) { return xs[i] == Contract.Result<int[]>()[i]; }
)
);
return default(int[]);
}
}
public class QuantifierTest1 : IQuantifierTest1 {
public bool ModifyArray(int[] ys, int x, bool shouldBeCorrect)
{
for (int i = 0; i < ys.Length; i++)
ys[i] = x - 1;
if (!shouldBeCorrect)
ys[ys.Length - 1] = x;
return true;
}
public int[] CopyArray(int[] xs, bool shouldBeCorrect)
{
// strengthen the postcondition
Contract.Ensures(
Contract.ForAll(0, xs.Length,
delegate(int i) { return xs[i] == Contract.Result<int[]>()[i]; })
);
int[] res = new int[xs.Length];
if (shouldBeCorrect)
{
for (int i = 0; i < xs.Length; i++)
res[i] = xs[i];
}
else
{
int max = Int32.MinValue;
foreach (int x in xs) if (max < x) max = x;
for (int i = 0; i < xs.Length; i++)
res[i] = max + 1;
}
return res;
}
}
[ContractClass(typeof(QuantifierTest_Contract_ExplicitImplementations))]
public interface IQuantifierTest2 {
bool ModifyArray(int[] xs, int x, bool shouldBeCorrect);
int[] CopyArray(int[] xs, bool shouldBeCorrect);
}
[ContractClassFor(typeof(IQuantifierTest2))]
abstract class QuantifierTest_Contract_ExplicitImplementations : IQuantifierTest2 {
bool IQuantifierTest2.ModifyArray(int[] xs, int x, bool shouldBeCorrect)
{
Contract.Requires(xs != null && 0 < xs.Length);
Contract.Ensures(Contract.Result<bool>() ==
Contract.ForAll<int>(xs, delegate(int i) { return i < x; })
);
return default(bool);
}
int[] IQuantifierTest2.CopyArray(int[] xs, bool shouldBeCorrect)
{
Contract.Requires(xs != null && 0 < xs.Length);
Contract.Ensures(Contract.Exists<int>(xs,
delegate(int i) { return xs[i] == Contract.Result<int[]>()[i]; }
)
);
return default(int[]);
}
}
public class QuantifierTest2 : IQuantifierTest2 {
public bool ModifyArray(int[] ys, int x, bool shouldBeCorrect)
{
for (int i = 0; i < ys.Length; i++)
ys[i] = x - 1;
if (!shouldBeCorrect)
ys[ys.Length - 1] = x;
return true;
}
public int[] CopyArray(int[] xs, bool shouldBeCorrect)
{
// strengthen the postcondition
Contract.Ensures(
Contract.ForAll(0, xs.Length,
delegate(int i) { return xs[i] == Contract.Result<int[]>()[i]; })
);
int[] res = new int[xs.Length];
if (shouldBeCorrect)
{
for (int i = 0; i < xs.Length; i++)
res[i] = xs[i];
}
else
{
int max = Int32.MinValue;
foreach (int x in xs) if (max < x) max = x;
for (int i = 0; i < xs.Length; i++)
res[i] = max + 1;
}
return res;
}
}
[ContractClass(typeof(AbstractClassInterfaceContract))]
public interface AbstractClassInterface {
string M(bool shouldBeCorrect);
}
[ContractClassFor(typeof(AbstractClassInterface))]
abstract class AbstractClassInterfaceContract : AbstractClassInterface {
string AbstractClassInterface.M(bool shouldBeCorrect)
{
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
return default(string);
}
}
public abstract class AbstractClassInterfaceImplementation : AbstractClassInterface {
public abstract string M(bool shouldBeCorrect);
}
public class AbstractClassInterfaceImplementationSubType : AbstractClassInterfaceImplementation {
public override string M(bool shouldBeCorrect)
{
return shouldBeCorrect ? "abc" : "";
}
}
public class BaseClassWithMethodCallInContract {
public virtual int P { get { return 0; } }
public virtual int M(int x)
{
Contract.Requires(P < x);
return 3;
}
}
public class DerivedClassForBaseClassWithMethodCallInContract : BaseClassWithMethodCallInContract {
public override int M(int y)
{
return 27;
}
}
public class BaseClassWithOldAndResult {
public virtual void InheritOld(ref int x, bool shouldBeCorrect)
{
Contract.Requires(1 <= x);
Contract.Ensures(Contract.OldValue(x) < x);
if (shouldBeCorrect) x++;
return;
}
public virtual void InheritOldInQuantifier(int[] xs, bool shouldBeCorrect)
{
Contract.Requires(0 < xs.Length);
Contract.Requires(Contract.ForAll(xs, delegate(int x) { return 0 < x; }));
Contract.Ensures(Contract.ForAll(0, xs.Length, delegate(int i) { return xs[i] < Contract.OldValue(xs[i]); }));
if (shouldBeCorrect)
for (int i = 0; i < xs.Length; i++) xs[i] = xs[i] - 1;
return;
}
public virtual int InheritResult(int x, bool shouldBeCorrect)
{
Contract.Ensures(Contract.Result<int>() == x);
return shouldBeCorrect ? x : x + 1;
}
public virtual int InheritResultInQuantifier(int[] xs, bool shouldBeCorrect)
{
Contract.Requires(0 < xs.Length);
Contract.Ensures(Contract.ForAll(0, xs.Length, delegate(int i) { return xs[i] < Contract.Result<int>(); }));
for (int i = 0; i < xs.Length; i++)
xs[i] = 3;
return shouldBeCorrect ? 27 : 3;
}
}
public class DerivedFromBaseClassWithOldAndResult : BaseClassWithOldAndResult {
public override void InheritOld(ref int y, bool shouldBeCorrect)
{
if (shouldBeCorrect) y = y * 2;
return;
}
public override void InheritOldInQuantifier(int[] ys, bool shouldBeCorrect)
{
if (shouldBeCorrect)
for (int i = 0; i < ys.Length; i++) ys[i] = ys[i] - 3;
return;
}
public override int InheritResult(int x, bool shouldBeCorrect)
{
return shouldBeCorrect ? x : x + 1;
}
public override int InheritResultInQuantifier(int[] ys, bool shouldBeCorrect)
{
for (int i = 0; i < ys.Length; i++)
ys[i] = 0;
return shouldBeCorrect ? 27 : 0;
}
}
public class NonGenericBaseWithInvariant {
protected bool succeed = true;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(succeed);
}
}
public class GenericWithInheritedInvariant<T> : NonGenericBaseWithInvariant {
}
public class NonGenericDerivedFromGenericWithInvariant : GenericWithInheritedInvariant<string> {
public NonGenericDerivedFromGenericWithInvariant(bool succeed)
{
this.succeed = succeed;
}
}
public class ExplicitGenericInterfaceMethodImplementation : IInterfaceWithGenericMethod {
int mode;
public ExplicitGenericInterfaceMethodImplementation(int mode)
{
this.mode = mode;
}
IEnumerable<T> IInterfaceWithGenericMethod.Bar<T>()
{
switch (mode)
{
case 0:
return new T[0];
case 1:
return new T[1];
default:
return null;
}
}
}
public class ImplicitGenericInterfaceMethodImplementation : IInterfaceWithGenericMethod {
int mode;
public ImplicitGenericInterfaceMethodImplementation(int mode)
{
this.mode = mode;
}
public IEnumerable<T> Bar<T>()
{
switch (mode)
{
case 0:
return new T[0];
case 1:
return new T[1];
default:
return null;
}
}
}
[ContractClass(typeof(InterfaceWithGenericMethodContract))]
public interface IInterfaceWithGenericMethod {
IEnumerable<T> Bar<T>();
}
[ContractClassFor(typeof(IInterfaceWithGenericMethod))]
abstract class InterfaceWithGenericMethodContract : IInterfaceWithGenericMethod {
IEnumerable<T> IInterfaceWithGenericMethod.Bar<T>()
{
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null));
return default(IEnumerable<T>);
}
}
#region Interface with method call in contract
[ContractClass(typeof(ContractForIFaceWithMethodCallInContract))]
public interface IFaceWithMethodCallInContract {
bool M(int x);
bool P { get; }
}
[ContractClassFor(typeof(IFaceWithMethodCallInContract))]
abstract class ContractForIFaceWithMethodCallInContract : IFaceWithMethodCallInContract {
bool IFaceWithMethodCallInContract.M(int x)
{
IFaceWithMethodCallInContract iFaceReference = this;
Contract.Requires(x != 3);
Contract.Requires(iFaceReference.P);
Contract.Ensures(x != 5 || !iFaceReference.P);
return default(bool);
}
bool IFaceWithMethodCallInContract.P
{
get
{
Contract.Ensures(Contract.Result<bool>());
return default(bool);
}
}
}
public class ImplForIFaceWithMethodCallInContract : IFaceWithMethodCallInContract {
public virtual bool M(int x)
{
return true;
}
public virtual bool P
{
get { return true; }
}
}
#endregion Interface with method call in contract
#region ContractClass for abstract methods
[ContractClass(typeof(AbstractClassContracts))]
public abstract class AbstractClass {
public abstract int ReturnFirst(int[] args, bool behave);
public virtual int Increment(int x, bool behave)
{
Contract.Requires(0 < x);
Contract.Ensures(Contract.Result<int>() >= x + 1);
return x + 1;
}
}
[ContractClassFor(typeof(AbstractClass))]
internal abstract class AbstractClassContracts : AbstractClass {
public override int ReturnFirst(int[] args, bool behave)
{
Contract.Requires(args != null);
Contract.Requires(args.Length > 0);
Contract.Ensures(Contract.Result<int>() == args[0]);
return default(int);
}
}
[ContractClass(typeof(GenericAbstractClassContracts<,>))]
public abstract class GenericAbstractClass<A, B> where A : class,B {
[Pure]
public abstract bool IsMatch(B b, A a);
public abstract B ReturnFirst(B[] args, A match, bool behave);
public abstract A[][] Collection(int x, int y);
public abstract A FirstNonNullMatch(A[] elems);
public abstract C[] GenericMethod<C>(A[] elems);
}
[ContractClassFor(typeof(GenericAbstractClass<,>))]
internal abstract class GenericAbstractClassContracts<A, B> : GenericAbstractClass<A, B>
where A : class, B {
public override bool IsMatch(B b, A a)
{
throw new NotImplementedException();
}
public override B ReturnFirst(B[] args, A match, bool behave)
{
Contract.Requires(args != null);
Contract.Requires(args.Length > 0);
Contract.Ensures(Contract.Exists(0, args.Length, i => args[i].Equals(Contract.Result<B>()) && IsMatch(args[i], match)));
return default(B);
}
public override A[][] Collection(int x, int y)
{
Contract.Ensures(Contract.ForAll(Contract.Result<A[][]>(), nested => nested != null && nested.Length == y && Contract.ForAll(nested, elem => elem != null)));
Contract.Ensures(Contract.ForAll(0, x, index => Contract.Result<A[][]>()[index] != null));
throw new NotImplementedException();
}
public override A FirstNonNullMatch(A[] elems)
{
// meaningless, but testing our closures, in particular inner one with a static closure referring to result.
Contract.Ensures(Contract.Exists(0, elems.Length, index => elems[index] != null && elems[index] == Contract.Result<A>() &&
Contract.ForAll(0, index, prior => Contract.Result<A>() != null)));
// See if we are properly sharing fields.
Contract.Ensures(Contract.Exists(0, elems.Length, index => elems[index] != null && elems[index] == Contract.Result<A>() &&
Contract.ForAll(0, index, prior => Contract.Result<A>() != null)));
// See if we are properly sharing fields.
Contract.Ensures(Contract.Exists(0, elems.Length, index => elems[index] != null &&
Contract.ForAll(0, index, prior => Contract.Result<A>() != null)));
throw new NotImplementedException();
}
public override C[] GenericMethod<C>(A[] elems)
{
Contract.Requires(elems != null);
Contract.Ensures(Contract.Result<C[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<C[]>(), resultElem => Contract.Exists(elems, orig => resultElem.Equals(orig))));
throw new NotImplementedException();
}
}
public class ImplForAbstractMethod : AbstractClass {
public override int ReturnFirst(int[] args, bool behave)
{
if (behave)
return args[0];
else
return args[0] + 1;
}
public override int Increment(int x, bool behave)
{
Contract.Ensures(Contract.Result<int>() == x + 2);
return behave ? (x + 2) : base.Increment(x, behave);
}
}
public class ImplForGenericAbstractClass : GenericAbstractClass<string, string> {
public override bool IsMatch(string b, string a)
{
return b == a;
}
public override string ReturnFirst(string[] args, string match, bool behave)
{
for (int i = 0; i < args.Length; i++)
{
if (IsMatch(args[i], match)) return args[i];
}
return default(string);
}
public override string[][] Collection(int x, int y)
{
var result = new string[x][];
for (int i = 0; i < result.Length; i++)
{
result[i] = new string[y];
for (int j = 0; j < y; j++)
{
if (x == 5 && y == 5 && i == 4 && j == 4)
{
// behave badly
continue;
}
result[i][j] = "Foo";
}
}
return result;
}
public override string FirstNonNullMatch(string[] elems)
{
for (int i = 0; i < elems.Length; i++)
{
if (elems[i] != null) return elems[i];
}
return null;
}
public override C[] GenericMethod<C>(string[] elems)
{
List<C> result = new List<C>();
foreach (var elem in elems)
{
if (elem is C)
{
result.Add((C)(object)elem);
}
}
if (typeof(C) == typeof(int))
{
// behave badly
result.Add((C)(object)55);
}
return result.ToArray();
}
}
#endregion ContractClass for abstract methods
#region Make sure stelem is properly specialized
public delegate bool D<T>(T t);
public class BaseWithClosureWithStelem<T> {
public bool Foo(D<T> action, T data)
{
action(data);
action(data);
return true;
}
public virtual void M(T[] ts, int i)
{
Contract.Requires(ts != null);
Contract.Requires(i + 1 < ts.Length);
Contract.Ensures(ts[i].Equals(ts[0]));
Contract.Ensures(ts[i + 1].Equals(ts[0]));
int index = i;
Foo(delegate(T t) { ts[index++] = t; return true; }, ts[0]);
}
}
public class DerivedOfClosureWithStelem<V> : BaseWithClosureWithStelem<V> {
public override void M(V[] vs, int j)
{
base.M(vs, j);
}
}
#endregion
#endregion
#region Contracts
public class C {
public int P { get { return _p; } }
[ContractPublicPropertyName("P")]
private int _p;
public virtual int foo(int x)
{
Contract.Requires(x < _p);
return 3;
}
public C()
{
_p = 0;
}
}
public class D : C {
public override int foo(int x)
{
return 27;
}
}
public class UsingVirtualProperty {
public virtual int P { get { return _p; } }
[ContractPublicPropertyName("P")]
private int _p;
public virtual int foo(int x)
{
Contract.Requires(x < _p);
return 3;
}
public UsingVirtualProperty()
{
_p = 0;
}
}
public class SubtypeOfUsingVirtualProperty : UsingVirtualProperty {
public override int P { get { return 100; } }
public override int foo(int x)
{
return 27;
}
}
#endregion Contracts
}
namespace Strilanc
{
public interface B
{
bool P { get; }
}
#region I contract binding
[ContractClass(typeof(CI<>))]
public partial interface I<T> : B
{
void S();
}
[ContractClassFor(typeof(I<>))]
abstract class CI<T> : I<T>
{
#region I Membersbu
public void S()
{
Contract.Requires(this.P);
}
#endregion
#region B Members
public bool P
{
get { return true; }
}
#endregion
}
#endregion
public class C : I<bool>
{
bool behave;
public C(bool behave)
{
this.behave = behave;
}
public bool P { get { return behave; } }
public void S()
{
Contract.Assert(((B)this).P);
}
}
}
namespace CodeUnderTest.ThomasPani
{
public class T
{
protected int i = 100;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(i >= 0); // i non-negative
}
public void SetToValidValue(bool behave)
{
if (behave)
{
i = 1;
} else
{
i = 0;
}
}
}
public class U : T
{
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(i > 0); // i positive
}
}
}
| |
// 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.Runtime.InteropServices;
using Xunit;
using System.Linq;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str
{
#region Utilities
public override string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName, "*");
}
public virtual string[] GetEntries(string dirName, string searchPattern)
{
return Directory.GetFileSystemEntries(dirName, searchPattern);
}
#endregion
#region UniversalTests
[Fact]
public void SearchPatternNull()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null));
}
[Fact]
public void SearchPatternEmpty()
{
// To avoid OS differences we have decided not to throw an argument exception when empty
// string passed. But we should return 0 items.
Assert.Empty(GetEntries(TestDirectory, string.Empty));
}
[Fact]
public void SearchPatternValid()
{
Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw
}
[Fact]
public void SearchPatternDotIsStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
{
string[] strArr = GetEntries(testDir.FullName, ".");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
}
}
[Fact]
public void SearchPatternWithTrailingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "Test1*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternWithLeadingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "*2");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*Dir*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternByExtension()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, "TestFile1.txt")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2.xxt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2.txt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2.txx")))
{
string[] strArr = GetEntries(testDir.FullName, "*.txt");
Assert.Equal(2, strArr.Length);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1.txt"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2.txt"), strArr);
}
}
}
[Fact]
public void SearchPatternExactMatch()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA"));
using (File.Create(Path.Combine(testDir.FullName, "AAABB")))
using (File.Create(Path.Combine(testDir.FullName, "AAABBC")))
using (File.Create(Path.Combine(testDir.FullName, "CAAABB")))
{
if (TestFiles)
{
string[] results = GetEntries(testDir.FullName, "AAABB");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results);
}
if (TestDirectories)
{
string[] results = GetEntries(testDir.FullName, "AAA");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results);
}
}
}
[Fact]
public void SearchPatternIgnoreSubDirectories()
{
//Shouldn't get files on full path by default
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*"));
if (TestDirectories && TestFiles)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Long path segment in search pattern throws PathTooLongException
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
public void SearchPatternLongPath()
{
// Create a destination path longer than the traditional Windows limit of 256 characters
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 254);
string longFullname = Path.Combine(testDir.FullName, longName);
if (TestFiles)
{
using (File.Create(longFullname)) { }
}
else
{
Directory.CreateDirectory(longFullname);
}
string[] results = GetEntries(testDir.FullName, longName);
Assert.Contains(longFullname, results);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Search pattern with double dots throws ArgumentException
public void WindowsSearchPatternWithDoubleDots()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
}
private static char[] OldWildcards = new char[] { '*', '?' };
private static char[] NewWildcards = new char[] { '<', '>', '\"' };
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
public void WindowsSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "|"));
Assert.All(Path.GetInvalidFileNameChars().Except(OldWildcards).Except(NewWildcards), invalidChar =>
{
switch (invalidChar)
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
//We don't throw in V1 too
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS
{
Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
}
else
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
}
break;
default:
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
}
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netcoreapp()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netfx()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-invalid sarch patterns throw ArgumentException
public void UnixSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString())));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ? in search pattern returns results
public virtual void WindowsSearchPatternQuestionMarks()
{
string testDir1Str = GetTestFileName();
DirectoryInfo testDir = new DirectoryInfo(TestDirectory);
DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str);
using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length)));
if (TestFiles && TestDirectories)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in search pattern returns nothing
public void WindowsSearchPatternWhitespace()
{
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\n"));
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\t"));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void SearchPatternCaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void SearchPatternCaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in file search patterns
public void UnixSearchPatternFileValidChar()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in directory search patterns
public void UnixSearchPatternDirectoryValidChar()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Search pattern with DoubleDots on Unix
public void UnixSearchPatternWithDoubleDots()
{
// search pattern is valid but directory doesn't exist
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
// invalid search pattern trying to go up a directory with ..
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc", "..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "..", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
#pragma warning disable CS0618 // Type or member is obsolete
namespace System.Runtime.InteropServices.Tests
{
public class Int64Tests
{
[Theory]
[InlineData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, long.MaxValue })]
public void WriteInt64_Pointer_Roundtrips(long[] values)
{
int sizeOfArray = Marshal.SizeOf(values[0]) * values.Length;
IntPtr ptr = Marshal.AllocCoTaskMem(sizeOfArray);
try
{
Marshal.WriteInt64(ptr, values[0]);
for (int i = 1; i < values.Length; i++)
{
Marshal.WriteInt64(ptr, i * Marshal.SizeOf(values[0]), values[i]);
}
long value = Marshal.ReadInt64(ptr);
Assert.Equal(values[0], value);
for (int i = 1; i < values.Length; i++)
{
value = Marshal.ReadInt64(ptr, i * Marshal.SizeOf(values[0]));
Assert.Equal(values[i], value);
}
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
[Fact]
public void WriteInt64_BlittableObject_Roundtrips()
{
int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32();
int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32();
object structure = new BlittableStruct
{
value1 = 10,
value2 = 20
};
Marshal.WriteInt64(structure, offset1, 11);
Marshal.WriteInt64(structure, offset2, 21);
Assert.Equal(11, ((BlittableStruct)structure).value1);
Assert.Equal(21, ((BlittableStruct)structure).value2);
Assert.Equal(11, Marshal.ReadInt64(structure, offset1));
Assert.Equal(21, Marshal.ReadInt64(structure, offset2));
}
[Fact]
public void WriteInt64_StructWithReferenceTypes_ReturnsExpected()
{
int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32();
int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32();
int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32();
object structure = new StructWithReferenceTypes
{
pointerValue = (IntPtr)100,
stringValue = "ABC",
byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
};
if (IntPtr.Size == 8)
{
Marshal.WriteInt64(structure, pointerOffset, 200);
}
Marshal.WriteInt64(structure, arrayOffset + sizeof(long) * 9, 100);
if (IntPtr.Size == 8)
{
Assert.Equal((IntPtr)200, ((StructWithReferenceTypes)structure).pointerValue);
}
Assert.Equal("ABC", ((StructWithReferenceTypes)structure).stringValue);
Assert.Equal(new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100 }, ((StructWithReferenceTypes)structure).byValueArray);
if (IntPtr.Size == 8)
{
Assert.Equal(200, Marshal.ReadInt64(structure, pointerOffset));
}
Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset));
Assert.Equal(100, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 9));
}
[Fact]
public void ReadInt64_BlittableObject_ReturnsExpected()
{
int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32();
int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32();
object structure = new BlittableStruct
{
value1 = 10,
value2 = 20
};
Assert.Equal(10, Marshal.ReadInt64(structure, offset1));
Assert.Equal(20, Marshal.ReadInt64(structure, offset2));
}
[Fact]
public void ReadInt64_StructWithReferenceTypes_ReturnsExpected()
{
int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32();
int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32();
int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32();
object structure = new StructWithReferenceTypes
{
pointerValue = (IntPtr)100,
stringValue = "ABC",
byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
};
if (IntPtr.Size == 8)
{
Assert.Equal(100, Marshal.ReadInt64(structure, pointerOffset));
}
Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset));
Assert.Equal(3, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 2));
}
[Fact]
public void ReadInt64_ZeroPointer_ThrowsException()
{
AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero));
AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero, 2));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Exception is wrapped in a TargetInvocationException in the .NET Framework.")]
public void ReadInt64_NullObject_ThrowsAccessViolationException()
{
Assert.Throws<AccessViolationException>(() => Marshal.ReadInt64(null, 2));
}
#if !netstandard // TODO: Enable for netstandard2.1
[Fact]
public void ReadInt64_NotReadable_ThrowsArgumentException()
{
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
TypeBuilder typeBuilder = moduleBuilder.DefineType("Type");
Type collectibleType = typeBuilder.CreateType();
object collectibleObject = Activator.CreateInstance(collectibleType);
AssertExtensions.Throws<ArgumentException>(null, () => Marshal.ReadInt64(collectibleObject, 0));
}
#endif
[Fact]
public void WriteInt64_ZeroPointer_ThrowsException()
{
AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 0));
AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 2, 0));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Exception is wrapped in a TargetInvocationException in the .NET Framework.")]
public void WriteInt64_NullObject_ThrowsAccessViolationException()
{
Assert.Throws<AccessViolationException>(() => Marshal.WriteInt64(null, 2, 0));
}
#if !netstandard // TODO: Enable for netstandard2.1
[Fact]
public void WriteInt64_NotReadable_ThrowsArgumentException()
{
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
TypeBuilder typeBuilder = moduleBuilder.DefineType("Type");
Type collectibleType = typeBuilder.CreateType();
object collectibleObject = Activator.CreateInstance(collectibleType);
AssertExtensions.Throws<ArgumentException>(null, () => Marshal.WriteInt64(collectibleObject, 0, 0));
}
#endif
public struct BlittableStruct
{
public long value1;
public int padding;
public long value2;
}
public struct StructWithReferenceTypes
{
public IntPtr pointerValue;
public string stringValue;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public long[] byValueArray;
}
}
}
#pragma warning restore CS0618 // Type or member is obsolete
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Linq;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
public static class TranslateListWithElements
{
private static Dictionary<Type, ConvertInstanceDelegate> TranslateICollectionCache
= new Dictionary<Type, ConvertInstanceDelegate>();
public static object TranslateToGenericICollectionCache(object from, Type toInstanceOfType, Type elementType)
{
if (TranslateICollectionCache.TryGetValue(toInstanceOfType, out var translateToFn))
return translateToFn(from, toInstanceOfType);
var genericType = typeof(TranslateListWithElements<>).MakeGenericType(elementType);
var mi = genericType.GetStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<Type, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateICollectionCache;
newCache = new Dictionary<Type, ConvertInstanceDelegate>(TranslateICollectionCache) {
[elementType] = translateToFn
};
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
private static Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> TranslateConvertibleICollectionCache
= new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>();
public static object TranslateToConvertibleGenericICollectionCache(
object from, Type toInstanceOfType, Type fromElementType)
{
var typeKey = new ConvertibleTypeKey(toInstanceOfType, fromElementType);
if (TranslateConvertibleICollectionCache.TryGetValue(typeKey, out var translateToFn)) return translateToFn(from, toInstanceOfType);
var toElementType = toInstanceOfType.FirstGenericType().GetGenericArguments()[0];
var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType);
var mi = genericType.GetStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateConvertibleICollectionCache;
newCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(TranslateConvertibleICollectionCache) {
[typeKey] = translateToFn
};
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateConvertibleICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
public static object TryTranslateCollections(Type fromPropertyType, Type toPropertyType, object fromValue)
{
var args = typeof(IEnumerable<>).GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (args != null)
{
return TranslateToGenericICollectionCache(
fromValue, toPropertyType, args[0]);
}
var varArgs = typeof(IEnumerable<>).GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (varArgs != null)
{
return TranslateToConvertibleGenericICollectionCache(
fromValue, toPropertyType, varArgs.Args1[0]);
}
var fromElType = fromPropertyType.GetCollectionType();
var toElType = toPropertyType.GetCollectionType();
if (fromElType == null || toElType == null)
return null;
return TranslateToGenericICollectionCache(fromValue, toPropertyType, toElType);
}
}
public class ConvertibleTypeKey
{
public Type ToInstanceType { get; set; }
public Type FromElementType { get; set; }
public ConvertibleTypeKey()
{
}
public ConvertibleTypeKey(Type toInstanceType, Type fromElementType)
{
ToInstanceType = toInstanceType;
FromElementType = fromElementType;
}
public bool Equals(ConvertibleTypeKey other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.ToInstanceType == ToInstanceType && other.FromElementType == FromElementType;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ConvertibleTypeKey)) return false;
return Equals((ConvertibleTypeKey)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((ToInstanceType != null ? ToInstanceType.GetHashCode() : 0) * 397)
^ (FromElementType != null ? FromElementType.GetHashCode() : 0);
}
}
}
public class TranslateListWithElements<T>
{
public static object CreateInstance(Type toInstanceOfType)
{
if (toInstanceOfType.IsGenericType)
{
if (toInstanceOfType.HasAnyTypeDefinitionsOf(
typeof(ICollection<>), typeof(IList<>)))
{
return typeof(List<T>).CreateInstance();
}
}
return toInstanceOfType.CreateInstance();
}
public static IList TranslateToIList(IList fromList, Type toInstanceOfType)
{
var to = (IList)toInstanceOfType.CreateInstance();
foreach (var item in fromList)
{
to.Add(item);
}
return to;
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
if (fromList == null)
return null; //AOT
if (toInstanceOfType.IsArray)
{
var result = TranslateToGenericICollection(
(IEnumerable)fromList, typeof(List<T>));
return result.ToArray();
}
return TranslateToGenericICollection(
(IEnumerable)fromList, toInstanceOfType);
}
public static ICollection<T> TranslateToGenericICollection(
IEnumerable fromList, Type toInstanceOfType)
{
var to = (ICollection<T>)CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
if (item is IEnumerable<KeyValuePair<string, object>> dictionary)
{
var convertedItem = dictionary.FromObjectDictionary<T>();
to.Add(convertedItem);
}
else
{
to.Add((T)item);
}
}
return to;
}
}
public class TranslateListWithConvertibleElements<TFrom, TTo>
{
private static readonly Func<TFrom, TTo> ConvertFn;
static TranslateListWithConvertibleElements()
{
ConvertFn = GetConvertFn();
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
return TranslateToGenericICollection(
(ICollection<TFrom>)fromList, toInstanceOfType);
}
public static ICollection<TTo> TranslateToGenericICollection(
ICollection<TFrom> fromList, Type toInstanceOfType)
{
if (fromList == null) return null; //AOT
var to = (ICollection<TTo>)TranslateListWithElements<TTo>.CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
var toItem = ConvertFn(item);
to.Add(toItem);
}
return to;
}
private static Func<TFrom, TTo> GetConvertFn()
{
if (typeof(TTo) == typeof(string))
{
return x => (TTo)(object)TypeSerializer.SerializeToString(x);
}
if (typeof(TFrom) == typeof(string))
{
return x => TypeSerializer.DeserializeFromString<TTo>((string)(object)x);
}
return x => TypeSerializer.DeserializeFromString<TTo>(TypeSerializer.SerializeToString(x));
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Option;
using Futures = QuantConnect.Securities.Futures;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times.
/// </summary>
public class FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _invested;
private int _liquidated;
private int _delistingsReceived;
private Symbol _esFuture;
private Symbol _esFutureOption;
private readonly DateTime _expectedExpiryWarningTime = new DateTime(2020, 6, 19);
private readonly DateTime _expectedExpiryDelistingTime = new DateTime(2020, 6, 20);
private readonly DateTime _expectedLiquidationTime = new DateTime(2020, 6, 19, 16, 0, 0);
public override void Initialize()
{
SetStartDate(2020, 1, 5);
SetEndDate(2020, 12, 1);
SetCash(100000);
var es = QuantConnect.Symbol.CreateFuture(
Futures.Indices.SP500EMini,
Market.CME,
new DateTime(2020, 6, 19));
var esOption = QuantConnect.Symbol.CreateOption(
es,
Market.CME,
OptionStyle.American,
OptionRight.Put,
3400m,
new DateTime(2020, 6, 19));
_esFuture = AddFutureContract(es, Resolution.Minute).Symbol;
_esFutureOption = AddFutureOptionContract(esOption, Resolution.Minute).Symbol;
}
public override void OnData(Slice data)
{
foreach (var delisting in data.Delistings.Values)
{
// Two warnings and two delisted events should be received for a grand total of 4 events.
_delistingsReceived++;
if (delisting.Type == DelistingType.Warning &&
delisting.Time != _expectedExpiryWarningTime)
{
throw new Exception($"Expiry warning with time {delisting.Time} but is expected to be {_expectedExpiryWarningTime}");
}
if (delisting.Type == DelistingType.Warning && delisting.Time != Time.Date)
{
throw new Exception($"Delisting warning received at an unexpected date: {Time} - expected {delisting.Time}");
}
if (delisting.Type == DelistingType.Delisted &&
delisting.Time != _expectedExpiryDelistingTime)
{
throw new Exception($"Delisting occurred at unexpected time: {delisting.Time} - expected: {_expectedExpiryDelistingTime}");
}
if (delisting.Type == DelistingType.Delisted &&
delisting.Time != Time.Date)
{
throw new Exception($"Delisting notice received at an unexpected date: {Time} - expected {delisting.Time}");
}
}
if (!_invested &&
(data.Bars.ContainsKey(_esFuture) || data.QuoteBars.ContainsKey(_esFuture)) &&
(data.Bars.ContainsKey(_esFutureOption) || data.QuoteBars.ContainsKey(_esFutureOption)))
{
_invested = true;
MarketOrder(_esFuture, 1);
var optionContract = Securities[_esFutureOption];
var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel;
if (marginModel.InitialIntradayMarginRequirement == 0
|| marginModel.InitialOvernightMarginRequirement == 0
|| marginModel.MaintenanceIntradayMarginRequirement == 0
|| marginModel.MaintenanceOvernightMarginRequirement == 0)
{
throw new Exception("Unexpected margin requirements");
}
if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0)
{
throw new Exception("Unexpected Initial Margin requirement");
}
if (marginModel.GetMaintenanceMargin(optionContract) != 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
MarketOrder(_esFutureOption, 1);
if (marginModel.GetMaintenanceMargin(optionContract) == 0)
{
throw new Exception("Unexpected Maintenance Margin requirement");
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Direction != OrderDirection.Sell || orderEvent.Status != OrderStatus.Filled)
{
return;
}
// * Future Liquidation
// * Future Option Exercise
// * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven
_liquidated++;
if (orderEvent.Symbol.SecurityType == SecurityType.FutureOption && _expectedLiquidationTime != Time)
{
throw new Exception($"Expected to liquidate option {orderEvent.Symbol} at {_expectedLiquidationTime}, instead liquidated at {Time}");
}
if (orderEvent.Symbol.SecurityType == SecurityType.Future && _expectedLiquidationTime.AddMinutes(-1) != Time && _expectedLiquidationTime != Time)
{
throw new Exception($"Expected to liquidate future {orderEvent.Symbol} at {_expectedLiquidationTime} (+1 minute), instead liquidated at {Time}");
}
}
public override void OnEndOfAlgorithm()
{
if (!_invested)
{
throw new Exception("Never invested in ES futures and FOPs");
}
if (_delistingsReceived != 4)
{
throw new Exception($"Expected 4 delisting events received, found: {_delistingsReceived}");
}
if (_liquidated != 2)
{
throw new Exception($"Expected 3 liquidation events, found {_liquidated}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "10.15%"},
{"Average Loss", "-11.34%"},
{"Compounding Annual Return", "-2.578%"},
{"Drawdown", "2.300%"},
{"Expectancy", "-0.053"},
{"Net Profit", "-2.345%"},
{"Sharpe Ratio", "-0.969"},
{"Probabilistic Sharpe Ratio", "0.004%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.89"},
{"Alpha", "-0.018"},
{"Beta", "0.001"},
{"Annual Standard Deviation", "0.018"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.696"},
{"Tracking Error", "0.33"},
{"Treynor Ratio", "-16.321"},
{"Total Fees", "$7.40"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "0.005"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.181"},
{"Return Over Maximum Drawdown", "-1.1"},
{"Portfolio Turnover", "0.013"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "0128b145984582f5eba7e95881d9b62d"}
};
}
}
| |
using GridProxyGUI;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Gtk;
using OpenMetaverse.Packets;
using Logger = OpenMetaverse.Logger;
using System.Timers;
using System.Text.RegularExpressions;
public partial class MainWindow : Gtk.Window
{
ProxyManager proxy = null;
MessageScroller messages;
PluginsScroller plugins;
// stats tracking
int PacketCounter;
int CapsInCounter;
int CapsInBytes;
int CapsOutCounter;
int CapsOutBytes;
int PacketsInCounter;
int PacketsInBytes;
int PacketsOutCounter;
int PacketsOutBytes;
Timer StatsTimer;
public MainWindow()
: base(Gtk.WindowType.Toplevel)
{
Build();
LoadSavedSettings();
ProxyLogger.Init();
ProxyLogger.OnLogLine += new ProxyLogger.Log(Logger_OnLogLine);
tabsMain.Page = 0;
string font;
if (PlatformDetection.IsMac)
{
txtSummary.ModifyFont(Pango.FontDescription.FromString("monospace bold"));
font = "monospace";
IgeMacIntegration.IgeMacMenu.GlobalKeyHandlerEnabled = true;
IgeMacIntegration.IgeMacMenu.MenuBar = menuMain;
MenuItem quit = new MenuItem("Quit");
quit.Activated += (object sender, EventArgs e) => OnExitActionActivated(sender, e);
IgeMacIntegration.IgeMacMenu.QuitMenuItem = quit;
menuMain.Hide();
menuSeparator.Hide();
}
else
{
txtSummary.ModifyFont(Pango.FontDescription.FromString("monospace bold 9"));
font = "monospace 9";
}
btnLoadPlugin.Sensitive = false;
txtPort.TextInserted += (object o, TextInsertedArgs args) =>
{
if (args.Length != 1) return;
if (!char.IsDigit(args.Text[0]))
{
txtPort.DeleteText(args.Position - 1, args.Position);
}
};
InitProxyFilters();
txtRequest.ModifyFont(Pango.FontDescription.FromString(font));
CreateTags(txtRequest.Buffer);
txtRequestRaw.ModifyFont(Pango.FontDescription.FromString(font));
txtRequestNotation.ModifyFont(Pango.FontDescription.FromString(font));
txtResponse.ModifyFont(Pango.FontDescription.FromString(font));
CreateTags(txtResponse.Buffer);
txtResponseRaw.ModifyFont(Pango.FontDescription.FromString(font));
txtResponseNotation.ModifyFont(Pango.FontDescription.FromString(font));
sessionLogScroller.Add(messages = new MessageScroller(this));
scrolledwindowPlugin.Add(plugins = new PluginsScroller());
messages.CursorChanged += messages_CursorChanged;
StatsTimer = new Timer(1000.0);
StatsTimer.Elapsed += StatsTimer_Elapsed;
StatsTimer.Enabled = true;
ProxyManager.OnLoginResponse += ProxyManager_OnLoginResponse;
ProxyManager.OnPacketLog += ProxyManager_OnPacketLog;
ProxyManager.OnCapabilityAdded += new ProxyManager.CapsAddedHandler(ProxyManager_OnCapabilityAdded);
ProxyManager.OnEventMessageLog += new ProxyManager.EventQueueMessageHandler(ProxyManager_OnEventMessageLog);
ProxyManager.OnMessageLog += new ProxyManager.MessageLogHandler(ProxyManager_OnMessageLog);
}
void StatsTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Application.Invoke((xsender, xe) =>
{
lblUDPIn.Text = string.Format("Packets In {0} ({1} bytes)", PacketsInCounter, PacketsInBytes);
lblUDPOut.Text = string.Format("Packets Out {0} ({1} bytes)", PacketsOutCounter, PacketsOutBytes);
lblUDPTotal.Text = string.Format("Packets Total {0} ({1} bytes)", PacketsInCounter + PacketsOutCounter, PacketsInBytes + PacketsOutBytes);
lblCapIn.Text = string.Format("Caps In {0} ({1} bytes)", CapsInCounter, CapsInBytes);
lblCapOut.Text = string.Format("Caps Out {0} ({1} bytes)", CapsOutCounter, CapsOutBytes);
lblCapTotal.Text = string.Format("Caps Total {0} ({1} bytes)", CapsInCounter + CapsOutCounter, CapsInBytes + CapsOutBytes);
});
}
void ProxyManager_OnLoginResponse(object request, GridProxy.Direction direction)
{
Application.Invoke((xsender, xe) =>
{
string loginType;
if (request is Nwc.XmlRpc.XmlRpcRequest)
{
loginType = "Login Request";
}
else
{
loginType = "Login Response";
}
if (UDPFilterItems.ContainsKey(loginType) && UDPFilterItems[loginType].Enabled)
{
PacketCounter++;
SessionLogin sessionLogin = new SessionLogin(request, direction, cbLoginURL.ActiveText, request.GetType().Name + " " + loginType);
sessionLogin.Columns = new string[] { PacketCounter.ToString(), sessionLogin.TimeStamp.ToString("HH:mm:ss.fff"),
sessionLogin.Protocol, sessionLogin.Name, sessionLogin.Length.ToString(), sessionLogin.Host, sessionLogin.ContentType };
messages.AddSession(sessionLogin);
}
});
}
void ProxyManager_OnPacketLog(Packet packet, GridProxy.Direction direction, System.Net.IPEndPoint endpoint)
{
Application.Invoke((xsender, xe) =>
{
PacketCounter++;
if (direction == GridProxy.Direction.Incoming)
{
PacketsInCounter++;
PacketsInBytes += packet.Length;
}
else
{
PacketsOutCounter++;
PacketsOutBytes += packet.Length;
}
SessionPacket sessionPacket = new SessionPacket(packet, direction, endpoint,
PacketDecoder.InterpretOptions(packet.Header) + " Seq: " + packet.Header.Sequence.ToString() + " Freq:" + packet.Header.Frequency.ToString());
sessionPacket.Columns = new string[] { PacketCounter.ToString(), sessionPacket.TimeStamp.ToString("HH:mm:ss.fff"), sessionPacket.Protocol, sessionPacket.Name, sessionPacket.Length.ToString(), sessionPacket.Host, sessionPacket.ContentType };
messages.AddSession(sessionPacket);
});
}
void ProxyManager_OnCapabilityAdded(GridProxy.CapInfo cap)
{
Application.Invoke((sender, e) =>
{
if (!CapFilterItems.ContainsKey(cap.CapType))
{
FilterItem item = new FilterItem() { Name = cap.CapType, Type = ItemType.Cap };
item.FilterItemChanged += item_FilterItemChanged;
item.Enabled = true;
CapFilterItems[item.Name] = item;
capStore.AppendValues(item);
}
});
}
void ProxyManager_OnEventMessageLog(GridProxy.CapsRequest req, GridProxy.CapsStage stage)
{
Application.Invoke((sender, e) =>
{
if (!CapFilterItems.ContainsKey(req.Info.CapType))
{
FilterItem item = new FilterItem() { Enabled = true, Name = req.Info.CapType, Type = ItemType.EQ };
item.FilterItemChanged += item_FilterItemChanged;
CapFilterItems[item.Name] = item;
capStore.AppendValues(item);
}
ProxyManager_OnMessageLog(req, GridProxy.CapsStage.Response);
});
}
void ProxyManager_OnMessageLog(GridProxy.CapsRequest req, GridProxy.CapsStage stage)
{
Application.Invoke((sender, e) =>
{
if (CapFilterItems.ContainsKey(req.Info.CapType))
{
var filter = CapFilterItems[req.Info.CapType];
if (!filter.Enabled) return;
PacketCounter++;
int size = 0;
if (req.RawRequest != null)
{
size += req.RawRequest.Length;
}
if (req.RawResponse != null)
{
size += req.RawResponse.Length;
}
GridProxy.Direction direction;
if (stage == GridProxy.CapsStage.Request)
{
CapsOutCounter++;
CapsOutBytes += req.Request.ToString().Length;
direction = GridProxy.Direction.Outgoing;
}
else
{
CapsInCounter++;
CapsInBytes += req.Response.ToString().Length;
direction = GridProxy.Direction.Incoming;
}
string proto = filter.Type.ToString();
Session capsSession = null;
if (filter.Type == ItemType.Cap)
{
capsSession = new SessionCaps(req.RawRequest, req.RawResponse, req.RequestHeaders,
req.ResponseHeaders, direction, req.Info.URI, req.Info.CapType, proto, req.FullUri);
}
else
{
capsSession = new SessionEvent(req.RawResponse, req.ResponseHeaders, req.Info.URI, req.Info.CapType, proto);
}
capsSession.Columns = new string[] { PacketCounter.ToString(), capsSession.TimeStamp.ToString("HH:mm:ss.fff"), capsSession.Protocol, capsSession.Name, capsSession.Length.ToString(), capsSession.Host, capsSession.ContentType };
messages.AddSession(capsSession);
}
});
}
void Logger_OnLogLine(object sender, LogEventArgs e)
{
Gtk.Application.Invoke((sx, ex) =>
{
AppendLog(e.Message);
});
}
void AppendLog(string msg)
{
var end = txtSummary.Buffer.EndIter;
txtSummary.Buffer.Insert(ref end, msg);
}
protected void StartPoxy()
{
AppendLog("Starting proxy..." + Environment.NewLine);
try
{
proxy = new ProxyManager(txtPort.Text, cbListen.ActiveText, cbLoginURL.ActiveText);
proxy.Start();
btnLoadPlugin.Sensitive = true;
ApplyProxyFilters();
}
catch (Exception ex)
{
Logger.Log("Failed to start proxy: " + ex.Message, OpenMetaverse.Helpers.LogLevel.Error);
try
{
proxy.Stop();
}
catch { }
btnStart.Label = "Start Proxy";
proxy = null;
}
}
protected void StopProxy()
{
AppendLog("Proxy stopped" + Environment.NewLine);
if (proxy != null) proxy.Stop();
proxy = null;
plugins.Store.Clear();
btnLoadPlugin.Sensitive = false;
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
StopProxy();
SaveSettings();
a.RetVal = true;
}
protected void OnExitActionActivated(object sender, EventArgs e)
{
StopProxy();
SaveSettings();
}
protected void OnBtnStartClicked(object sender, EventArgs e)
{
if (btnStart.Label.StartsWith("Start"))
{
btnStart.Label = "Stop Proxy";
StartPoxy();
}
else if (btnStart.Label.StartsWith("Stop"))
{
btnStart.Label = "Start Proxy";
StopProxy();
}
}
void SetAllToggles(bool on, ListStore store)
{
if (null == store) return;
store.Foreach((model, path, iter) =>
{
var item = model.GetValue(iter, 0) as FilterItem;
if (null != item)
{
item.Enabled = on;
model.SetValue(iter, 0, item);
}
return false;
});
}
protected void OnCbSelectAllUDPToggled(object sender, EventArgs e)
{
SetAllToggles(cbSelectAllUDP.Active, udpStore);
}
protected void OnCbSelectAllCapToggled(object sender, EventArgs e)
{
SetAllToggles(cbSelectAllCap.Active, capStore);
}
protected void OnCbAutoScrollToggled(object sender, EventArgs e)
{
messages.AutoScroll = cbAutoScroll.Active;
}
void messages_CursorChanged(object sender, EventArgs e)
{
var tv = (TreeView)sender;
var paths = tv.Selection.GetSelectedRows();
TreeIter iter;
if (paths.Length == 1 && tv.Model.GetIter(out iter, paths[0]))
{
var item = tv.Model.GetValue(iter, 0) as Session;
if (item != null)
{
ColorizePacket(txtRequest.Buffer, item.ToPrettyString(GridProxy.Direction.Outgoing));
txtRequestRaw.Buffer.Text = item.ToRawString(GridProxy.Direction.Outgoing);
txtRequestNotation.Buffer.Text = item.ToStringNotation(GridProxy.Direction.Outgoing);
ColorizePacket(txtResponse.Buffer, item.ToPrettyString(GridProxy.Direction.Incoming));
txtResponseRaw.Buffer.Text = item.ToRawString(GridProxy.Direction.Incoming);
txtResponseNotation.Buffer.Text = item.ToStringNotation(GridProxy.Direction.Incoming);
SetVisibility();
}
}
}
void SetVisibility()
{
tabsMain.Page = 2;
var w1 = vboxInspector.Children.GetValue(0) as Widget;
var w2 = vboxInspector.Children.GetValue(1) as Widget;
if (w1 == null || w2 == null) return;
// check if request is empry
if (txtRequest.Buffer.Text.Trim().Length < 3 && txtRequestRaw.Buffer.Text.Trim().Length < 3)
{
w1.Hide();
}
else
{
w1.Show();
}
// check if request is empry
if (txtResponse.Buffer.Text.Trim().Length < 3 && txtResponseRaw.Buffer.Text.Trim().Length < 3)
{
w2.Hide();
}
else
{
w2.Show();
}
}
void CreateTags(TextBuffer buffer)
{
TextTag tag = buffer.TagTable.Lookup("bold");
if (tag == null)
{
tag = new TextTag("bold");
tag.Weight = Pango.Weight.Bold;
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("type");
if (tag == null)
{
tag = new TextTag("type");
tag.ForegroundGdk = new Gdk.Color(43, 145, 175);
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("header");
if (tag == null)
{
tag = new TextTag("header");
tag.ForegroundGdk = new Gdk.Color(0, 96, 0);
tag.BackgroundGdk = new Gdk.Color(206, 226, 252);
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("block");
if (tag == null)
{
tag = new TextTag("block");
tag.ForegroundGdk = new Gdk.Color(255, 215, 0);
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("tag");
if (tag == null)
{
tag = new TextTag("tag");
tag.ForegroundGdk = new Gdk.Color(255, 255, 255);
tag.BackgroundGdk = new Gdk.Color(40, 40, 40);
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("counter");
if (tag == null)
{
tag = new TextTag("counter");
tag.ForegroundGdk = new Gdk.Color(0, 64, 0);
buffer.TagTable.Add(tag);
}
tag = buffer.TagTable.Lookup("UUID");
if (tag == null)
{
tag = new TextTag("UUID");
tag.ForegroundGdk = new Gdk.Color(148, 0, 211);
buffer.TagTable.Add(tag);
}
}
void ColorizePacket(TextBuffer buffer, string text)
{
if (!text.StartsWith("Message Type:") && !text.StartsWith("Packet Type:"))
{
buffer.Text = text;
return;
}
buffer.Text = string.Empty;
text = text.Replace("\r", "");
TextIter iter = buffer.StartIter;
Regex typesRegex = new Regex(@"\[(?<Type>\w+|\w+\[\])\]|\((?<Enum>.*)\)|\s-- (?<Header>\w+|\w+ \[\]) --\s|(?<BlockSep>\s\*\*\*\s)|(?<Tag>\s<\w+>\s|\s<\/\w+>\s)|(?<BlockCounter>\s\w+\[\d+\]\s)|(?<UUID>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})", RegexOptions.ExplicitCapture);
MatchCollection matches = typesRegex.Matches(text);
int pos = 0;
if (matches.Count == 0)
{
buffer.Text = text;
}
foreach (Match match in matches)
{
string tag = "bold";
buffer.Insert(ref iter, text.Substring(pos, match.Index - pos));
pos += match.Index - pos;
if (!String.IsNullOrEmpty(match.Groups["Type"].Value))
{
tag = "type";
}
else if (!String.IsNullOrEmpty(match.Groups["Enum"].Value))
{
tag = "type";
}
else if (!String.IsNullOrEmpty(match.Groups["Header"].Value))
{
tag = "header";
}
else if (!String.IsNullOrEmpty(match.Groups["BlockSep"].Value))
{
tag = "block";
}
else if (!String.IsNullOrEmpty(match.Groups["Tag"].Value))
{
tag = "tag";
}
else if (!String.IsNullOrEmpty(match.Groups["BlockCounter"].Value))
{
tag = "counter";
}
else if (!String.IsNullOrEmpty(match.Groups["UUID"].Value))
{
tag = "UUID";
}
buffer.InsertWithTagsByName(ref iter, text.Substring(pos, match.Length), tag);
pos += match.Length;
}
}
List<FileFilter> GetFileFilters()
{
List<FileFilter> filters = new List<FileFilter>();
FileFilter filter = new FileFilter();
filter.Name = "Grid Proxy Compressed (*.gpz)";
filter.AddPattern("*.gpz");
filters.Add(filter);
filter = new FileFilter();
filter.Name = "All Files (*.*)";
filter.AddPattern("*.*");
filters.Add(filter);
return filters;
}
public void RedrawFilters()
{
containerFilterCap.QueueDraw();
containerFilterUDP.QueueDraw();
}
protected void OnOpenActionActivated(object sender, EventArgs e)
{
var od = new Gtk.FileChooserDialog(null, "Open Session", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
foreach (var filter in GetFileFilters()) od.AddFilter(filter);
if (od.Run() == (int)ResponseType.Accept)
{
OpenSession(od.Filename);
}
od.Destroy();
}
protected void OnSaveAsActionActivated(object sender, EventArgs e)
{
var od = new Gtk.FileChooserDialog(null, "Save Session", this, FileChooserAction.Save, "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept);
foreach (var filter in GetFileFilters()) od.AddFilter(filter);
if (od.Run() == (int)ResponseType.Accept)
{
SessionFileName = od.Filename;
if (string.IsNullOrEmpty(System.IO.Path.GetExtension(SessionFileName)))
{
SessionFileName += ".gpz";
}
SaveSession();
}
od.Destroy();
}
protected void OnSaveActionActivated(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(SessionFileName))
{
OnSaveAsActionActivated(sender, e);
}
else
{
SaveSession();
}
}
protected void OnAboutActionActivated(object sender, EventArgs e)
{
var about = new GridProxyGUI.About();
about.SkipTaskbarHint = about.SkipPagerHint = true;
about.Run();
about.Destroy();
}
protected void OnBtnLoadPluginClicked(object sender, EventArgs e)
{
if (proxy == null) return;
plugins.LoadPlugin(proxy.Proxy);
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H03Level11Child (editable child object).<br/>
/// This is a generated base class of <see cref="H03Level11Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H02Level1"/> collection.
/// </remarks>
[Serializable]
public partial class H03Level11Child : BusinessBase<H03Level11Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1 Child Name.</value>
public string Level_1_1_Child_Name
{
get { return GetProperty(Level_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H03Level11Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H03Level11Child"/> object.</returns>
internal static H03Level11Child NewH03Level11Child()
{
return DataPortal.CreateChild<H03Level11Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="H03Level11Child"/> object, based on given parameters.
/// </summary>
/// <param name="cParentID1">The CParentID1 parameter of the H03Level11Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="H03Level11Child"/> object.</returns>
internal static H03Level11Child GetH03Level11Child(int cParentID1)
{
return DataPortal.FetchChild<H03Level11Child>(cParentID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H03Level11Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private H03Level11Child()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H03Level11Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H03Level11Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cParentID1">The CParent ID1.</param>
protected void Child_Fetch(int cParentID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH03Level11Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CParentID1", cParentID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cParentID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="H03Level11Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H03Level11Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH03Level11Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H03Level11Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH03Level11Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="H03Level11Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteH03Level11Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
namespace Microsoft.Azure.Management.PowerBIEmbedded
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for WorkspaceCollectionsOperations.
/// </summary>
public static partial class WorkspaceCollectionsOperationsExtensions
{
/// <summary>
/// Retrieves an existing Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
public static WorkspaceCollection GetByName(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).GetByNameAsync(resourceGroupName, workspaceCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves an existing Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkspaceCollection> GetByNameAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByNameWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Power BI Workspace Collection with the specified properties.
/// A Power BI Workspace Collection contains one or more Power BI Workspaces
/// and can be used to provision keys that provide API access to those Power
/// BI Workspaces.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Create workspace collection request
/// </param>
public static WorkspaceCollection Create(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CreateWorkspaceCollectionRequest body)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).CreateAsync(resourceGroupName, workspaceCollectionName, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Power BI Workspace Collection with the specified properties.
/// A Power BI Workspace Collection contains one or more Power BI Workspaces
/// and can be used to provision keys that provide API access to those Power
/// BI Workspaces.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Create workspace collection request
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkspaceCollection> CreateAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CreateWorkspaceCollectionRequest body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing Power BI Workspace Collection with the specified
/// properties.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Update workspace collection request
/// </param>
public static WorkspaceCollection Update(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, UpdateWorkspaceCollectionRequest body)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).UpdateAsync(resourceGroupName, workspaceCollectionName, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing Power BI Workspace Collection with the specified
/// properties.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Update workspace collection request
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkspaceCollection> UpdateAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, UpdateWorkspaceCollectionRequest body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
public static void Delete(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName)
{
Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).DeleteAsync(resourceGroupName, workspaceCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete a Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
public static void BeginDelete(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName)
{
Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).BeginDeleteAsync(resourceGroupName, workspaceCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a Power BI Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Check that the specified Power BI Workspace Collection name is valid and
/// not in use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure location
/// </param>
/// <param name='body'>
/// Check name availability request
/// </param>
public static CheckNameResponse CheckNameAvailability(this IWorkspaceCollectionsOperations operations, string location, CheckNameRequest body)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).CheckNameAvailabilityAsync(location, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Check that the specified Power BI Workspace Collection name is valid and
/// not in use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure location
/// </param>
/// <param name='body'>
/// Check name availability request
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckNameResponse> CheckNameAvailabilityAsync(this IWorkspaceCollectionsOperations operations, string location, CheckNameRequest body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(location, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves all existing Power BI Workspace Collections in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
public static IEnumerable<WorkspaceCollection> ListByResourceGroup(this IWorkspaceCollectionsOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves all existing Power BI Workspace Collections in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<WorkspaceCollection>> ListByResourceGroupAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves all existing Power BI Workspace Collections in the specified
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<WorkspaceCollection> ListBySubscription(this IWorkspaceCollectionsOperations operations)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).ListBySubscriptionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves all existing Power BI Workspace Collections in the specified
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<WorkspaceCollection>> ListBySubscriptionAsync(this IWorkspaceCollectionsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves the primary and secondary access keys for the specified Power BI
/// Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
public static WorkspaceCollectionAccessKeys GetAccessKeys(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).GetAccessKeysAsync(resourceGroupName, workspaceCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves the primary and secondary access keys for the specified Power BI
/// Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkspaceCollectionAccessKeys> GetAccessKeysAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAccessKeysWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the primary or secondary access key for the specified Power BI
/// Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Access key to regenerate
/// </param>
public static WorkspaceCollectionAccessKeys RegenerateKey(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, WorkspaceCollectionAccessKey body)
{
return Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).RegenerateKeyAsync(resourceGroupName, workspaceCollectionName, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the primary or secondary access key for the specified Power BI
/// Workspace Collection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='workspaceCollectionName'>
/// Power BI Embedded workspace collection name
/// </param>
/// <param name='body'>
/// Access key to regenerate
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<WorkspaceCollectionAccessKeys> RegenerateKeyAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, string workspaceCollectionName, WorkspaceCollectionAccessKey body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, workspaceCollectionName, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Migrates an existing Power BI Workspace Collection to a different resource
/// group and/or subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='body'>
/// Workspace migration request
/// </param>
public static void Migrate(this IWorkspaceCollectionsOperations operations, string resourceGroupName, MigrateWorkspaceCollectionRequest body)
{
Task.Factory.StartNew(s => ((IWorkspaceCollectionsOperations)s).MigrateAsync(resourceGroupName, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Migrates an existing Power BI Workspace Collection to a different resource
/// group and/or subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group
/// </param>
/// <param name='body'>
/// Workspace migration request
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task MigrateAsync(this IWorkspaceCollectionsOperations operations, string resourceGroupName, MigrateWorkspaceCollectionRequest body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.MigrateWithHttpMessagesAsync(resourceGroupName, body, null, cancellationToken).ConfigureAwait(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 System;
using System.Globalization;
namespace TVGL.Numerics
{
/// <summary>
/// A structure encapsulating a four-dimensional vector (x,y,z,w),
/// which is used to efficiently rotate an object about the (x,y,z) vector by the angle theta, where w = cos(theta/2).
/// </summary>
public struct Quaternion : IEquatable<Quaternion>
{
private const double SlerpEpsilon = 1e-6;
/// <summary>
/// Specifies the X-value of the vector component of the Quaternion.
/// </summary>
public double X;
/// <summary>
/// Specifies the Y-value of the vector component of the Quaternion.
/// </summary>
public double Y;
/// <summary>
/// Specifies the Z-value of the vector component of the Quaternion.
/// </summary>
public double Z;
/// <summary>
/// Specifies the rotation component of the Quaternion.
/// </summary>
public double W;
/// <summary>
/// Returns a Quaternion representing no rotation.
/// </summary>
public static Quaternion Identity => new Quaternion(0, 0, 0, 1);
/// <summary>
/// Returns a Quaternion representing no rotation.
/// </summary>
public static Quaternion Null => new Quaternion(double.NaN, double.NaN, double.NaN, double.NaN);
/// <summary>
/// Returns whether the Quaternion is the identity Quaternion.
/// </summary>
public bool IsIdentity()
{
return X == 0.0 && Y == 0.0 && Z == 0.0 && W == 1.0;
}
/// <summary>
/// Returns whether the Quaternion is the identity Quaternion.
/// </summary>
public bool IsNull()
{
return double.IsNaN(X) || double.IsNaN(Y) || double.IsNaN(Z) || double.IsNaN(W);
}
/// <summary>
/// Constructs a Quaternion from the given components.
/// </summary>
/// <param name="x">The X component of the Quaternion.</param>
/// <param name="y">The Y component of the Quaternion.</param>
/// <param name="z">The Z component of the Quaternion.</param>
/// <param name="w">The W component of the Quaternion.</param>
public Quaternion(double x, double y, double z, double w)
{
this.X = x;
this.Y = y;
this.Z = z;
this.W = w;
}
/// <summary>
/// Constructs a Quaternion from the given vector and rotation parts.
/// </summary>
/// <param name="vectorPart">The vector part of the Quaternion.</param>
/// <param name="scalarPart">The rotation part of the Quaternion.</param>
public Quaternion(Vector3 vectorPart, double scalarPart)
{
X = vectorPart.X;
Y = vectorPart.Y;
Z = vectorPart.Z;
W = scalarPart;
}
/// <summary>
/// Calculates the length of the Quaternion.
/// </summary>
/// <returns>The computed length of the Quaternion.</returns>
public double Length()
{
return Math.Sqrt(LengthSquared());
}
/// <summary>
/// Calculates the length squared of the Quaternion. This operation is cheaper than Length().
/// </summary>
/// <returns>The length squared of the Quaternion.</returns>
public double LengthSquared()
{
return X * X + Y * Y + Z * Z + W * W;
}
/// <summary>
/// Divides each component of the Quaternion by the length of the Quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The normalized Quaternion.</returns>
public static Quaternion Normalize(Quaternion value)
{
Quaternion ans;
double invNorm = 1.0 / value.Length();
ans.X = value.X * invNorm;
ans.Y = value.Y * invNorm;
ans.Z = value.Z * invNorm;
ans.W = value.W * invNorm;
return ans;
}
/// <summary>
/// Creates the conjugate of a specified Quaternion.
/// </summary>
/// <param name="value">The Quaternion of which to return the conjugate.</param>
/// <returns>A new Quaternion that is the conjugate of the specified one.</returns>
public static Quaternion Conjugate(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = value.W;
return ans;
}
/// <summary>
/// Returns the inverse of a Quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The inverted Quaternion.</returns>
public static Quaternion Inverse(Quaternion value)
{
// -1 ( a -v )
// q = ( ------------- ------------- )
// ( a^2 + |v|^2 , a^2 + |v|^2 )
Quaternion ans;
double ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W;
double invNorm = 1.0 / ls;
ans.X = -value.X * invNorm;
ans.Y = -value.Y * invNorm;
ans.Z = -value.Z * invNorm;
ans.W = value.W * invNorm;
return ans;
}
/// <summary>
/// Creates a Quaternion from a normalized vector axis and an angle to rotate about the vector.
/// </summary>
/// <param name="axis">The unit vector to rotate around.
/// This vector must be normalized before calling this function or the resulting Quaternion will be incorrect.</param>
/// <param name="angle">The angle, in radians, to rotate around the vector.</param>
/// <returns>The created Quaternion.</returns>
public static Quaternion CreateFromAxisAngle(Vector3 axis, double angle)
{
Quaternion ans;
double halfAngle = angle * 0.5;
double s = Math.Sin(halfAngle);
double c = Math.Cos(halfAngle);
ans.X = axis.X * s;
ans.Y = axis.Y * s;
ans.Z = axis.Z * s;
ans.W = c;
return ans;
}
/// <summary>
/// Creates a new Quaternion from the given yaw, pitch, and roll, in radians.
/// </summary>
/// <param name="yaw">The yaw angle, in radians, around the Y-axis.</param>
/// <param name="pitch">The pitch angle, in radians, around the X-axis.</param>
/// <param name="roll">The roll angle, in radians, around the Z-axis.</param>
/// <returns></returns>
public static Quaternion CreateFromYawPitchRoll(double yaw, double pitch, double roll)
{
// Roll first, about axis the object is facing, then
// pitch upward, then yaw to face into the new heading
double halfRoll = roll * 0.5;
var sr = Math.Sin(halfRoll);
var cr = Math.Cos(halfRoll);
double halfPitch = pitch * 0.5;
var sp = Math.Sin(halfPitch);
var cp = Math.Cos(halfPitch);
double halfYaw = yaw * 0.5;
var sy = Math.Sin(halfYaw);
var cy = Math.Cos(halfYaw);
Quaternion result;
result.X = cy * sp * cr + sy * cp * sr;
result.Y = sy * cp * cr - cy * sp * sr;
result.Z = cy * cp * sr - sy * sp * cr;
result.W = cy * cp * cr + sy * sp * sr;
return result;
}
/// <summary>
/// Creates a Quaternion from the given rotation matrix.
/// </summary>
/// <param name="matrix">The rotation matrix.</param>
/// <returns>The created Quaternion.</returns>
public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix)
{
double trace = matrix.M11 + matrix.M22 + matrix.M33;
Quaternion q = default;
if (trace > 0.0)
{
double s = Math.Sqrt(trace + 1.0);
q.W = s * 0.5;
s = 0.5 / s;
q.X = (matrix.M23 - matrix.M32) * s;
q.Y = (matrix.M31 - matrix.M13) * s;
q.Z = (matrix.M12 - matrix.M21) * s;
}
else
{
if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33)
{
double s = Math.Sqrt(1.0 + matrix.M11 - matrix.M22 - matrix.M33);
double invS = 0.5 / s;
q.X = 0.5 * s;
q.Y = (matrix.M12 + matrix.M21) * invS;
q.Z = (matrix.M13 + matrix.M31) * invS;
q.W = (matrix.M23 - matrix.M32) * invS;
}
else if (matrix.M22 > matrix.M33)
{
double s = Math.Sqrt(1.0 + matrix.M22 - matrix.M11 - matrix.M33);
double invS = 0.5 / s;
q.X = (matrix.M21 + matrix.M12) * invS;
q.Y = 0.5 * s;
q.Z = (matrix.M32 + matrix.M23) * invS;
q.W = (matrix.M31 - matrix.M13) * invS;
}
else
{
double s = Math.Sqrt(1.0 + matrix.M33 - matrix.M11 - matrix.M22);
double invS = 0.5 / s;
q.X = (matrix.M31 + matrix.M13) * invS;
q.Y = (matrix.M32 + matrix.M23) * invS;
q.Z = 0.5 * s;
q.W = (matrix.M12 - matrix.M21) * invS;
}
}
return q;
}
/// <summary>
/// Calculates the dot product of two Quaternions.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <returns>The dot product of the Quaternions.</returns>
public static double Dot(Quaternion quaternion1, Quaternion quaternion2)
{
return quaternion1.X * quaternion2.X +
quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z +
quaternion1.W * quaternion2.W;
}
/// <summary>
/// Interpolates between two quaternions, using spherical linear interpolation.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param>
/// <returns>The interpolated Quaternion.</returns>
public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, double amount)
{
double t = amount;
double cosOmega = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
bool flip = false;
if (cosOmega < 0.0)
{
flip = true;
cosOmega = -cosOmega;
}
double s1, s2;
if (cosOmega > (1.0 - SlerpEpsilon))
{
// Too close, do straight linear interpolation.
s1 = 1.0 - t;
s2 = (flip) ? -t : t;
}
else
{
double omega = Math.Acos(cosOmega);
double invSinOmega = 1 / Math.Sin(omega);
s1 = Math.Sin((1.0 - t) * omega) * invSinOmega;
s2 = (flip)
? -Math.Sin(t * omega) * invSinOmega
: Math.Sin(t * omega) * invSinOmega;
}
Quaternion ans;
ans.X = s1 * quaternion1.X + s2 * quaternion2.X;
ans.Y = s1 * quaternion1.Y + s2 * quaternion2.Y;
ans.Z = s1 * quaternion1.Z + s2 * quaternion2.Z;
ans.W = s1 * quaternion1.W + s2 * quaternion2.W;
return ans;
}
/// <summary>
/// Linearly interpolates between two quaternions.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param>
/// <returns>The interpolated Quaternion.</returns>
public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, double amount)
{
double t = amount;
double t1 = 1.0 - t;
Quaternion r = default;
double dot = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
if (dot >= 0.0)
{
r.X = t1 * quaternion1.X + t * quaternion2.X;
r.Y = t1 * quaternion1.Y + t * quaternion2.Y;
r.Z = t1 * quaternion1.Z + t * quaternion2.Z;
r.W = t1 * quaternion1.W + t * quaternion2.W;
}
else
{
r.X = t1 * quaternion1.X - t * quaternion2.X;
r.Y = t1 * quaternion1.Y - t * quaternion2.Y;
r.Z = t1 * quaternion1.Z - t * quaternion2.Z;
r.W = t1 * quaternion1.W - t * quaternion2.W;
}
// Normalize it.
double ls = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
double invNorm = 1.0 / Math.Sqrt(ls);
r.X *= invNorm;
r.Y *= invNorm;
r.Z *= invNorm;
r.W *= invNorm;
return r;
}
/// <summary>
/// Concatenates two Quaternions; the result represents the value1 rotation followed by the value2 rotation.
/// </summary>
/// <param name="quaternion1">The first Quaternion rotation in the series.</param>
/// <param name="quaternion2">The second Quaternion rotation in the series.</param>
/// <returns>A new Quaternion representing the concatenation of the value1 rotation followed by the value2 rotation.</returns>
public static Quaternion Concatenate(Quaternion quaternion1, Quaternion quaternion2)
{
Quaternion ans;
// Concatenate rotation is actually q2 * q1 instead of q1 * q2.
// So that's why value2 goes q1 and value1 goes q2.
double q1x = quaternion2.X;
double q1y = quaternion2.Y;
double q1z = quaternion2.Z;
double q1w = quaternion2.W;
double q2x = quaternion1.X;
double q2y = quaternion1.Y;
double q2z = quaternion1.Z;
double q2w = quaternion1.W;
// cross(av, bv)
double cx = q1y * q2z - q1z * q2y;
double cy = q1z * q2x - q1x * q2z;
double cz = q1x * q2y - q1y * q2x;
double dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Flips the sign of each component of the quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The negated Quaternion.</returns>
public static Quaternion Negate(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = -value.W;
return ans;
}
/// <summary>
/// Adds two Quaternions element-by-element.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second source Quaternion.</param>
/// <returns>The result of adding the Quaternions.</returns>
public static Quaternion Add(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X + value2.X;
ans.Y = value1.Y + value2.Y;
ans.Z = value1.Z + value2.Z;
ans.W = value1.W + value2.W;
return ans;
}
/// <summary>
/// Subtracts one Quaternion from another.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second Quaternion, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static Quaternion Subtract(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X - value2.X;
ans.Y = value1.Y - value2.Y;
ans.Z = value1.Z - value2.Z;
ans.W = value1.W - value2.W;
return ans;
}
/// <summary>
/// Multiplies two Quaternions together.
/// </summary>
/// <param name="value1">The Quaternion on the left side of the multiplication.</param>
/// <param name="value2">The Quaternion on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion Multiply(Quaternion value1, Quaternion value2)
{
Quaternion ans;
double q1x = value1.X;
double q1y = value1.Y;
double q1z = value1.Z;
double q1w = value1.W;
double q2x = value2.X;
double q2y = value2.Y;
double q2z = value2.Z;
double q2w = value2.W;
// cross(av, bv)
double cx = q1y * q2z - q1z * q2y;
double cy = q1z * q2x - q1x * q2z;
double cz = q1x * q2y - q1y * q2x;
double dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Multiplies a Quaternion by a scalar value.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion Multiply(Quaternion value1, double value2)
{
Quaternion ans;
ans.X = value1.X * value2;
ans.Y = value1.Y * value2;
ans.Z = value1.Z * value2;
ans.W = value1.W * value2;
return ans;
}
/// <summary>
/// Divides a Quaternion by another Quaternion.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static Quaternion Divide(Quaternion value1, Quaternion value2)
{
Quaternion ans;
double q1x = value1.X;
double q1y = value1.Y;
double q1z = value1.Z;
double q1w = value1.W;
//-------------------------------------
// Inverse part.
double ls = value2.X * value2.X + value2.Y * value2.Y +
value2.Z * value2.Z + value2.W * value2.W;
double invNorm = 1.0 / ls;
double q2x = -value2.X * invNorm;
double q2y = -value2.Y * invNorm;
double q2z = -value2.Z * invNorm;
double q2w = value2.W * invNorm;
//-------------------------------------
// Multiply part.
// cross(av, bv)
double cx = q1y * q2z - q1z * q2y;
double cy = q1z * q2x - q1x * q2z;
double cz = q1x * q2y - q1y * q2x;
double dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Flips the sign of each component of the quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The negated Quaternion.</returns>
public static Quaternion operator -(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = -value.W;
return ans;
}
/// <summary>
/// Adds two Quaternions element-by-element.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second source Quaternion.</param>
/// <returns>The result of adding the Quaternions.</returns>
public static Quaternion operator +(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X + value2.X;
ans.Y = value1.Y + value2.Y;
ans.Z = value1.Z + value2.Z;
ans.W = value1.W + value2.W;
return ans;
}
/// <summary>
/// Subtracts one Quaternion from another.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second Quaternion, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static Quaternion operator -(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X - value2.X;
ans.Y = value1.Y - value2.Y;
ans.Z = value1.Z - value2.Z;
ans.W = value1.W - value2.W;
return ans;
}
/// <summary>
/// Multiplies two Quaternions together.
/// </summary>
/// <param name="value1">The Quaternion on the left side of the multiplication.</param>
/// <param name="value2">The Quaternion on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion operator *(Quaternion value1, Quaternion value2)
{
Quaternion ans;
double q1x = value1.X;
double q1y = value1.Y;
double q1z = value1.Z;
double q1w = value1.W;
double q2x = value2.X;
double q2y = value2.Y;
double q2z = value2.Z;
double q2w = value2.W;
// cross(av, bv)
double cx = q1y * q2z - q1z * q2y;
double cy = q1z * q2x - q1x * q2z;
double cz = q1x * q2y - q1y * q2x;
double dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Multiplies a Quaternion by a scalar value.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion operator *(Quaternion value1, double value2)
{
Quaternion ans;
ans.X = value1.X * value2;
ans.Y = value1.Y * value2;
ans.Z = value1.Z * value2;
ans.W = value1.W * value2;
return ans;
}
/// <summary>
/// Multiplies a Quaternion by a scalar value.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion operator *(double value1, Quaternion value2)
{ return value2 * value1; }
/// <summary>
/// Divides a Quaternion by another Quaternion.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static Quaternion operator /(Quaternion value1, Quaternion value2)
{
Quaternion ans;
double q1x = value1.X;
double q1y = value1.Y;
double q1z = value1.Z;
double q1w = value1.W;
//-------------------------------------
// Inverse part.
double ls = value2.X * value2.X + value2.Y * value2.Y +
value2.Z * value2.Z + value2.W * value2.W;
double invNorm = 1.0 / ls;
double q2x = -value2.X * invNorm;
double q2y = -value2.Y * invNorm;
double q2z = -value2.Z * invNorm;
double q2w = value2.W * invNorm;
//-------------------------------------
// Multiply part.
// cross(av, bv)
double cx = q1y * q2z - q1z * q2y;
double cy = q1z * q2x - q1x * q2z;
double cz = q1x * q2y - q1y * q2x;
double dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Returns a boolean indicating whether the two given Quaternions are equal.
/// </summary>
/// <param name="value1">The first Quaternion to compare.</param>
/// <param name="value2">The second Quaternion to compare.</param>
/// <returns>True if the Quaternions are equal; False otherwise.</returns>
public static bool operator ==(Quaternion value1, Quaternion value2)
{
return (value1.X == value2.X &&
value1.Y == value2.Y &&
value1.Z == value2.Z &&
value1.W == value2.W);
}
/// <summary>
/// Returns a boolean indicating whether the two given Quaternions are not equal.
/// </summary>
/// <param name="value1">The first Quaternion to compare.</param>
/// <param name="value2">The second Quaternion to compare.</param>
/// <returns>True if the Quaternions are not equal; False if they are equal.</returns>
public static bool operator !=(Quaternion value1, Quaternion value2)
{
return (value1.X != value2.X ||
value1.Y != value2.Y ||
value1.Z != value2.Z ||
value1.W != value2.W);
}
/// <summary>
/// Returns a boolean indicating whether the given Quaternion is equal to this Quaternion instance.
/// </summary>
/// <param name="other">The Quaternion to compare this instance to.</param>
/// <returns>True if the other Quaternion is equal to this instance; False otherwise.</returns>
public bool Equals(Quaternion other)
{
return (X == other.X &&
Y == other.Y &&
Z == other.Z &&
W == other.W);
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Quaternion instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Quaternion; False otherwise.</returns>
public override bool Equals(object obj)
{
if (obj is Quaternion quaternion)
{
return Equals(quaternion);
}
return false;
}
/// <summary>
/// Returns a String representing this Quaternion instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X, Y, Z, W);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return unchecked(X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode());
}
}
}
| |
using System; // for Basic system types
using System.IO; // for File, Path
using System.Diagnostics; // for TraceInformation ...
using System.Threading;
using System.Security.Permissions;
using System.Runtime.CompilerServices;
#if FEATURE_NETCORE
using System.Core; // for strongly typed resources
#endif
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
#if !FEATURE_NETCORE
[HostProtection(SecurityAction.LinkDemand, Synchronization=true, ExternalThreading=true)]
#endif
[HostProtection(MayLeakOnAbort = true)]
public class ReaderWriterLockSlim : IDisposable
{
//Specifying if the lock can be reacquired recursively.
bool fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with the
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
int myLock;
//The variables controlling spinning behavior of Mylock(which is a spin-lock)
const int LockSpinCycles = 20;
const int LockSpinCount = 10;
const int LockSleep0Count = 5;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
uint numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
uint numUpgradeWaiters;
//Variable used for quick check when there are no waiters.
bool fNoWaiters;
int upgradeLockOwnerId;
int writeLockOwnerId;
// conditions we wait on.
EventWaitHandle writeEvent; // threads waiting to acquire a write lock go here.
EventWaitHandle readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
EventWaitHandle upgradeEvent; // thread waiting to acquire the upgrade lock
EventWaitHandle waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
static long s_nextLockID;
long lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
static ReaderWriterCount t_rwc;
bool fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
//The uint, that contains info like if the writer lock is held, num of
//readers etc.
uint owners;
//Various R/W masks
//Note:
//The Uint is divided as follows:
//
//Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
//Dividing the uint, allows to vastly simplify logic for checking if a
//reader should go in etc. Setting the writer bit, will automatically
//make the value of the uint much larger than the max num of readers
//allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
//The max readers is actually one less than it's theoretical max.
//This is done in order to prevent reader count overflows. If the reader
//count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool fDisposed;
private void InitializeThreadCounts()
{
upgradeLockOwnerId = -1;
writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
fIsReentrant = true;
}
InitializeThreadCounts();
fNoWaiters = true;
lockID = Interlocked.Increment(ref s_nextLockID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != this.lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount rwc = t_rwc;
ReaderWriterCount empty = null;
while (rwc != null)
{
if (rwc.lockID == this.lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = this.lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private int m_total;
private int m_start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException("timeout");
m_total = (int)ltm;
if (m_total != -1 && m_total != 0)
m_start = Environment.TickCount;
else
m_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException("millisecondsTimeout");
m_total = millisecondsTimeout;
if (m_total != -1 && m_total != 0)
m_start = Environment.TickCount;
else
m_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (m_total == -1 || m_total == 0)
return m_total;
int elapsed = Environment.TickCount - m_start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= m_total)
return 0;
return m_total - elapsed;
}
}
public bool IsExpired
{
get
{
return RemainingMilliseconds == 0;
}
}
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
#if !FEATURE_NETCORE
Thread.BeginCriticalRegion();
#endif // !FEATURE_NETCORE
bool result = false;
try
{
result = TryEnterReadLockCore(timeout);
}
finally
{
#if !FEATURE_NETCORE
if (!result)
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
return result;
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if(fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc = null;
int id = Thread.CurrentThread.ManagedThreadId;
if (!fIsReentrant)
{
if (id == writeLockOwnerId)
{
//Check for AW->AR
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_ReadAfterWriteNotAllowed));
}
EnterMyLock();
lrwc = GetThreadRWCount(false);
//Check if the reader lock is already acquired. Note, we could
//check the presence of a reader by not allocating rwc (But that
//would lead to two lookups in the common case. It's better to keep
//a count in the struucture).
if (lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_RecursiveReadNotAllowed));
}
else if (id == upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
owners++;
ExitMyLock();
return true;
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
lrwc.readercount++;
ExitMyLock();
return true;
}
else if (id == upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
owners++;
ExitMyLock();
fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == writeLockOwnerId)
{
//The write lock is already held.
//Update global read counts here,
lrwc.readercount++;
owners++;
ExitMyLock();
return true;
}
}
bool retVal = true;
int spincount = 0;
for (; ; )
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if(IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (readEvent == null) // Create the needed event
{
LazyCreateEvent(ref readEvent, false);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(readEvent, ref numReadWaiters, timeout);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
}
ExitMyLock();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
#if !FEATURE_NETCORE
Thread.BeginCriticalRegion();
#endif // !FEATURE_NETCORE
bool result = false;
try
{
result = TryEnterWriteLockCore(timeout);
}
finally
{
#if !FEATURE_NETCORE
if (!result)
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
return result;
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if(fDisposed)
throw new ObjectDisposedException(null);
int id = Thread.CurrentThread.ManagedThreadId;
ReaderWriterCount lrwc;
bool upgradingToWrite = false;
if (!fIsReentrant)
{
if (id == writeLockOwnerId)
{
//Check for AW->AW
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_RecursiveWriteNotAllowed));
}
else if (id == upgradeLockOwnerId)
{
//AU->AW case is allowed once.
upgradingToWrite = true;
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_WriteAfterReadNotAllowed));
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == writeLockOwnerId)
{
lrwc.writercount++;
ExitMyLock();
return true;
}
else if (id == upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
//Write locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_WriteAfterReadNotAllowed));
}
}
int spincount = 0;
bool retVal = true;
for (; ; )
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
//Check if there is just one upgrader, and no readers.
//Assumption: Only one thread can have the upgrade lock, so the
//following check will fail for all other threads that may sneak in
//when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
//This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(fIsReentrant);
Debug.Assert(fUpgradeThreadHoldingRead);
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
if (upgradingToWrite)
{
if (waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref waitUpgradeEvent, true);
continue; // since we left the lock, start over.
}
Debug.Assert(numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal = WaitOnEvent(waitUpgradeEvent, ref numWriteUpgradeWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref writeEvent, true);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(writeEvent, ref numWriteWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((owners & WRITER_HELD) > 0);
if (fIsReentrant)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.writercount++;
}
ExitMyLock();
writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
#if !FEATURE_NETCORE
Thread.BeginCriticalRegion();
#endif // !FEATURE_NETCORE
bool result = false;
try
{
result = TryEnterUpgradeableReadLockCore(timeout);
}
finally
{
#if !FEATURE_NETCORE
if (!result)
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
return result;
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if(fDisposed)
throw new ObjectDisposedException(null);
int id = Thread.CurrentThread.ManagedThreadId;
ReaderWriterCount lrwc;
if (!fIsReentrant)
{
if (id == upgradeLockOwnerId)
{
//Check for AU->AU
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_RecursiveUpgradeNotAllowed));
}
else if (id == writeLockOwnerId)
{
//Check for AU->AW
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_UpgradeAfterWriteNotAllowed));
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_UpgradeAfterReadNotAllowed));
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == upgradeLockOwnerId)
{
lrwc.upgradecount++;
ExitMyLock();
return true;
}
else if (id == writeLockOwnerId)
{
//Write lock is already held, Just update the global state
//to show presence of upgrader.
Debug.Assert((owners & WRITER_HELD) > 0);
owners++;
upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
fUpgradeThreadHoldingRead = true;
ExitMyLock();
return true;
}
else if (lrwc.readercount > 0)
{
//Upgrade locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.GetString(SR.LockRecursionException_UpgradeAfterReadNotAllowed));
}
}
bool retVal = true;
int spincount = 0;
for (; ; )
{
//Once an upgrade lock is taken, it's like having a reader lock held
//until upgrade or downgrade operations are performed.
if ((upgradeLockOwnerId == -1) && (owners < MAX_READER))
{
owners++;
upgradeLockOwnerId = id;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref upgradeEvent, true);
continue; // since we left the lock, start over.
}
//Only one thread with the upgrade lock held can proceed.
retVal = WaitOnEvent(upgradeEvent, ref numUpgradeWaiters, timeout);
if (!retVal)
return false;
}
if (fIsReentrant)
{
//The lock may have been dropped getting here, so make a quick check to see whether some other
//thread did not grab the entry.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.upgradecount++;
}
ExitMyLock();
return true;
}
public void ExitReadLock()
{
ReaderWriterCount lrwc = null;
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null || lrwc.readercount < 1)
{
//You have to be holding the read lock to make this call.
ExitMyLock();
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedRead));
}
if (fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
ExitMyLock();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
return;
}
if (Thread.CurrentThread.ManagedThreadId == upgradeLockOwnerId)
{
fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!fIsReentrant)
{
if (Thread.CurrentThread.ManagedThreadId != writeLockOwnerId)
{
//You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedWrite));
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedWrite));
}
if (lrwc.writercount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedWrite));
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
ExitMyLock();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
return;
}
}
Debug.Assert((owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount lrwc;
if (!fIsReentrant)
{
if (Thread.CurrentThread.ManagedThreadId != upgradeLockOwnerId)
{
//You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedUpgrade));
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedUpgrade));
}
if (lrwc.upgradecount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_MisMatchedUpgrade));
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
ExitMyLock();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
return;
}
fUpgradeThreadHoldingRead = false;
}
owners--;
upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
#if !FEATURE_NETCORE
Thread.EndCriticalRegion();
#endif // !FEATURE_NETCORE
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
{
#if DEBUG
Debug.Assert(MyLockHeld);
Debug.Assert(waitEvent == null);
#endif
ExitMyLock();
EventWaitHandle newEvent;
if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Close();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
waitEvent.Reset();
numWaiters++;
fNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (numWriteWaiters == 1)
SetWritersWaiting();
if (numWriteUpgradeWaiters == 1)
SetUpgraderWaiting();
bool waitSuccessful = false;
ExitMyLock(); // Do the wait outside of any lock
try
{
waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
}
finally
{
EnterMyLock();
--numWaiters;
if (numWriteWaiters == 0 && numWriteUpgradeWaiters == 0 && numUpgradeWaiters == 0 && numReadWaiters == 0)
fNoWaiters = true;
if (numWriteWaiters == 0)
ClearWritersWaiting();
if (numWriteUpgradeWaiters == 0)
ClearUpgraderWaiting();
if (!waitSuccessful) // We may also be aboutto throw for some reason. Exit myLock.
ExitMyLock();
}
return waitSuccessful;
}
/// <summary>
/// Determines the appropriate events to set, leaves the locks, and sets the events.
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (fNoWaiters)
{
ExitMyLock();
return;
}
ExitAndWakeUpAppropriateWaitersPreferringWriters();
}
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
bool setUpgradeEvent = false;
bool setReadEvent = false;
uint readercount = GetNumReaders();
//We need this case for EU->ER->EW case, as the read count will be 2 in
//that scenario.
if (fIsReentrant)
{
if (numWriteUpgradeWaiters > 0 && fUpgradeThreadHoldingRead && readercount == 2)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
return;
}
}
if (readercount == 1 && numWriteUpgradeWaiters > 0)
{
//We have to be careful now, as we are droppping the lock.
//No new writes should be allowed to sneak in if an upgrade
//was pending.
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
}
else if (readercount == 0 && numWriteWaiters > 0)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
writeEvent.Set(); // release one writer.
}
else if (readercount >= 0)
{
if (numReadWaiters != 0 || numUpgradeWaiters != 0)
{
if (numReadWaiters != 0)
setReadEvent = true;
if (numUpgradeWaiters != 0 && upgradeLockOwnerId == -1)
{
setUpgradeEvent = true;
}
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (setReadEvent)
readEvent.Set(); // release all readers.
if (setUpgradeEvent)
upgradeEvent.Set(); //release one upgrader.
}
else
ExitMyLock();
}
else
ExitMyLock();
}
private bool IsWriterAcquired()
{
return (owners & ~WAITING_WRITERS) == 0;
}
private void SetWriterAcquired()
{
owners |= WRITER_HELD; // indicate we have a writer.
}
private void ClearWriterAcquired()
{
owners &= ~WRITER_HELD;
}
private void SetWritersWaiting()
{
owners |= WAITING_WRITERS;
}
private void ClearWritersWaiting()
{
owners &= ~WAITING_WRITERS;
}
private void SetUpgraderWaiting()
{
owners |= WAITING_UPGRADER;
}
private void ClearUpgraderWaiting()
{
owners &= ~WAITING_UPGRADER;
}
private uint GetNumReaders()
{
return owners & READER_MASK;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0)
EnterMyLockSpin();
}
private void EnterMyLockSpin()
{
int pc = Environment.ProcessorCount;
for (int i = 0; ; i++)
{
if (i < LockSpinCount && pc > 1)
{
Thread.SpinWait(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
}
else if (i < (LockSpinCount + LockSleep0Count))
{
Thread.Sleep(0); // Give up my quantum.
}
else
{
Thread.Sleep(1); // Give up my quantum.
}
if (myLock == 0 && Interlocked.CompareExchange(ref myLock, 1, 0) == 0)
return;
}
}
private void ExitMyLock()
{
Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
Volatile.Write(ref myLock, 0);
}
#if DEBUG
private bool MyLockHeld { get { return myLock != 0; } }
#endif
private static void SpinWait(int SpinCount)
{
//Exponential backoff
if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
{
Thread.SpinWait(LockSpinCycles * SpinCount);
}
else if (SpinCount < MaxSpinCount - 3)
{
Thread.Sleep(0);
}
else
{
Thread.Sleep(1);
}
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if(disposing && !fDisposed)
{
if(WaitingReadCount>0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_IncorrectDispose));
if(IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
throw new SynchronizationLockException(SR.GetString(SR.SynchronizationLockException_IncorrectDispose));
if (writeEvent != null)
{
writeEvent.Close();
writeEvent = null;
}
if (readEvent != null)
{
readEvent.Close();
readEvent = null;
}
if (upgradeEvent != null)
{
upgradeEvent.Close();
upgradeEvent = null;
}
if (waitUpgradeEvent != null)
{
waitUpgradeEvent.Close();
waitUpgradeEvent = null;
}
fDisposed = true;
}
}
public bool IsReadLockHeld
{
get
{
if (RecursiveReadCount > 0)
return true;
else
return false;
}
}
public bool IsUpgradeableReadLockHeld
{
get
{
if (RecursiveUpgradeCount > 0)
return true;
else
return false;
}
}
public bool IsWriteLockHeld
{
get
{
if (RecursiveWriteCount > 0)
return true;
else
return false;
}
}
public LockRecursionPolicy RecursionPolicy
{
get
{
if (fIsReentrant)
{
return LockRecursionPolicy.SupportsRecursion;
}
else
{
return LockRecursionPolicy.NoRecursion;
}
}
}
public int CurrentReadCount
{
get
{
int numreaders = (int)GetNumReaders();
if (upgradeLockOwnerId != -1)
return numreaders - 1;
else
return numreaders;
}
}
public int RecursiveReadCount
{
get
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if(lrwc != null)
count = lrwc.readercount;
return count;
}
}
public int RecursiveUpgradeCount
{
get
{
if (fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if(lrwc != null)
count = lrwc.upgradecount;
return count;
}
else
{
if (Thread.CurrentThread.ManagedThreadId == upgradeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int RecursiveWriteCount
{
get
{
if (fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if(lrwc != null)
count = lrwc.writercount;
return count;
}
else
{
if (Thread.CurrentThread.ManagedThreadId == writeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int WaitingReadCount
{
get
{
return (int)numReadWaiters;
}
}
public int WaitingUpgradeCount
{
get
{
return (int)numUpgradeWaiters;
}
}
public int WaitingWriteCount
{
get
{
return (int)numWriteWaiters;
}
}
}
}
| |
using System;
using System.Reflection;
using System.Web.Mvc;
using Orchard.Blogs.Extensions;
using Orchard.Blogs.Models;
using Orchard.Blogs.Services;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.Core.Contents.Settings;
using Orchard.Localization;
using Orchard.Mvc.AntiForgery;
using Orchard.Mvc.Extensions;
using Orchard.UI.Admin;
using Orchard.UI.Notify;
namespace Orchard.Blogs.Controllers {
[ValidateInput(false), Admin]
public class BlogPostAdminController : Controller, IUpdateModel {
private readonly IBlogService _blogService;
private readonly IBlogPostService _blogPostService;
public BlogPostAdminController(IOrchardServices services, IBlogService blogService, IBlogPostService blogPostService) {
Services = services;
_blogService = blogService;
_blogPostService = blogPostService;
T = NullLocalizer.Instance;
}
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Create(int blogId) {
var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>();
if (blog == null)
return HttpNotFound();
var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost");
blogPost.BlogPart = blog;
if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Not allowed to create blog post")))
return new HttpUnauthorizedResult();
dynamic model = Services.ContentManager.BuildEditor(blogPost);
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
[HttpPost, ActionName("Create")]
[FormValueRequired("submit.Save")]
public ActionResult CreatePOST(int blogId) {
return CreatePOST(blogId, false);
}
[HttpPost, ActionName("Create")]
[FormValueRequired("submit.Publish")]
public ActionResult CreateAndPublishPOST(int blogId) {
if (!Services.Authorizer.Authorize(Permissions.PublishOwnBlogPost, T("Couldn't create content")))
return new HttpUnauthorizedResult();
return CreatePOST(blogId, true);
}
private ActionResult CreatePOST(int blogId, bool publish = false) {
var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>();
if (blog == null)
return HttpNotFound();
var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost");
blogPost.BlogPart = blog;
if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Couldn't create blog post")))
return new HttpUnauthorizedResult();
Services.ContentManager.Create(blogPost, VersionOptions.Draft);
var model = Services.ContentManager.UpdateEditor(blogPost, this);
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
if (publish) {
if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blog.ContentItem, T("Couldn't publish blog post")))
return new HttpUnauthorizedResult();
Services.ContentManager.Publish(blogPost.ContentItem);
}
Services.Notifier.Information(T("Your {0} has been created.", blogPost.TypeDefinition.DisplayName));
return Redirect(Url.BlogPostEdit(blogPost));
}
//todo: the content shape template has extra bits that the core contents module does not (remove draft functionality)
//todo: - move this extra functionality there or somewhere else that's appropriate?
public ActionResult Edit(int blogId, int postId) {
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
var post = _blogPostService.Get(postId, VersionOptions.Latest);
if (post == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, post, T("Couldn't edit blog post")))
return new HttpUnauthorizedResult();
dynamic model = Services.ContentManager.BuildEditor(post);
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public ActionResult EditPOST(int blogId, int postId, string returnUrl) {
return EditPOST(blogId, postId, returnUrl, contentItem => {
if (!contentItem.Has<IPublishingControlAspect>() && !contentItem.TypeDefinition.Settings.GetModel<ContentTypeSettings>().Draftable)
Services.ContentManager.Publish(contentItem);
});
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Publish")]
public ActionResult EditAndPublishPOST(int blogId, int postId, string returnUrl) {
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
// Get draft (create a new version if needed)
var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired);
if (blogPost == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blogPost, T("Couldn't publish blog post")))
return new HttpUnauthorizedResult();
return EditPOST(blogId, postId, returnUrl, contentItem => Services.ContentManager.Publish(contentItem));
}
public ActionResult EditPOST(int blogId, int postId, string returnUrl, Action<ContentItem> conditionallyPublish) {
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
// Get draft (create a new version if needed)
var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired);
if (blogPost == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Couldn't edit blog post")))
return new HttpUnauthorizedResult();
// Validate form input
var model = Services.ContentManager.UpdateEditor(blogPost, this);
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
conditionallyPublish(blogPost.ContentItem);
Services.Notifier.Information(T("Your {0} has been saved.", blogPost.TypeDefinition.DisplayName));
return this.RedirectLocal(returnUrl, Url.BlogPostEdit(blogPost));
}
[ValidateAntiForgeryTokenOrchard]
public ActionResult DiscardDraft(int id) {
// get the current draft version
var draft = Services.ContentManager.Get(id, VersionOptions.Draft);
if (draft == null) {
Services.Notifier.Information(T("There is no draft to discard."));
return RedirectToEdit(id);
}
// check edit permission
if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, draft, T("Couldn't discard blog post draft")))
return new HttpUnauthorizedResult();
// locate the published revision to revert onto
var published = Services.ContentManager.Get(id, VersionOptions.Published);
if (published == null) {
Services.Notifier.Information(T("Can not discard draft on unpublished blog post."));
return RedirectToEdit(draft);
}
// marking the previously published version as the latest
// has the effect of discarding the draft but keeping the history
draft.VersionRecord.Latest = false;
published.VersionRecord.Latest = true;
Services.Notifier.Information(T("Blog post draft version discarded"));
return RedirectToEdit(published);
}
ActionResult RedirectToEdit(int id) {
return RedirectToEdit(Services.ContentManager.GetLatest<BlogPostPart>(id));
}
ActionResult RedirectToEdit(IContent item) {
if (item == null || item.As<BlogPostPart>() == null)
return HttpNotFound();
return RedirectToAction("Edit", new { BlogId = item.As<BlogPostPart>().BlogPart.Id, PostId = item.ContentItem.Id });
}
[ValidateAntiForgeryTokenOrchard]
public ActionResult Delete(int blogId, int postId) {
//refactoring: test PublishBlogPost/PublishBlogPost in addition if published
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
var post = _blogPostService.Get(postId, VersionOptions.Latest);
if (post == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.DeleteBlogPost, post, T("Couldn't delete blog post")))
return new HttpUnauthorizedResult();
_blogPostService.Delete(post);
Services.Notifier.Information(T("Blog post was successfully deleted"));
return Redirect(Url.BlogForAdmin(blog.As<BlogPart>()));
}
[ValidateAntiForgeryTokenOrchard]
public ActionResult Publish(int blogId, int postId) {
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
var post = _blogPostService.Get(postId, VersionOptions.Latest);
if (post == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't publish blog post")))
return new HttpUnauthorizedResult();
_blogPostService.Publish(post);
Services.Notifier.Information(T("Blog post successfully published."));
return Redirect(Url.BlogForAdmin(blog.As<BlogPart>()));
}
[ValidateAntiForgeryTokenOrchard]
public ActionResult Unpublish(int blogId, int postId) {
var blog = _blogService.Get(blogId, VersionOptions.Latest);
if (blog == null)
return HttpNotFound();
var post = _blogPostService.Get(postId, VersionOptions.Latest);
if (post == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't unpublish blog post")))
return new HttpUnauthorizedResult();
_blogPostService.Unpublish(post);
Services.Notifier.Information(T("Blog post successfully unpublished."));
return Redirect(Url.BlogForAdmin(blog.As<BlogPart>()));
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
public class FormValueRequiredAttribute : ActionMethodSelectorAttribute {
private readonly string _submitButtonName;
public FormValueRequiredAttribute(string submitButtonName) {
_submitButtonName = submitButtonName;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
var value = controllerContext.HttpContext.Request.Form[_submitButtonName];
return !string.IsNullOrEmpty(value);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace XSerializer
{
internal sealed class NumberJsonSerializer : IJsonSerializerInternal
{
private static readonly ConcurrentDictionary<Tuple<Type, bool>, NumberJsonSerializer> _cache = new ConcurrentDictionary<Tuple<Type, bool>, NumberJsonSerializer>();
private readonly bool _encrypt;
private readonly bool _nullable;
private readonly Type _type;
private readonly Action<JsonWriter, object> _write;
private readonly Func<string, string, int, int, object> _read;
private NumberJsonSerializer(Type type, bool encrypt)
{
_encrypt = encrypt;
_nullable = type.IsNullableType();
_type = type;
SetDelegates(out _write, out _read);
}
public static NumberJsonSerializer Get(Type type, bool encrypt)
{
return _cache.GetOrAdd(Tuple.Create(type, encrypt), t => new NumberJsonSerializer(t.Item1, t.Item2));
}
public void SerializeObject(JsonWriter writer, object instance, IJsonSerializeOperationInfo info)
{
if (instance == null)
{
writer.WriteNull();
}
else
{
if (_encrypt)
{
var toggler = new EncryptWritesToggler(writer);
toggler.Toggle();
_write(writer, instance);
toggler.Revert();
}
else
{
_write(writer, instance);
}
}
}
public object DeserializeObject(JsonReader reader, IJsonSerializeOperationInfo info, string path)
{
if (!reader.ReadContent(path))
{
if (reader.NodeType == JsonNodeType.EndOfString)
{
throw new MalformedDocumentException(MalformedDocumentError.MissingValue,
path, reader.Value, reader.Line, reader.Position);
}
Debug.Assert(reader.NodeType == JsonNodeType.Invalid);
throw new MalformedDocumentException(MalformedDocumentError.NumberInvalidValue,
path, reader.Value, reader.Line, reader.Position, null, _type);
}
if (_encrypt)
{
var toggler = new DecryptReadsToggler(reader, path);
if (toggler.Toggle())
{
if (reader.NodeType == JsonNodeType.EndOfString)
{
throw new MalformedDocumentException(MalformedDocumentError.MissingValue,
path, reader.Value, reader.Line, reader.Position);
}
var exception = false;
try
{
return Read(reader, path);
}
catch (MalformedDocumentException)
{
exception = true;
throw;
}
finally
{
if (!exception)
{
if (reader.NodeType != JsonNodeType.Null && reader.DecryptReads && (reader.ReadContent(path) || reader.NodeType == JsonNodeType.Invalid))
{
throw new MalformedDocumentException(MalformedDocumentError.ExpectedEndOfDecryptedString,
path, reader.Value, reader.Line, reader.Position, null, reader.NodeType);
}
toggler.Revert();
}
}
}
}
return Read(reader, path);
}
private object Read(JsonReader reader, string path)
{
if (reader.NodeType == JsonNodeType.Number || reader.NodeType == JsonNodeType.String)
{
return _read((string)reader.Value, path, reader.Line, reader.Position);
}
if (_nullable && reader.NodeType == JsonNodeType.Null)
{
return null;
}
throw GetNumberInvalidValueException(reader, path);
}
private void SetDelegates(
out Action<JsonWriter, object> writeAction,
out Func<string, string, int, int, object> readFunc)
{
Func<string, object> readFuncLocal;
if (_type == typeof(double) || _type == typeof(double?))
{
writeAction = (writer, value) => writer.WriteValue((double)value);
readFuncLocal = value => double.Parse(value);
}
else if(_type == typeof(int) || _type == typeof(int?))
{
writeAction = (writer, value) => writer.WriteValue((int)value);
readFuncLocal = value => int.Parse(value);
}
else if(_type == typeof(long) || _type == typeof(long?))
{
writeAction = (writer, value) => writer.WriteValue((long)value);
readFuncLocal = value => long.Parse(value);
}
else if(_type == typeof(uint) || _type == typeof(uint?))
{
writeAction = (writer, value) => writer.WriteValue((uint)value);
readFuncLocal = value => uint.Parse(value);
}
else if(_type == typeof(byte) || _type == typeof(byte?))
{
writeAction = (writer, value) => writer.WriteValue((byte)value);
readFuncLocal = value => byte.Parse(value);
}
else if(_type == typeof(sbyte) || _type == typeof(sbyte?))
{
writeAction = (writer, value) => writer.WriteValue((sbyte)value);
readFuncLocal = value => sbyte.Parse(value);
}
else if(_type == typeof(short) || _type == typeof(short?))
{
writeAction = (writer, value) => writer.WriteValue((short)value);
readFuncLocal = value => short.Parse(value);
}
else if(_type == typeof(ushort) || _type == typeof(ushort?))
{
writeAction = (writer, value) => writer.WriteValue((ushort)value);
readFuncLocal = value => ushort.Parse(value);
}
else if(_type == typeof(ulong) || _type == typeof(ulong?))
{
writeAction = (writer, value) => writer.WriteValue((ulong)value);
readFuncLocal = value => ulong.Parse(value);
}
else if(_type == typeof(float) || _type == typeof(float?))
{
writeAction = (writer, value) => writer.WriteValue((float)value);
readFuncLocal = value => float.Parse(value);
}
else if (_type == typeof(decimal) || _type == typeof(decimal?))
{
writeAction = (writer, value) => writer.WriteValue((decimal)value);
readFuncLocal = value => decimal.Parse(value);
}
else
{
throw new InvalidOperationException("Unknown number type: " + _type);
}
readFunc =
!_type.IsNullableType()
? (Func<string, string, int, int, object>)
((value, path, line, position) =>
Try(readFuncLocal, value, path, line, position))
: (value, path, line, position) =>
string.IsNullOrEmpty(value)
? null
: Try(readFuncLocal, value, path, line, position);
}
private object Try(Func<string, object> parseFunc,
string value, string path, int line, int position)
{
try
{
return parseFunc(value);
}
catch (Exception ex)
{
throw new MalformedDocumentException(MalformedDocumentError.NumberInvalidValue,
path, value, line, position, ex, _type);
}
}
private MalformedDocumentException GetNumberInvalidValueException(JsonReader reader, string path)
{
var invalidValue = reader.Value;
if (invalidValue is bool)
{
invalidValue = invalidValue.ToString().ToLower();
}
return new MalformedDocumentException(MalformedDocumentError.NumberInvalidValue,
path, invalidValue, reader.Line, reader.Position, null, _type);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Shuttle.Core.Infrastructure
{
public class ReflectionService : IReflectionService
{
private readonly List<string> _assemblyExtensions = new List<string>
{
".dll",
".exe"
};
private readonly ILog _log;
public ReflectionService()
{
_log = Log.For(this);
}
public string AssemblyPath(Assembly assembly)
{
Guard.AgainstNull(assembly, "assembly");
return !assembly.IsDynamic
? new Uri(Uri.UnescapeDataString(new UriBuilder(assembly.CodeBase).Path)).LocalPath
: string.Empty;
}
public Assembly GetAssembly(string assemblyPath)
{
var result = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(assembly => AssemblyPath(assembly)
.Equals(assemblyPath, StringComparison.InvariantCultureIgnoreCase));
if (result != null)
{
return result;
}
try
{
switch (Path.GetExtension(assemblyPath))
{
case ".dll":
case ".exe":
{
result = Path.GetDirectoryName(assemblyPath) == AppDomain.CurrentDomain.BaseDirectory
? Assembly.Load(Path.GetFileNameWithoutExtension(assemblyPath))
: Assembly.LoadFile(assemblyPath);
break;
}
default:
{
result = Assembly.Load(assemblyPath);
break;
}
}
}
catch (Exception ex)
{
_log.Warning(string.Format(InfrastructureResources.AssemblyLoadException, assemblyPath, ex.Message));
var reflection = ex as ReflectionTypeLoadException;
if (reflection != null)
{
foreach (var exception in reflection.LoaderExceptions)
{
_log.Trace($"'{exception.AllMessages()}'.");
}
}
else
{
_log.Trace($"{ex.GetType()}: '{ex.AllMessages()}'.");
}
return null;
}
return result;
}
public Assembly FindAssemblyNamed(string name)
{
Guard.AgainstNullOrEmptyString(name, nameof(name));
var assemblyName = name;
var hasFileExtension = false;
if (name.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase)
||
name.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
{
assemblyName = Path.GetFileNameWithoutExtension(name);
hasFileExtension = true;
}
var result = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(assembly => assembly.GetName()
.Name.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase));
if (result != null)
{
return result;
}
var privateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.RelativeSearchPath ?? string.Empty);
var extensions = new List<string>();
if (hasFileExtension)
{
extensions.Add(string.Empty);
}
else
{
extensions.AddRange(_assemblyExtensions);
}
foreach (var extension in extensions)
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Concat(name, extension));
if (File.Exists(path))
{
return GetAssembly(path);
}
if (!privateBinPath.Equals(AppDomain.CurrentDomain.BaseDirectory))
{
path = Path.Combine(privateBinPath, string.Concat(name, extension));
if (File.Exists(path))
{
return GetAssembly(path);
}
}
}
return null;
}
public IEnumerable<Assembly> GetAssemblies(string folder)
{
return GetMatchingAssemblies(string.Empty, folder);
}
public IEnumerable<Assembly> GetAssemblies()
{
return GetMatchingAssemblies(string.Empty);
}
public IEnumerable<Assembly> GetMatchingAssemblies(string regex, string folder)
{
var expression = new Regex(regex, RegexOptions.IgnoreCase);
var result = new List<Assembly>();
if (Directory.Exists(folder))
{
result.AddRange(
Directory.GetFiles(folder, "*.exe")
.Where(file => expression.IsMatch(Path.GetFileNameWithoutExtension(file)))
.Select(GetAssembly)
.Where(assembly => assembly != null));
result.AddRange(
Directory.GetFiles(folder, "*.dll")
.Where(file => expression.IsMatch(Path.GetFileNameWithoutExtension(file)))
.Select(GetAssembly)
.Where(assembly => assembly != null));
}
return result;
}
public IEnumerable<Assembly> GetMatchingAssemblies(string regex)
{
var assemblies = new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
foreach (
var assembly in
GetMatchingAssemblies(regex, AppDomain.CurrentDomain.BaseDirectory)
.Where(assembly => assemblies.Find(candidate => candidate.Equals(assembly)) == null))
{
assemblies.Add(assembly);
}
var privateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.RelativeSearchPath ?? string.Empty);
if (!privateBinPath.Equals(AppDomain.CurrentDomain.BaseDirectory))
{
foreach (
var assembly in
GetMatchingAssemblies(regex, privateBinPath)
.Where(assembly => assemblies.Find(candidate => candidate.Equals(assembly)) == null))
{
assemblies.Add(assembly);
}
}
return assemblies;
}
public IEnumerable<Type> GetTypes<T>()
{
return GetTypes(typeof(T));
}
public IEnumerable<Type> GetTypes(Type type)
{
var result = new List<Type>();
foreach (var assembly in GetAssemblies())
{
GetTypes(type, assembly)
.Where(candidate => result.Find(existing => existing == candidate) == null)
.ToList()
.ForEach(add => result.Add(add));
}
return result;
}
public IEnumerable<Type> GetTypes<T>(Assembly assembly)
{
return GetTypes(typeof(T), assembly);
}
public IEnumerable<Type> GetTypes(Type type, Assembly assembly)
{
Guard.AgainstNull(type, "type");
Guard.AgainstNull(assembly, "assemblyPath");
return GetTypes(assembly).Where(candidate => candidate.IsAssignableTo(type) && candidate != type).ToList();
}
public IEnumerable<Type> GetTypes(Assembly assembly)
{
Type[] types;
try
{
_log.Trace(string.Format(InfrastructureResources.TraceGetTypesFromAssembly, assembly));
types = assembly.GetTypes();
}
catch (Exception ex)
{
var reflection = ex as ReflectionTypeLoadException;
if (reflection != null)
{
foreach (var exception in reflection.LoaderExceptions)
{
_log.Error($"'{exception.AllMessages()}'.");
}
}
else
{
_log.Error($"{ex.GetType()}: '{ex.AllMessages()}'.");
}
return new List<Type>();
}
return types;
}
}
}
| |
using Swashbuckle.Application;
using System;
using System.IO;
using System.Web.Http;
using System.Xml.Linq;
namespace EduardoBursa.Templates.WebApi
{
/// <summary>
/// Defines an entry point for swagger web api configuration.
/// </summary>
public partial class Startup
{
/// <summary>
/// Configures the swagger and swagger UI on application.
/// </summary>
/// <remarks>
/// For more information:
/// https://github.com/domaindrivendev/Swashbuckle#swashbuckle-50
/// </remarks>
public static void ConfigureSwagger(HttpConfiguration config)
{
var thisAssembly = typeof(Startup).Assembly;
config
.EnableSwagger(c =>
{
// By default, the service root url is inferred from the request used to access the docs.
// However, there may be situations (e.g. proxy and load-balanced environments) where this does not
// resolve correctly. You can workaround this by providing your own code to determine the root URL.
//
//c.RootUrl(req => GetRootUrlFromAppConfig());
// If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access
// the docs is taken as the default. If your API supports multiple schemes and you want to be explicit
// about them, you can use the "Schemes" option as shown below.
//
//c.Schemes(new[] { "http", "https" });
// Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to
// hold additional metadata for an API. Version and title are required but you can also provide
// additional fields by chaining methods off SingleApiVersion.
//
c.SingleApiVersion("v1", "Template - Web Api");
// If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
// In this case, you must provide a lambda that tells Swashbuckle which actions should be
// included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
// returns an "Info" builder so you can provide additional metadata per API version.
//
//c.MultipleApiVersions(
// (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
// (vc) =>
// {
// vc.Version("v2", "Swashbuckle Dummy API V2");
// vc.Version("v1", "Swashbuckle Dummy API V1");
// });
// You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API.
// See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details.
// NOTE: These only define the schemes and need to be coupled with a corresponding "security" property
// at the document or operation level to indicate which schemes are required for an operation. To do this,
// you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
// according to your specific authorization implementation
//
//c.BasicAuth("basic")
// .Description("Basic HTTP Authentication");
//
// NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
//c.ApiKey("apiKey")
// .Description("API Key Authentication")
// .Name("apiKey")
// .In("header");
//
// Set this flag to omit descriptions for any actions decorated with the Obsolete attribute
//c.IgnoreObsoleteActions();
// Each operation be assigned one or more tags which are then used by consumers for various reasons.
// For example, the swagger-ui groups operations according to the first tag of each operation.
// By default, this will be controller name but you can use the "GroupActionsBy" option to
// override with any value.
//
//c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString());
// You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate
// the order in which operations are listed. For example, if the default grouping is in place
// (controller name) and you specify a descending alphabetic sort order, then actions from a
// ProductsController will be listed before thoseana from a CustomersController. This is typically
// used to customize the order of groupings in the swagger-ui.
//
//c.OrderActionGroupsBy(new DescendingAlphabeticComparer());
// If you annotate Controllers and API Types with
// Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
// those comments into the generated docs and UI. You can enable this by providing the path to one or
// more Xml comment files.
//
c.IncludeXmlComments(GetXmlCommentsPath());
// Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types
// exposed in your API. However, there may be occasions when more control of the output is needed.
// This is supported through the "MapType" and "SchemaFilter" options:
//
// Use the "MapType" option to override the Schema generation for a specific type.
// It should be noted that the resulting Schema will be placed "inline" for any applicable Operations.
// While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not.
// It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only
// use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a
// complex Schema, use a Schema filter.
//
//c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" });
// If you want to post-modify "complex" Schemas once they've been generated, across the board or for a
// specific type, you can wire up one or more Schema filters.
//
//c.SchemaFilter<ApplySchemaVendorExtensions>();
// In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique
// Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this
// works well because it prevents the "implementation detail" of type namespaces from leaking into your
// Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll
// need to opt out of this behavior to avoid Schema Id conflicts.
//
//c.UseFullTypeNameInSchemaIds();
// Alternatively, you can provide your own custom strategy for inferring SchemaId's for
// describing "complex" types in your API.
//
//c.SchemaId(t => t.FullName.Contains('`') ? t.FullName.Substring(0, t.FullName.IndexOf('`')) : t.FullName);
// Set this flag to omit schema property descriptions for any type properties decorated with the
// Obsolete attribute
//c.IgnoreObsoleteProperties();
// In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers.
// You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given
// enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different
// approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings.
//
//c.DescribeAllEnumsAsStrings();
// Similar to Schema filters, Swashbuckle also supports Operation and Document filters:
//
// Post-modify Operation descriptions once they've been generated by wiring up one or more
// Operation filters.
//
//c.OperationFilter<AddDefaultResponse>();
//
// If you've defined an OAuth2 flow as described above, you could use a custom filter
// to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required
// to execute the operation
//
//c.OperationFilter<AssignOAuth2SecurityRequirements>();
// Post-modify the entire Swagger document by wiring up one or more Document filters.
// This gives full control to modify the final SwaggerDocument. You should have a good understanding of
// the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
// before using this option.
//
//c.DocumentFilter<ApplyDocumentVendorExtensions>();
// In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL
// to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions
// with the same path (sans query string) and HTTP method. You can workaround this by providing a
// custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs
//
//c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
// Wrap the default SwaggerGenerator with additional behavior (e.g. caching) or provide an
// alternative implementation for ISwaggerProvider with the CustomProvider option.
//
//c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
})
.EnableSwaggerUi(c =>
{
// Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets.
// The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown below.
//
//c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
c.InjectStylesheet(thisAssembly, $"{thisAssembly.GetName().Name}.Extensions.Swagger.index.css");
// Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
// has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown above.
//
//c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
// The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false"
// strings as the possible choices. You can use this option to change these to something else,
// for example 0 and 1.
//
//c.BooleanValues(new[] { "0", "1" });
// By default, swagger-ui will validate specs against swagger.io's online validator and display the result
// in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the
// feature entirely.
//c.SetValidatorUrl("http://localhost/validator");
c.DisableValidator();
// Use this option to control how the Operation listing is displayed.
// It can be set to "None" (default), "List" (shows operations for each resource),
// or "Full" (fully expanded: shows operations and their details).
//
//c.DocExpansion(DocExpansion.List);
// Specify which HTTP operations will have the 'Try it out!' option. An empty paramter list disables
// it for all operations.
//
//c.SupportedSubmitMethods("GET", "HEAD");
// Use the CustomAsset option to provide your own version of assets used in the swagger-ui.
// It's typically used to instruct Swashbuckle to return your version instead of the default
// when a request is made for "index.html". As with all custom content, the file must be included
// in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to
// the method as shown below.
//
//c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html");
c.CustomAsset("index", thisAssembly, $"{thisAssembly.GetName().Name}.Extensions.Swagger.index.html");
// If your API has multiple versions and you've applied the MultipleApiVersions setting
// as described above, you can also enable a select box in the swagger-ui, that displays
// a discovery URL for each version. This provides a convenient way for users to browse documentation
// for different API versions.
//
//c.EnableDiscoveryUrlSelector();
// If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
// the Swagger 2.0 specification, you can enable UI support as shown below.
//
//c.EnableOAuth2Support(
// clientId: "test-client-id",
// clientSecret: "abc",
// realm: "test-realm",
// appName: "Swagger UI"
////additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } }
//);
// If your API supports ApiKey, you can override the default values.
// "apiKeyIn" can either be "query" or "header"
//
//c.EnableApiKeySupport("apiKey", "header");
});
}
/// <summary>
/// Gets the path to the xml document that contains the comments.
/// </summary>
/// <returns></returns>
private static string GetXmlCommentsPath()
{
string documentationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "SwaggerDocumentation.xml");
#if DEBUG
BuildSwaggerDocumentationFile(documentationFilePath);
#else
if (!File.Exists(documentationFilePath))
BuildSwaggerDocumentationFile(documentationFilePath);
#endif
return documentationFilePath;
}
/// <summary>
/// Builds the swagger documentation file.
/// </summary>
/// <remarks>
/// It must contain the logic to combine all documentation
/// files you need to expose right documentation on your web api.
/// </remarks>
/// <returns></returns>
private static string BuildSwaggerDocumentationFile(string documentationFilePath)
{
XElement xml = null;
XElement dependentXml = null;
string docsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
// TODO: validade search pattern logic to get xml comments to build main documentation file
foreach (string filePath in Directory.GetFiles(docsDirectory, "*.xml"))
{
if (xml == null)
{
xml = XElement.Load(filePath);
}
else
{
dependentXml = XElement.Load(filePath);
foreach (XElement element in dependentXml.Descendants())
{
xml.Add(element);
}
}
}
if (xml != null)
{
xml.Save(documentationFilePath);
}
return documentationFilePath;
}
}
}
| |
// 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 global::System;
using global::System.Reflection;
using global::System.Diagnostics;
using global::System.Collections.Generic;
using global::System.Reflection.Runtime.General;
using global::System.Reflection.Runtime.Types;
using global::System.Reflection.Runtime.TypeInfos;
using global::System.Reflection.Runtime.Assemblies;
using global::System.Reflection.Runtime.TypeParsing;
using global::Internal.Reflection.Core;
using global::Internal.Reflection.Core.Execution;
using global::Internal.Reflection.Core.NonPortable;
using global::Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.General
{
internal static class TypeResolver
{
//
// Main routine to resolve a typeDef/Ref/Spec.
//
internal static RuntimeType Resolve(this ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeDefRefOrSpec, TypeContext typeContext)
{
Exception exception = null;
RuntimeType runtimeType = reflectionDomain.TryResolve(reader, typeDefRefOrSpec, typeContext, ref exception);
if (runtimeType == null)
throw exception;
return runtimeType;
}
internal static RuntimeType TryResolve(this ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeDefRefOrSpec, TypeContext typeContext, ref Exception exception)
{
HandleType handleType = typeDefRefOrSpec.HandleType;
if (handleType == HandleType.TypeDefinition)
return reflectionDomain.ResolveTypeDefinition(reader, typeDefRefOrSpec.ToTypeDefinitionHandle(reader));
else if (handleType == HandleType.TypeReference)
return reflectionDomain.TryResolveTypeReference(reader, typeDefRefOrSpec.ToTypeReferenceHandle(reader), ref exception);
else if (handleType == HandleType.TypeSpecification)
return reflectionDomain.TryResolveTypeSignature(reader, typeDefRefOrSpec.ToTypeSpecificationHandle(reader), typeContext, ref exception);
else
throw new BadImageFormatException(); // Expected TypeRef, Def or Spec.
}
//
// Main routine to resolve a typeDefinition.
//
internal static RuntimeType ResolveTypeDefinition(this ReflectionDomain reflectionDomain, MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle)
{
return RuntimeTypeUnifierEx.GetNamedType(reader, typeDefinitionHandle);
}
//
// Main routine to parse a metadata type specification signature.
//
private static RuntimeType TryResolveTypeSignature(this ReflectionDomain reflectionDomain, MetadataReader reader, TypeSpecificationHandle typeSpecHandle, TypeContext typeContext, ref Exception exception)
{
Handle typeHandle = typeSpecHandle.GetTypeSpecification(reader).Signature;
switch (typeHandle.HandleType)
{
case HandleType.ArraySignature:
{
ArraySignature sig = typeHandle.ToArraySignatureHandle(reader).GetArraySignature(reader);
int rank = sig.Rank;
if (rank <= 0)
throw new BadImageFormatException(); // Bad rank.
RuntimeType elementType = reflectionDomain.TryResolve(reader, sig.ElementType, typeContext, ref exception);
if (elementType == null)
return null;
return ReflectionCoreNonPortable.GetMultiDimArrayType(elementType, rank);
}
case HandleType.ByReferenceSignature:
{
ByReferenceSignature sig = typeHandle.ToByReferenceSignatureHandle(reader).GetByReferenceSignature(reader);
RuntimeType targetType = reflectionDomain.TryResolve(reader, sig.Type, typeContext, ref exception);
if (targetType == null)
return null;
return ReflectionCoreNonPortable.GetByRefType(targetType);
}
case HandleType.MethodTypeVariableSignature:
{
MethodTypeVariableSignature sig = typeHandle.ToMethodTypeVariableSignatureHandle(reader).GetMethodTypeVariableSignature(reader);
return typeContext.GenericMethodArguments[sig.Number];
}
case HandleType.PointerSignature:
{
PointerSignature sig = typeHandle.ToPointerSignatureHandle(reader).GetPointerSignature(reader);
RuntimeType targetType = reflectionDomain.TryResolve(reader, sig.Type, typeContext, ref exception);
if (targetType == null)
return null;
return ReflectionCoreNonPortable.GetPointerType(targetType);
}
case HandleType.SZArraySignature:
{
SZArraySignature sig = typeHandle.ToSZArraySignatureHandle(reader).GetSZArraySignature(reader);
RuntimeType elementType = reflectionDomain.TryResolve(reader, sig.ElementType, typeContext, ref exception);
if (elementType == null)
return null;
return ReflectionCoreNonPortable.GetArrayType(elementType);
}
case HandleType.TypeDefinition:
{
return reflectionDomain.ResolveTypeDefinition(reader, typeHandle.ToTypeDefinitionHandle(reader));
}
case HandleType.TypeInstantiationSignature:
{
TypeInstantiationSignature sig = typeHandle.ToTypeInstantiationSignatureHandle(reader).GetTypeInstantiationSignature(reader);
RuntimeType genericTypeDefinition = reflectionDomain.TryResolve(reader, sig.GenericType, typeContext, ref exception);
if (genericTypeDefinition == null)
return null;
LowLevelList<RuntimeType> genericTypeArguments = new LowLevelList<RuntimeType>();
foreach (Handle genericTypeArgumentHandle in sig.GenericTypeArguments)
{
RuntimeType genericTypeArgument = reflectionDomain.TryResolve(reader, genericTypeArgumentHandle, typeContext, ref exception);
if (genericTypeArgument == null)
return null;
genericTypeArguments.Add(genericTypeArgument);
}
return ReflectionCoreNonPortable.GetConstructedGenericType(genericTypeDefinition, genericTypeArguments.ToArray());
}
case HandleType.TypeReference:
{
return reflectionDomain.TryResolveTypeReference(reader, typeHandle.ToTypeReferenceHandle(reader), ref exception);
}
case HandleType.TypeVariableSignature:
{
TypeVariableSignature sig = typeHandle.ToTypeVariableSignatureHandle(reader).GetTypeVariableSignature(reader);
return typeContext.GenericTypeArguments[sig.Number];
}
default:
throw new NotSupportedException(); // Unexpected Type signature type.
}
}
//
// Main routine to resolve a typeReference.
//
private static RuntimeType TryResolveTypeReference(this ReflectionDomain reflectionDomain, MetadataReader reader, TypeReferenceHandle typeReferenceHandle, ref Exception exception)
{
{
ExecutionDomain executionDomain = reflectionDomain as ExecutionDomain;
if (executionDomain != null)
{
RuntimeTypeHandle resolvedRuntimeTypeHandle;
if (executionDomain.ExecutionEnvironment.TryGetNamedTypeForTypeReference(reader, typeReferenceHandle, out resolvedRuntimeTypeHandle))
return ReflectionCoreNonPortable.GetTypeForRuntimeTypeHandle(resolvedRuntimeTypeHandle);
}
}
TypeReference typeReference = typeReferenceHandle.GetTypeReference(reader);
String name = typeReference.TypeName.GetString(reader);
Handle parent = typeReference.ParentNamespaceOrType;
HandleType parentType = parent.HandleType;
TypeInfo outerTypeInfo = null;
// Check if this is a reference to a nested type.
if (parentType == HandleType.TypeDefinition)
{
outerTypeInfo = RuntimeNamedTypeInfo.GetRuntimeNamedTypeInfo(reader, parent.ToTypeDefinitionHandle(reader));
}
else if (parentType == HandleType.TypeReference)
{
RuntimeType outerType = reflectionDomain.TryResolveTypeReference(reader, parent.ToTypeReferenceHandle(reader), ref exception);
if (outerType == null)
return null;
outerTypeInfo = outerType.GetTypeInfo(); // Since we got to outerType via a metadata reference, we're assured GetTypeInfo() won't throw a MissingMetadataException.
}
if (outerTypeInfo != null)
{
// It was a nested type. We've already resolved the containing type recursively - just find the nested among its direct children.
TypeInfo resolvedTypeInfo = outerTypeInfo.GetDeclaredNestedType(name);
if (resolvedTypeInfo == null)
{
exception = reflectionDomain.CreateMissingMetadataException(outerTypeInfo, name);
return null;
}
return (RuntimeType)(resolvedTypeInfo.AsType());
}
// If we got here, the typeReference was to a non-nested type.
if (parentType == HandleType.NamespaceReference)
{
AssemblyQualifiedTypeName assemblyQualifiedTypeName = parent.ToNamespaceReferenceHandle(reader).ToAssemblyQualifiedTypeName(name, reader);
RuntimeType runtimeType;
exception = assemblyQualifiedTypeName.TryResolve(reflectionDomain, null, /*ignoreCase: */false, out runtimeType);
if (exception != null)
return null;
return runtimeType;
}
throw new BadImageFormatException(); // Expected TypeReference parent to be typeRef, typeDef or namespaceRef.
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CognitiveServices
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CognitiveServicesAccountsOperations.
/// </summary>
public static partial class CognitiveServicesAccountsOperationsExtensions
{
/// <summary>
/// Create Cognitive Services Account. Accounts is a resource group wide
/// resource type. It holds the keys for developer to access intelligent APIs.
/// It's also the resource type for billing.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
public static CognitiveServicesAccount Create(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccountCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create Cognitive Services Account. Accounts is a resource group wide
/// resource type. It holds the keys for developer to access intelligent APIs.
/// It's also the resource type for billing.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> CreateAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='sku'>
/// Gets or sets the SKU of the resource.
/// </param>
/// <param name='tags'>
/// Gets or sets a list of key value pairs that describe the resource. These
/// tags can be used in viewing and grouping this resource (across resource
/// groups). A maximum of 15 tags can be provided for a resource. Each tag must
/// have a key no greater than 128 characters and value no greater than 256
/// characters.
/// </param>
public static CognitiveServicesAccount Update(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, Sku sku = default(Sku), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
return operations.UpdateAsync(resourceGroupName, accountName, sku, tags).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='sku'>
/// Gets or sets the SKU of the resource.
/// </param>
/// <param name='tags'>
/// Gets or sets a list of key value pairs that describe the resource. These
/// tags can be used in viewing and grouping this resource (across resource
/// groups). A maximum of 15 tags can be provided for a resource. Each tag must
/// have a key no greater than 128 characters and value no greater than 256
/// characters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> UpdateAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, Sku sku = default(Sku), IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, sku, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Cognitive Services account from the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static void Delete(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Cognitive Services account from the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a Cognitive Services account specified by the parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccount GetProperties(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a Cognitive Services account specified by the parameters.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccount> GetPropertiesAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the account keys for the specified Cognitive Services account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccountKeys ListKeys(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the account keys for the specified Cognitive Services account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountKeys> ListKeysAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the specified account key for the specified Cognitive Services
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='keyName'>
/// key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
/// </param>
public static CognitiveServicesAccountKeys RegenerateKey(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, KeyName keyName)
{
return operations.RegenerateKeyAsync(resourceGroupName, accountName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the specified account key for the specified Cognitive Services
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='keyName'>
/// key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountKeys> RegenerateKeyAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, KeyName keyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List available SKUs for the requested Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
public static CognitiveServicesAccountEnumerateSkusResult ListSkus(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName)
{
return operations.ListSkusAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// List available SKUs for the requested Cognitive Services account
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of Cognitive Services account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CognitiveServicesAccountEnumerateSkusResult> ListSkusAsync(this ICognitiveServicesAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSkusWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Linq;
using System.Web.Security;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Collections.Generic;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Runtime;
using Microsoft.Xrm.Portal.Web.Security.LiveId;
namespace Microsoft.Xrm.Portal.Web.Security
{
/// <summary>
/// A pseudo membership provider to enable the use of some .NET login controls.
/// </summary>
/// <remarks>
/// Configuration format.
/// <code>
/// <![CDATA[
/// <configuration>
///
/// <connectionStrings>
/// <add name="Xrm" connectionString="ServiceUri=...; Domain=...; Username=...; Password=..."/>
/// <add name="Live" connectionString="Application Id=...; Secret=..."/>
/// </connectionStrings>
///
/// <system.web>
///
/// <machineKey validationKey="..." decryptionKey="..." validation="SHA1" decryption="AES"/>
///
/// <membership defaultProvider="Xrm">
/// <providers>
/// <add
/// name="Xrm"
/// type="Microsoft.Xrm.Portal.Web.Security.LiveIdMembershipProvider"
/// liveIdConnectionStringName="Live"
/// connectionStringName="Xrm"
/// contextName="Xrm" [Microsoft.Xrm.Client.Configuration.OrganizationServiceContextElement]
/// />
/// </providers>
/// </membership>
///
/// </system.web>
///
/// <system.webServer>
/// <handlers>
/// <add
/// name="LiveId" verb="*"
/// path="LiveId.axd"
/// type="Microsoft.Xrm.Portal.Web.Handlers.LiveIdWebAuthenticationHandler, Microsoft.Xrm.Portal"
/// preCondition="integratedMode"/>
/// </handlers>
/// </system.webServer>
///
/// </configuration>
/// ]]>
/// </code>
/// </remarks>
/// <seealso cref="OrganizationServiceContextElement"/>
/// <seealso cref="PortalCrmConfigurationManager"/>
/// <seealso cref="CrmConfigurationManager"/>
public class LiveIdMembershipProvider : MembershipProvider // MSBug #120050: Won't seal, inheritance is expected extension point.
{
private string _applicationName;
private bool _initialized;
/// <summary>
/// The Windows Live Application ID.
/// </summary>
public string AppId { get; private set; }
///<summary>
///The name of the application using the membership provider.
///</summary>
public override string ApplicationName
{
get { return _applicationName; }
set
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("{0} - 'ApplicationName' cannot be null or empty.".FormatWith(ToString()));
if (value.Length > 0x100) throw new ProviderException("{0} - 'ApplicationName too long".FormatWith(ToString()));
_applicationName = value;
}
}
/// <summary>
/// The name of the <see cref="CrmConnection"/> used by the provider.
/// </summary>
public string ConnectionStringName { get; private set; }
/// <summary>
/// The name of the Live ID connection used by the provider.
/// </summary>
public string LiveIdConnectionStringName { get; private set; }
/// <summary>
/// Accessor to the single available <see cref="LiveIdMembershipProvider"/> provider.
/// </summary>
public static LiveIdMembershipProvider Current
{
get
{
// find the single LiveIdMembershipProvider
var providers =
from MembershipProvider provider in Membership.Providers
where provider is LiveIdMembershipProvider
select provider as LiveIdMembershipProvider;
if (providers.Count() > 1)
{
throw new ProviderException("Only a single '{0}' may added in the web.config. Remove any extra membership providers.".FormatWith(typeof(LiveIdMembershipProvider)));
}
return providers.SingleOrDefault();
}
}
/// <summary>
/// Initializes the provider with the property values specified in the ASP.NET application's configuration file.
/// </summary>
public override void Initialize(string name, NameValueCollection config)
{
if (_initialized) return;
config.ThrowOnNull("config");
if (string.IsNullOrEmpty(name))
{
name = GetType().FullName;
}
if (string.IsNullOrEmpty(config["description"]))
{
config["description"] = "Windows Live Id Membership Provider";
}
base.Initialize(name, config);
ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName();
var connectionStringName = config["connectionStringName"];
var contextName = config["contextName"];
if (!string.IsNullOrWhiteSpace(connectionStringName))
{
ConnectionStringName = connectionStringName;
}
else if (!string.IsNullOrWhiteSpace(contextName))
{
ConnectionStringName = CrmConfigurationManager.GetConnectionStringNameFromContext(contextName);
}
else if (CrmConfigurationManager.CreateConnectionStringSettings(connectionStringName) != null)
{
ConnectionStringName = name;
}
else
{
ConnectionStringName = CrmConfigurationManager.GetConnectionStringNameFromContext(name, true);
}
if (string.IsNullOrEmpty(ConnectionStringName))
{
throw new ConfigurationErrorsException("One of 'connectionStringName' or 'contextName' must be specified on the '{0}' named '{1}'.".FormatWith(this, name));
}
LiveIdConnectionStringName = config["liveIdConnectionStringName"];
if (string.IsNullOrEmpty(LiveIdConnectionStringName))
{
throw new ConfigurationErrorsException("The 'liveIdConnectionStringName' must be specified on the '{0}' named '{1}'.".FormatWith(this, name));
}
var parameters = LiveIdConnectionStringName.ToDictionaryFromConnectionStringName();
AppId = parameters.FirstNotNullOrEmpty("AppId", "Application Id", "ApplicationId");
// Remove all of the known configuration values. If there are any left over, they are unrecognized.
config.Remove("name");
config.Remove("applicationName");
config.Remove("contextName");
config.Remove("connectionStringName");
config.Remove("liveIdConnectionStringName");
if (config.Count > 0)
{
string unrecognizedAttribute = config.GetKey(0);
if (!string.IsNullOrEmpty(unrecognizedAttribute))
{
throw new ConfigurationErrorsException("The '{0}' named '{1}' does not currently recognize or support the attribute '{2}'.".FormatWith(this, name, unrecognizedAttribute));
}
}
_initialized = true;
}
#region Members Not Implemented
public override bool EnablePasswordRetrieval { get { return false; } }
public override bool EnablePasswordReset { get { return false; } }
public override bool RequiresQuestionAndAnswer { get { return false; } }
public override int MaxInvalidPasswordAttempts { get { throw new NotImplementedException(); } }
public override int PasswordAttemptWindow { get { throw new NotImplementedException(); } }
public override MembershipPasswordFormat PasswordFormat { get { throw new NotImplementedException(); } }
public override int MinRequiredPasswordLength { get { return 0; } }
public override int MinRequiredNonAlphanumericCharacters { get { return 0; } }
public override string PasswordStrengthRegularExpression { get { throw new NotImplementedException(); } }
public override bool RequiresUniqueEmail { get { return false; } }
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Creates the Live ID user and authenticates with forms authentication if <paramref name="setUserOnline"/> is true.
/// </summary>
/// <param name="token">The token returned from Live ID that contains information about the user.</param>
/// <param name="setUserOnline">If true, the user will be authenticated once created.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
/// </returns>
public MembershipUser CreateUser(string token, bool setUserOnline)
{
var user = GetWindowsLiveLoginUser(token);
if (user == null)
{
return null;
}
MembershipCreateStatus status;
var membershipUser = CreateUser(user.Id, null, null, null, null, true, null, out status);
if (membershipUser == null) throw new MembershipCreateUserException(status);
if (setUserOnline)
{
FormsAuthentication.SetAuthCookie(membershipUser.UserName, user.UsePersistentCookie);
}
return membershipUser;
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the information for the newly created user.
/// </returns>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">NOT SUPPORTED.</param>
/// <param name="email">NOT SUPPORTED.</param>
/// <param name="passwordQuestion">NOT SUPPORTED.</param>
/// <param name="passwordAnswer">NOT SUPPORTED.</param>
/// <param name="isApproved">NOT SUPPORTED.</param>
/// <param name="providerUserKey">NOT SUPPORTED.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus" /> enumeration value indicating whether the user was created successfully.</param>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
if (string.IsNullOrEmpty(username))
{
status = MembershipCreateStatus.InvalidUserName;
return null;
}
var user = new LiveIdUser(ConnectionStringName, username) { Approved = isApproved };
user.Save();
status = MembershipCreateStatus.Success;
return new MembershipUser(Name, username, username, string.Empty, string.Empty, string.Empty, isApproved, false, user.CreatedAt.Value, user.LastLogin, user.LastLogin, DateTime.MinValue, DateTime.MinValue);
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <returns>
/// true if the user was successfully deleted; otherwise, false.
/// </returns>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
LiveIdUser.Delete(username, ConnectionStringName);
return LiveIdUser.GetByUserId(username, ConnectionStringName) == null;
}
/// <summary>
/// Gets the Passport Unique Identifier from a Windows Live ID token.
/// </summary>
public string GetPuid(string token)
{
var user = GetWindowsLiveLoginUser(token);
return user == null ? null : user.Id;
}
/// <summary>
/// Gets user information from the data source based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the specified user's information from the data source.
/// </returns>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (!(providerUserKey is string)) throw new NotSupportedException();
return GetUser(providerUserKey as string, userIsOnline);
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the specified user's information from the data source.
/// </returns>
/// <param name="username">The name of the user to get information for. </param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user. </param>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (string.IsNullOrEmpty(username)) return null;
var user = LiveIdUser.GetByUserId(username, ConnectionStringName);
if (user == null) return null;
if (userIsOnline)
{
user.LastLogin = DateTime.UtcNow;
user.Save();
}
return new MembershipUser(Name, user.UserId, user.UserId, string.Empty, string.Empty, string.Empty, user.Approved, false, user.CreatedAt.Value, user.LastLogin, user.LastLogin, DateTime.MinValue, DateTime.MinValue);
}
/// <summary>
/// Sets a user as authenticated using forms authentication and the Windows Live ID token.
/// </summary>
/// <param name="token">The Windows Live ID token that contains the user to set as authenticated.</param>
/// <returns>true if successful; otherwise, false</returns>
public bool SetUserOnline(string token)
{
var user = GetWindowsLiveLoginUser(token);
if (user == null) return false;
ValidateUser(user.Id, user.Id);
FormsAuthentication.SetAuthCookie(user.Id, user.UsePersistentCookie);
return true;
}
/// <summary>
/// Updates information about a user in the data source.
/// </summary>
/// <param name="user">A <see cref="T:System.Web.Security.MembershipUser" /> object that represents the user to update and the updated information for the user. </param>
public override void UpdateUser(MembershipUser user)
{
user.ThrowOnNull("user");
var liveIdUser = LiveIdUser.GetByUserId(user.UserName, ConnectionStringName);
if (liveIdUser == null) throw new ArgumentException("Unable to find the user with ID '{0}'.".FormatWith(user.UserName));
liveIdUser.LastLogin = user.LastLoginDate;
liveIdUser.Approved = user.IsApproved;
liveIdUser.Save();
}
/// <summary>
/// Verifies that the specified user id exists in the data source and is approved.
/// </summary>
/// <returns>
/// true if the specified username exists and is approved; otherwise, false.
/// </returns>
/// <param name="username">The id of the user.</param>
/// <param name="password">NOT SUPPORTED.</param>
public override bool ValidateUser(string username, string password)
{
username.ThrowOnNullOrWhitespace("username");
var user = LiveIdUser.GetByUserId(username, ConnectionStringName);
if (user == null || !user.Approved) return false;
user.LastLogin = DateTime.UtcNow;
user.Save();
return true;
}
private WindowsLiveLogin.User GetWindowsLiveLoginUser(string token)
{
var user = new WindowsLiveLogin(true).ProcessToken(token);
if (user == null)
{
Tracing.FrameworkError(ToString(), "GetPuid", "The Live ID token was not valid or could not be parsed -- No user created");
return null;
}
return user;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI
{
using System;
using System.IO;
using System.Collections;
using NPOI.POIFS.FileSystem;
using NPOI.HPSF;
using System.Collections.Generic;
using NPOI.POIFS.Crypt;
using NPOI.Util;
/// <summary>
/// This holds the common functionality for all POI
/// Document classes.
/// Currently, this relates to Document Information Properties
/// </summary>
/// <remarks>@author Nick Burch</remarks>
[Serializable]
public abstract class POIDocument : ICloseable
{
private static POILogger logger = POILogFactory.GetLogger(typeof(POIDocument));
/** Holds metadata on our document */
protected SummaryInformation sInf;
/** Holds further metadata on our document */
protected DocumentSummaryInformation dsInf;
/** The directory that our document lives in */
protected DirectoryNode directory;
/// <summary>
/// just for test case TestPOIDocumentMain.TestWriteReadProperties
/// </summary>
protected internal void SetDirectoryNode(DirectoryNode directory)
{
this.directory = directory;
}
/** For our own logging use */
//protected POILogger logger;
/* Have the property streams been Read yet? (Only done on-demand) */
protected bool initialized = false;
protected POIDocument(DirectoryNode dir)
{
this.directory = dir;
}
/**
* Constructs from an old-style OPOIFS
*/
protected POIDocument(OPOIFSFileSystem fs)
: this(fs.Root)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="POIDocument"/> class.
/// </summary>
/// <param name="fs">The fs.</param>
public POIDocument(NPOIFSFileSystem fs)
: this(fs.Root)
{
}
/**
* Constructs from the default POIFS
*/
protected POIDocument(POIFSFileSystem fs)
: this(fs.Root)
{
}
/**
* Will create whichever of SummaryInformation
* and DocumentSummaryInformation (HPSF) properties
* are not already part of your document.
* This is normally useful when creating a new
* document from scratch.
* If the information properties are already there,
* then nothing will happen.
*/
public void CreateInformationProperties()
{
if (!initialized) ReadProperties();
if (sInf == null)
{
sInf = PropertySetFactory.CreateSummaryInformation();
}
if (dsInf == null)
{
dsInf = PropertySetFactory.CreateDocumentSummaryInformation();
}
}
// nothing to dispose
//public virtual void Dispose()
//{
//
//}
/// <summary>
/// Fetch the Document Summary Information of the document
/// </summary>
/// <value>The document summary information.</value>
public DocumentSummaryInformation DocumentSummaryInformation
{
get
{
if (!initialized) ReadProperties();
return dsInf;
}
set
{
dsInf = value;
}
}
/// <summary>
/// Fetch the Summary Information of the document
/// </summary>
/// <value>The summary information.</value>
public SummaryInformation SummaryInformation
{
get
{
if (!initialized) ReadProperties();
return sInf;
}
set
{
sInf = value;
}
}
/// <summary>
/// Find, and Create objects for, the standard
/// Documment Information Properties (HPSF).
/// If a given property Set is missing or corrupt,
/// it will remain null;
/// </summary>
protected internal void ReadProperties()
{
PropertySet ps;
// DocumentSummaryInformation
ps = GetPropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
if (ps != null && ps is DocumentSummaryInformation)
{
dsInf = (DocumentSummaryInformation)ps;
}
else if (ps != null)
{
logger.Log(POILogger.WARN, "DocumentSummaryInformation property Set came back with wrong class - ", ps.GetType());
}
else
{
logger.Log(POILogger.WARN, "DocumentSummaryInformation property set came back as null");
}
// SummaryInformation
ps = GetPropertySet(SummaryInformation.DEFAULT_STREAM_NAME);
if (ps is SummaryInformation)
{
sInf = (SummaryInformation)ps;
}
else if (ps != null)
{
logger.Log(POILogger.WARN, "SummaryInformation property Set came back with wrong class - ", ps.GetType());
}
else
{
logger.Log(POILogger.WARN, "SummaryInformation property set came back as null");
}
// Mark the fact that we've now loaded up the properties
initialized = true;
}
/// <summary>
/// For a given named property entry, either return it or null if
/// if it wasn't found
/// </summary>
/// <param name="setName">The property to read</param>
/// <returns>The value of the given property or null if it wasn't found.</returns>
/// <exception cref="IOException">If retrieving properties fails</exception>
protected PropertySet GetPropertySet(string setName)
{
return GetPropertySet(setName, null);
}
/// <summary>
/// For a given named property entry, either return it or null if
/// if it wasn't found
/// </summary>
/// <param name="setName">The property to read</param>
/// <param name="encryptionInfo">the encryption descriptor in case of cryptoAPI encryption</param>
/// <returns>The value of the given property or null if it wasn't found.</returns>
/// <exception cref="IOException">If retrieving properties fails</exception>
protected PropertySet GetPropertySet(string setName, EncryptionInfo encryptionInfo)
{
DirectoryNode dirNode = directory;
NPOIFSFileSystem encPoifs = null;
String step = "getting";
try
{
if (encryptionInfo != null)
{
step = "getting encrypted";
InputStream is1 = encryptionInfo.Decryptor.GetDataStream(directory);
try
{
encPoifs = new NPOIFSFileSystem(is1);
dirNode = encPoifs.Root;
}
finally
{
is1.Close();
}
}
//directory can be null when creating new documents
if (dirNode == null || !dirNode.HasEntry(setName))
{
return null;
}
// Find the entry, and get an input stream for it
step = "getting";
DocumentInputStream dis = dirNode.CreateDocumentInputStream(dirNode.GetEntry(setName));
try
{
// Create the Property Set
step = "creating";
return PropertySetFactory.Create(dis);
}
finally
{
dis.Close();
}
}
catch (Exception e)
{
logger.Log(POILogger.WARN, "Error " + step + " property set with name " + setName, e);
return null;
}
finally
{
if (encPoifs != null)
{
try
{
encPoifs.Close();
}
catch (IOException e)
{
logger.Log(POILogger.WARN, "Error closing encrypted property poifs", e);
}
}
}
}
/**
* Writes out the updated standard Document Information Properties (HPSF)
* into the currently open NPOIFSFileSystem
* TODO Implement in-place update
*
* @throws IOException if an error when writing to the open
* {@link NPOIFSFileSystem} occurs
* TODO throws exception if open from stream not file
*/
protected internal void WriteProperties()
{
ValidateInPlaceWritePossible();
WriteProperties(directory.FileSystem, null);
}
/// <summary>
/// Writes out the standard Documment Information Properties (HPSF)
/// </summary>
/// <param name="outFS">the POIFSFileSystem to Write the properties into</param>
protected internal void WriteProperties(NPOIFSFileSystem outFS)
{
WriteProperties(outFS, null);
}
/// <summary>
/// Writes out the standard Documment Information Properties (HPSF)
/// </summary>
/// <param name="outFS">the POIFSFileSystem to Write the properties into.</param>
/// <param name="writtenEntries">a list of POIFS entries to Add the property names too.</param>
protected internal void WriteProperties(NPOIFSFileSystem outFS, IList writtenEntries)
{
if (sInf != null)
{
WritePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, sInf, outFS);
if (writtenEntries != null)
{
writtenEntries.Add(SummaryInformation.DEFAULT_STREAM_NAME);
}
}
if (dsInf != null)
{
WritePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsInf, outFS);
if (writtenEntries != null)
{
writtenEntries.Add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
}
}
/// <summary>
/// Writes out a given ProperySet
/// </summary>
/// <param name="name">the (POIFS Level) name of the property to Write.</param>
/// <param name="Set">the PropertySet to Write out.</param>
/// <param name="outFS">the POIFSFileSystem to Write the property into.</param>
protected void WritePropertySet(String name, PropertySet Set, NPOIFSFileSystem outFS)
{
try
{
MutablePropertySet mSet = new MutablePropertySet(Set);
using (MemoryStream bOut = new MemoryStream())
{
mSet.Write(bOut);
byte[] data = bOut.ToArray();
using (MemoryStream bIn = new MemoryStream(data))
{
// Create or Update the Property Set stream in the POIFS
outFS.CreateOrUpdateDocument(bIn, name);
}
//logger.Log(POILogger.INFO, "Wrote property Set " + name + " of size " + data.Length);
}
}
catch (WritingNotSupportedException)
{
//logger.log(POILogger.ERROR, "Couldn't Write property Set with name " + name + " as not supported by HPSF yet");
}
}
/**
* Called during a {@link #write()} to ensure that the Document (and
* associated {@link POIFSFileSystem}) was opened in a way compatible
* with an in-place write.
*
* @ if the document was opened suitably
*/
protected void ValidateInPlaceWritePossible()
{
if (directory == null)
{
throw new InvalidOperationException("Newly created Document, cannot save in-place");
}
if (directory.Parent != null)
{
throw new InvalidOperationException("This is not the root Document, cannot save embedded resource in-place");
}
if (directory.FileSystem == null ||
!directory.FileSystem.IsInPlaceWriteable())
{
throw new InvalidOperationException("Opened read-only or via an InputStream, a Writeable File is required");
}
}
/**
* Writes the document out to the currently open {@link File}, via the
* writeable {@link POIFSFileSystem} it was opened from.
*
* <p>This will Assert.Fail (with an {@link InvalidOperationException} if the
* document was opened read-only, opened from an {@link InputStream}
* instead of a File, or if this is not the root document. For those cases,
* you must use {@link #write(OutputStream)} or {@link #write(File)} to
* write to a brand new document.
*
* @ thrown on errors writing to the file
*/
public abstract void Write() ;
/**
* Writes the document out to the specified new {@link File}. If the file
* exists, it will be replaced, otherwise a new one will be created
*
* @param newFile The new File to write to.
*
* @ thrown on errors writing to the file
*/
public abstract void Write(FileInfo newFile) ;
/**
* Writes the document out to the specified output stream. The
* stream is not closed as part of this operation.
*
* Note - if the Document was opened from a {@link File} rather
* than an {@link InputStream}, you <b>must</b> write out using
* {@link #write()} or to a different File. Overwriting the currently
* open file via an OutputStream isn't possible.
*
* If {@code stream} is a {@link java.io.FileOutputStream} on a networked drive
* or has a high cost/latency associated with each written byte,
* consider wrapping the OutputStream in a {@link java.io.BufferedOutputStream}
* to improve write performance, or use {@link #write()} / {@link #write(File)}
* if possible.
*
* @param out The stream to write to.
*
* @ thrown on errors writing to the stream
*/
public abstract void Write(Stream out1);
/**
* Closes the underlying {@link NPOIFSFileSystem} from which
* the document was read, if any. Has no effect on documents
* opened from an InputStream, or newly created ones.
*
* Once {@link #close()} has been called, no further operations
* should be called on the document.
*/
public virtual void Close()
{
if (directory != null) {
if (directory.NFileSystem != null) {
directory.NFileSystem.Close();
directory = null;
}
}
}
public DirectoryNode Directory
{
get { return directory; }
}
}
}
| |
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Draw bar and stacked bar charts in 2D or 3D.
/// </summary>
public class BarChart {
/// <summary>
/// The data driving the chart.
/// </summary>
public List <float[]> data;
/// <summary>
/// The labels of the data items.
/// </summary>
public List <string> labels;
/// <summary>
/// The distance between each bar.
/// </summary>
public float barSpacer = 0.5f;
/// <summary>
/// The x border.
/// </summary>
public float xBorder = 30;
/// <summary>
/// The y border.
/// </summary>
public float yBorder = 20;
/// <summary>
/// The format string for the values.
/// </summary>
public string formatString = "{0:0}";
/// <summary>
/// The format string for the axis values.
/// </summary>
public string axisFormatString = "{0:0}";
/// <summary>
/// The colors to draw the bar in. Colors will cycle if there aren't enough to draw each stack. The first
/// color will be used by a single bar chart.
/// </summary>
public List<Color> colors = new List<Color>(){Colors.PastelGreen, Colors.PastelYellow, Colors.PastelBlue};
/// <summary>
/// The color of the selected bar.
/// </summary>
public Color selectedColor = Colors.PastelOrange;
/// <summary>
/// The depth of the bars, larger than zero will make this a 3D bar graph.
/// </summary>
public float depth = 0.0f;
/// <summary>
/// The value view mode. Do we see the values, NEVER, ALWAYS or only ON_SELECT.
/// </summary>
public ViewMode valueViewMode = ViewMode.ON_SELECT;
/// <summary>
/// The label view mode. Do we see the labels, NEVER, ALWAYS or only ON_SELECT.
/// </summary>
public ViewMode labelViewMode = ViewMode.ALWAYS;
/// <summary>
/// How many horizontal grid lines to draw.
/// </summary>
public int gridLines = 4;
/// <summary>
/// What level should values on the axis be rounded too?
/// </summary>
public float axisRounding = 10f;
/// <summary>
/// The ClickReponder that recieves click events.
/// </summary>
public ClickResponder clickResponder;
/// <summary>
/// The color of the axis.
/// </summary>
public Color axisColor = Color.white;
/// <summary>
/// The color of the label and value font.
/// </summary>
public Color fontColor = Color.white;
/// <summary>
/// Additional GUI style drawn in the background. Use this to add a backgroudn image or background box.
/// </summary>
public GUIStyle boxStyle;
private EditorWindow window;
private Editor editor;
private float windowHeight;
/// <summary>
/// Initializes a new instance of the <see cref="BarChart"/> class from an Editor (Inspector).
/// </summary>
/// <param name='editor'>
/// Editor.
/// </param>
/// <param name='windowHeight'>
/// Window height.
/// </param>
public BarChart(Editor editor, float windowHeight){
this.editor = editor;
this.windowHeight = windowHeight;
data = new List<float[]>();
labels = new List<string>();
}
/// <summary>
/// Initializes a new instance of the <see cref="BarChart"/> class from an EditorWindow.
/// </summary>
/// <param name='window'>
/// Window.
/// </param>
/// <param name='windowHeight'>
/// Window height.
/// </param>
public BarChart(EditorWindow window, float windowHeight){
this.window = window;
this.windowHeight = windowHeight;
data = new List<float[]>();
labels = new List<string>();
}
/// <summary>
/// Draws the chart.
/// </summary>
public void DrawChart() {
Rect rect = GUILayoutUtility.GetRect(Screen.width, windowHeight);
float barTop = rect.y + yBorder;
float barWidth = (float) (Screen.width - (xBorder * 2))/ ((data.Count * 1.5f) + 1);
float barFloor = rect.y + rect.height - yBorder;
float dataMax = 0.0f;
for (int i = 0; i < data.Count; i++) {
if (data[i].Sum() > dataMax) {
dataMax = data[i].Sum();
}
}
Rect currentRect;
// Box/border
if (boxStyle != null) {
GUI.Box(new Rect(rect.x + boxStyle.margin.left, rect.y + boxStyle.margin.top,
rect.width - (boxStyle.margin.right + boxStyle.margin.left) ,
rect.height - (boxStyle.margin.top + boxStyle.margin.bottom)),"", boxStyle);
}
// Clean up variables
if (dataMax % axisRounding != 0){
dataMax = dataMax + axisRounding - (dataMax % axisRounding);
}
// Text to Left
GUIStyle labelTextStyle = new GUIStyle();
labelTextStyle.alignment = TextAnchor.UpperRight;
labelTextStyle.normal.textColor = fontColor;
// Draw grid lines
if (gridLines > 0) {
Handles.color = Color.grey;
float lineSpacing = (barFloor - barTop) / (gridLines + 1);
for (int i = 0; i <= gridLines; i++) {
if (i > 0) Handles.DrawLine(new Vector2(xBorder, barTop + (lineSpacing * i)), new Vector2(Screen.width - xBorder, barTop + (lineSpacing * i)));
GUI.Label(new Rect(0, barTop + (lineSpacing * i) - 8, xBorder - 2, 50), string.Format(axisFormatString, (dataMax * (1 - ((lineSpacing * i) / (barFloor - barTop))))) , labelTextStyle);
}
Handles.color = Color.white;
}
// Draw bars
GUIStyle centeredStyle = new GUIStyle();
centeredStyle.alignment = TextAnchor.UpperCenter;
centeredStyle.normal.textColor = fontColor;
for (int i = 0; i < data.Count; i++) {
float currentHeight = 0.0f;
int c = 0;
for (int j = 0; j < data[i].Length; j++) {
float height = (barFloor - barTop) * (data[i][j] / dataMax);
currentRect = new Rect(((i * 1.5f) + 0.5f) * barWidth + xBorder , barFloor - currentHeight - height, barWidth, height);
if (height > 0) {
if (currentRect.Contains(Event.current.mousePosition)) {
//GUI.color = selectedColor;
Draw3DBar(new Vector3(((i * 1.5f) + 0.5f) * barWidth + xBorder, barFloor - currentHeight, 0.0f), barWidth, height, depth, selectedColor, Color.black);
// Draw value
Rect labelRect = currentRect;
if (valueViewMode == ViewMode.ON_SELECT || valueViewMode == ViewMode.ALWAYS) {
if (labelRect.height < 16) { labelRect.height = 16; labelRect.y -= 16 + depth; }
GUI.Label(labelRect, string.Format(formatString, data[i][j]), centeredStyle);
}
// Draw label
if (j == 0) {
if (labelViewMode == ViewMode.ON_SELECT && i < labels.Count) {
labelRect.height = 16; labelRect.y -= 16 + depth;
GUI.Label(labelRect, labels[i], centeredStyle);
}
}
// Listen for click
if (clickResponder != null && Event.current.button == 0 && Event.current.isMouse && Event.current.type == EventType.MouseDown) {
clickResponder.Click(this, labels[i], data[i][j]);
}
if (window != null) window.Repaint();
if (editor != null) editor.Repaint();
} else {
Draw3DBar(new Vector3(((i * 1.5f) + 0.5f) * barWidth + xBorder, barFloor - currentHeight, 0.0f), barWidth, height, depth, colors[c++], Color.black);
if (valueViewMode == ViewMode.ALWAYS) {
if (currentRect.height < 16) { currentRect.height = 16; currentRect.y -= 16 + depth; }
GUI.Label(currentRect, string.Format(formatString, data[i][j]), centeredStyle);
}
}
}
if (labelViewMode == ViewMode.ALWAYS && i < labels.Count && j == 0) {
Rect labelRect = new Rect(currentRect.x, currentRect.y + currentRect.height + 1, currentRect.width, 16);
GUI.Label(labelRect, labels[i], centeredStyle);
}
currentHeight += height;
if (c > colors.Count - 1) c = 0;
}
GUI.color = Color.white;
}
// Draw Axis
Handles.color = axisColor;
Handles.DrawLine(new Vector2(xBorder, barTop), new Vector2(xBorder, barFloor));
Handles.DrawLine(new Vector2(xBorder, barFloor), new Vector2(Screen.width - xBorder, barFloor));
Handles.color = Color.white;
}
private void Draw3DBar(Vector3 offset, float width, float height, float depth, Color color, Color outlineColor) {
List <Vector3> verts = new List<Vector3>();
verts.Add(new Vector3(offset.x, offset.y,0));
verts.Add(new Vector3(offset.x + width, offset.y,0));
verts.Add(new Vector3(offset.x + width, offset.y - height,0));
verts.Add(new Vector3(offset.x, offset.y - height,0));
Handles.DrawSolidRectangleWithOutline(verts.ToArray(), color, outlineColor);
if (depth > 0) {
verts.Clear();
verts.Add(new Vector3(offset.x + width, offset.y - height,0));
verts.Add(new Vector3(offset.x, offset.y - height,0));
verts.Add(new Vector3(offset.x + depth, offset.y - height - depth,0));
verts.Add(new Vector3(offset.x + width + depth, offset.y - height - depth,0));
Handles.DrawSolidRectangleWithOutline(verts.ToArray(), new Color(color.r * 0.8f, color.g * 0.8f, color.b * 0.8f), outlineColor);
verts.Clear();
verts.Add(new Vector3(offset.x + width, offset.y,0));
verts.Add(new Vector3(offset.x + width, offset.y - height,0));
verts.Add(new Vector3(offset.x + width + depth, offset.y - height - depth,0));
verts.Add(new Vector3(offset.x + width + depth, offset.y - depth,0));
Handles.DrawSolidRectangleWithOutline(verts.ToArray(), new Color(color.r * 0.6f, color.g * 0.6f, color.b * 0.6f), outlineColor);
}
}
/// <summary>
/// Convenience method to set the data to a list of floats.
/// </summary>
/// <param name='data'>
/// Chart data as a list of floats.
/// </param>
public void SetData(List<float> data) {
this.data = new List<float[]>();
foreach (float d in data){
this.data.Add(new float[]{d});
}
}
}
#endif
| |
/************************************************************************************
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.Runtime.InteropServices;
using UnityEngine;
/// <summary>
/// OVRGamepadController is an interface class to a gamepad controller.
/// </summary>
public class OVRGamepadController : MonoBehaviour
{
//-------------------------
// Input enums
public enum Axis
{
None = -1,
LeftXAxis = 0,
LeftYAxis,
RightXAxis,
RightYAxis,
LeftTrigger,
RightTrigger,
Max,
};
public enum Button
{
None = -1,
A = 0,
B,
X,
Y,
Up,
Down,
LeftShoulder,
RightShoulder,
Start,
Back,
LStick,
RStick,
L1,
R1,
Max
};
public static string[] DefaultAxisNames = new string[(int)Axis.Max]
{
"Left_X_Axis",
"Left_Y_Axis",
"Right_X_Axis",
"Right_Y_Axis",
"LeftTrigger",
"RightTrigger",
};
public static string[] DefaultButtonNames = new string[(int)Button.Max]
{
"Button A",
"Button B",
"Button X",
"Button Y",
"Up",
"Down",
"Left Shoulder",
"Right Shoulder",
"Start",
"Back",
"LStick",
"RStick",
"LeftShoulder",
"RightShoulder",
};
public static int[] DefaultButtonIds = new int[(int)Button.Max]
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
};
public static string[] AxisNames = null;
public static string[] ButtonNames = null;
static OVRGamepadController()
{
SetAxisNames(DefaultAxisNames);
SetButtonNames(DefaultButtonNames);
}
public static void SetAxisNames(string[] axisNames)
{
AxisNames = axisNames;
}
public static void SetButtonNames(string[] buttonNames)
{
ButtonNames = buttonNames;
}
public delegate float ReadAxisDelegate(Axis axis);
public delegate bool ReadButtonDelegate(Button button);
public static ReadAxisDelegate ReadAxis = DefaultReadAxis;
public static ReadButtonDelegate ReadButton = DefaultReadButton;
#if (!UNITY_ANDROID || UNITY_EDITOR)
private static bool GPC_Available = false;
//-------------------------
// Public access to plugin functions
/// <summary>
/// GPC_Initialize.
/// </summary>
/// <returns><c>true</c>, if c_ initialize was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Initialize()
{
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Initialize();
}
/// <summary>
/// GPC_Destroy
/// </summary>
/// <returns><c>true</c>, if c_ destroy was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Destroy()
{
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Destroy();
}
/// <summary>
/// GPC_Update
/// </summary>
/// <returns><c>true</c>, if c_ update was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Update()
{
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Update();
}
#endif
/// <summary>
/// GPC_GetAxis
/// The default delegate for retrieving axis info.
/// </summary>
/// <returns>The current value of the axis.</returns>
/// <param name="axis">Axis.</param>
public static float DefaultReadAxis(Axis axis)
{
#if UNITY_ANDROID && !UNITY_EDITOR
return Input.GetAxis(AxisNames[(int)axis]);
#else
return OVR_GamepadController_GetAxis((int)axis);
#endif
}
public static float GPC_GetAxis(Axis axis)
{
if (ReadAxis == null)
return 0f;
return ReadAxis(axis);
}
public static void SetReadAxisDelegate(ReadAxisDelegate del)
{
ReadAxis = del;
}
/// <summary>
/// GPC_GetButton
/// </summary>
/// <returns><c>true</c>, if c_ get button was GPed, <c>false</c> otherwise.</returns>
/// <param name="button">Button.</param>
public static bool DefaultReadButton(Button button)
{
#if UNITY_ANDROID && !UNITY_EDITOR
return Input.GetButton(ButtonNames[(int)button]);
#else
return OVR_GamepadController_GetButton((int)button);
#endif
}
public static bool GPC_GetButton(Button button)
{
if (ReadButton == null)
return false;
return ReadButton(button);
}
public static void SetReadButtonDelegate(ReadButtonDelegate del)
{
ReadButton = del;
}
/// <summary>
/// GPC_IsAvailable
/// </summary>
/// <returns><c>true</c>, if c_ is available was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_IsAvailable()
{
#if !UNITY_ANDROID || UNITY_EDITOR
return GPC_Available;
#else
return true;
#endif
}
/// <summary>
/// GPC_Test
/// </summary>
void GPC_Test()
{
// Axis test
Debug.Log(string.Format("LT:{0:F3} RT:{1:F3} LX:{2:F3} LY:{3:F3} RX:{4:F3} RY:{5:F3}",
GPC_GetAxis(Axis.LeftTrigger), GPC_GetAxis(Axis.RightTrigger),
GPC_GetAxis(Axis.LeftXAxis), GPC_GetAxis(Axis.LeftYAxis),
GPC_GetAxis(Axis.RightXAxis), GPC_GetAxis(Axis.RightYAxis)));
// Button test
Debug.Log(string.Format("A:{0} B:{1} X:{2} Y:{3} U:{4} D:{5} L:{6} R:{7} SRT:{8} BK:{9} LS:{10} RS:{11} L1{12} R1{13}",
GPC_GetButton(Button.A), GPC_GetButton(Button.B),
GPC_GetButton(Button.X), GPC_GetButton(Button.Y),
GPC_GetButton(Button.Up), GPC_GetButton(Button.Down),
GPC_GetButton(Button.LeftShoulder), GPC_GetButton(Button.RightShoulder),
GPC_GetButton(Button.Start), GPC_GetButton(Button.Back),
GPC_GetButton(Button.LStick), GPC_GetButton(Button.RStick),
GPC_GetButton(Button.L1), GPC_GetButton(Button.R1)));
}
#if !UNITY_ANDROID || UNITY_EDITOR
void Start()
{
GPC_Available = GPC_Initialize();
}
void Update()
{
GPC_Available = GPC_Update();
}
void OnDestroy()
{
GPC_Destroy();
GPC_Available = false;
}
public const string LibOVR = "OculusPlugin";
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Initialize();
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Destroy();
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Update();
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
public static extern float OVR_GamepadController_GetAxis(int axis);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_GetButton(int button);
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
using System.Diagnostics.SymbolStore;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.Reflection.Emit
{
public sealed class MethodBuilder : MethodInfo
{
#region Private Data Members
// Identity
internal string m_strName; // The name of the method
private MethodToken m_tkMethod; // The token of this method
private ModuleBuilder m_module;
internal TypeBuilder m_containingType;
// IL
private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
internal LocalSymInfo? m_localSymInfo; // keep track debugging local information
internal ILGenerator? m_ilGenerator; // Null if not used.
private byte[]? m_ubBody; // The IL for the method
private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
private bool m_bIsGlobalMethod;
private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not.
// Attributes
private MethodAttributes m_iAttributes;
private CallingConventions m_callingConvention;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
private SignatureHelper? m_signature;
internal Type[]? m_parameterTypes;
private Type m_returnType;
private Type[]? m_returnTypeRequiredCustomModifiers;
private Type[]? m_returnTypeOptionalCustomModifiers;
private Type[][]? m_parameterTypeRequiredCustomModifiers;
private Type[][]? m_parameterTypeOptionalCustomModifiers;
// Generics
private GenericTypeParameterBuilder[]? m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
if (mod == null)
throw new ArgumentNullException(nameof(mod));
if (parameterTypes != null)
{
foreach (Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException(nameof(parameterTypes));
}
}
m_strName = name;
m_module = mod;
m_containingType = type;
m_returnType = returnType ?? typeof(void);
if ((attributes & MethodAttributes.Static) == 0)
{
// turn on the has this calling convention
callingConvention |= CallingConventions.HasThis;
}
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
throw new ArgumentException(SR.Arg_NoStaticVirtual);
}
#if !FEATURE_DEFAULT_INTERFACES
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
{
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
(MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
}
}
#endif
m_callingConvention = callingConvention;
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
else
{
m_parameterTypes = null;
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
m_bIsBaked = false;
m_fInitLocals = true;
m_localSymInfo = new LocalSymInfo();
m_ubBody = null;
m_ilGenerator = null;
// Default is managed IL. Manged IL has bit flag 0x0020 set off
m_dwMethodImplFlags = MethodImplAttributes.IL;
}
#endregion
#region Internal Members
internal void CheckContext(params Type[]?[]? typess)
{
m_module.CheckContext(typess);
}
internal void CheckContext(params Type?[]? types)
{
m_module.CheckContext(types);
}
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
if (il == null)
{
throw new ArgumentNullException(nameof(il));
}
__ExceptionInfo[] excp;
int counter = 0;
int[] filterAddrs;
int[] catchAddrs;
int[] catchEndAddrs;
Type[] catchClass;
int[] type;
int numCatch;
int start, end;
ModuleBuilder dynMod = (ModuleBuilder)m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
{
// you don't need to call DefineBody when you get your ILGenerator
// through MethodBuilder::GetILGenerator.
//
throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
}
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
}
m_ubBody = il.BakeByteArray();
m_mdMethodFixups = il.GetTokenFixups();
// Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions()!;
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
m_exceptions = new ExceptionHandler[numExceptions];
for (int i = 0; i < excp.Length; i++)
{
filterAddrs = excp[i].GetFilterAddresses();
catchAddrs = excp[i].GetCatchAddresses();
catchEndAddrs = excp[i].GetCatchEndAddresses();
catchClass = excp[i].GetCatchClass();
numCatch = excp[i].GetNumberOfCatches();
start = excp[i].GetStartAddress();
end = excp[i].GetEndAddress();
type = excp[i].GetExceptionTypes();
for (int j = 0; j < numCatch; j++)
{
int tkExceptionClass = 0;
if (catchClass[j] != null)
{
tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
}
switch (type[j])
{
case __ExceptionInfo.None:
case __ExceptionInfo.Fault:
case __ExceptionInfo.Filter:
m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
case __ExceptionInfo.Finally:
m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
}
}
}
}
m_bIsBaked = true;
if (dynMod.GetSymWriter() != null)
{
// set the debugging information such as scope and line number
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter()!;
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
// call OpenScope because OpenMethod no longer implicitly creating
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
if (m_symCustomAttrs != null)
{
foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter()!.SetSymAttribute(
new SymbolToken(MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
}
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
symWriter.CloseScope(il.ILOffset);
symWriter.CloseMethod();
}
}
// This is only called from TypeBuilder.CreateType after the method has been created
internal void ReleaseBakedStructures()
{
if (!m_bIsBaked)
{
// We don't need to do anything here if we didn't baked the method body
return;
}
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes() => m_parameterTypes ??= Array.Empty<Type>();
internal static Type? GetMethodBaseReturnType(MethodBase? method)
{
if (method is MethodInfo mi)
{
return mi.ReturnType;
}
else if (method is ConstructorInfo ci)
{
return ci.GetReturnType();
}
else
{
Debug.Fail("We should never get here!");
return null;
}
}
internal void SetToken(MethodToken token)
{
m_tkMethod = token;
}
internal byte[]? GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
internal int[]? GetTokenFixups()
{
return m_mdMethodFixups;
}
internal SignatureHelper GetMethodSignature()
{
m_parameterTypes ??= Array.Empty<Type>();
m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
return m_signature;
}
// Returns a buffer whose initial signatureLength bytes contain encoded local signature.
internal byte[] GetLocalSignature(out int signatureLength)
{
if (m_localSignature != null)
{
signatureLength = m_localSignature.Length;
return m_localSignature;
}
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
{
// If user is using ILGenerator::DeclareLocal, then get local signaturefrom there.
return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
}
}
return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
}
internal int GetMaxStack()
{
if (m_ilGenerator != null)
{
return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
}
else
{
// this is the case when client provide an array of IL byte stream rather than going through ILGenerator.
return m_maxStack;
}
}
internal ExceptionHandler[]? GetExceptionHandlers()
{
return m_exceptions;
}
internal int ExceptionHandlerCount => m_exceptions != null ? m_exceptions.Length : 0;
internal static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp)
{
int num = 0;
if (excp == null)
{
return 0;
}
for (int i = 0; i < excp.Length; i++)
{
num += excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
{
return m_containingType != null && m_containingType.IsCreated();
}
internal TypeBuilder GetTypeBuilder()
{
return m_containingType;
}
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
#endregion
#region Object Overrides
public override bool Equals(object? obj)
{
if (!(obj is MethodBuilder))
{
return false;
}
if (!this.m_strName.Equals(((MethodBuilder)obj).m_strName))
{
return false;
}
if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes))
{
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
if (thatSig.Equals(GetMethodSignature()))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.m_strName.GetHashCode();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(1000);
sb.Append("Name: ").Append(m_strName).AppendLine(" ");
sb.Append("Attributes: ").Append((int)m_iAttributes).AppendLine();
sb.Append("Method Signature: ").Append(GetMethodSignature()).AppendLine();
sb.AppendLine();
return sb.ToString();
}
#endregion
#region MemberInfo Overrides
public override string Name => m_strName;
internal int MetadataTokenInternal => GetToken().Token;
public override Module Module => m_containingType.Module;
public override Type? DeclaringType
{
get
{
if (m_containingType.m_isHiddenGlobalType)
return null;
return m_containingType;
}
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder();
public override Type? ReflectedType => DeclaringType;
#endregion
#region MethodBase Overrides
public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_dwMethodImplFlags;
}
public override MethodAttributes Attributes => m_iAttributes;
public override CallingConventions CallingConvention => m_callingConvention;
public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule);
public override bool IsSecurityCritical => true;
public override bool IsSecuritySafeCritical => false;
public override bool IsSecurityTransparent => false;
#endregion
#region MethodInfo Overrides
public override MethodInfo GetBaseDefinition()
{
return this;
}
public override Type ReturnType => m_returnType;
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.GetParameters();
}
public override ParameterInfo ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.ReturnParameter;
}
}
#endregion
#region ICustomAttributeProvider Implementation
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
#endregion
#region Generic Members
public override bool IsGenericMethodDefinition => m_bIsGenMethDef;
public override bool ContainsGenericParameters => throw new NotSupportedException();
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod => m_inst != null;
public override Type[] GetGenericArguments() => m_inst ?? Array.Empty<Type>();
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
if (m_inst != null)
throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet);
for (int i = 0; i < names.Length; i++)
if (names[i] == null)
throw new ArgumentNullException(nameof(names));
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked);
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
for (int i = 0; i < names.Length; i++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); }
#endregion
#region Public Members
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
// we only "tokenize" a method when requested. But the order in which the methods are tokenized
// didn't change: the same order the MethodBuilders are constructed. The recursion introduced
// will overflow the stack when there are many methods on the same type (10000 in my experiment).
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
// I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
MethodBuilder? currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
// We need to lock here to prevent a method from being "tokenized" twice.
// We don't need to synchronize this with Type.DefineMethod because it only appends newly
// constructed MethodBuilders to the end of m_listMethods
lock (m_containingType.m_listMethods)
{
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
// If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller
// than the index of the current method.
for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i)
{
currentMethod = m_containingType.m_listMethods[i];
currentToken = currentMethod.GetTokenNoLock();
if (currentMethod == this)
break;
}
m_containingType.m_lastTokenizedMethod = i;
}
Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
Debug.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
private MethodToken GetTokenNoLock()
{
Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
ModuleBuilder module = m_module;
int token = TypeBuilder.DefineMethod(JitHelpers.GetQCallModuleOnStack(ref module), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);
m_tkMethod = new MethodToken(token);
if (m_inst != null)
foreach (GenericTypeParameterBuilder tb in m_inst)
if (!tb.m_type.IsCreated()) tb.m_type.CreateType();
TypeBuilder.SetMethodImpl(JitHelpers.GetQCallModuleOnStack(ref module), token, m_dwMethodImplFlags);
return m_tkMethod;
}
public void SetParameters(params Type[] parameterTypes)
{
CheckContext(parameterTypes);
SetSignature(null, null, null, parameterTypes, null, null);
}
public void SetReturnType(Type? returnType)
{
CheckContext(returnType);
SetSignature(returnType, null, null, null, null, null);
}
public void SetSignature(
Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
if (m_tkMethod.Token != 0)
return;
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
ThrowIfGeneric();
if (returnType != null)
{
m_returnType = returnType;
}
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
attributes &= ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
}
private List<SymCustomAttr>? m_symCustomAttrs;
private struct SymCustomAttr
{
public string m_name;
public byte[] m_data;
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
m_dwMethodImplFlags = attributes;
m_canBeRuntimeImpl = true;
ModuleBuilder module = m_module;
TypeBuilder.SetMethodImpl(JitHelpers.GetQCallModuleOnStack(ref module), MetadataTokenInternal, attributes);
}
public ILGenerator GetILGenerator()
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
return m_ilGenerator ??= new ILGenerator(this);
}
public ILGenerator GetILGenerator(int size)
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
return m_ilGenerator ??= new ILGenerator(this, size);
}
private void ThrowIfShouldNotHaveBody()
{
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
m_isDllImport)
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody);
}
}
public bool InitLocals
{
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
get { ThrowIfGeneric(); return m_fInitLocals; }
set { ThrowIfGeneric(); m_fInitLocals = value; }
}
public Module GetModule()
{
return GetModuleBuilder();
}
public string Signature => GetMethodSignature().ToString();
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con is null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute is null)
throw new ArgumentNullException(nameof(binaryAttribute));
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal,
((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
if (IsKnownCA(con))
ParseCA(con);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con);
}
// this method should return true for any and every ca that requires more work
// than just setting the ca
private static bool IsKnownCA(ConstructorInfo con)
{
Type? caType = con.DeclaringType;
return caType == typeof(MethodImplAttribute) || caType == typeof(DllImportAttribute);
}
private void ParseCA(ConstructorInfo con)
{
Type? caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
// for now we simply set a flag that relaxes the check when saving and
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
else if (caType == typeof(DllImportAttribute))
{
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
}
internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
#endregion
}
internal class LocalSymInfo
{
// This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
internal string[] m_strName = null!; // All these arrys initialized in helper method
internal byte[][] m_ubSignature = null!;
internal int[] m_iLocalSlot = null!;
internal int[] m_iStartOffset = null!;
internal int[] m_iEndOffset = null!;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
internal string[] m_namespace = null!;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
#region Constructor
internal LocalSymInfo()
{
// initialize data variables
m_iLocalSymCount = 0;
m_iNameSpaceCount = 0;
}
#endregion
#region Private Members
private void EnsureCapacityNamespace()
{
if (m_iNameSpaceCount == 0)
{
m_namespace = new string[InitialSize];
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
string[] strTemp = new string[checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount);
m_namespace = strTemp;
}
}
private void EnsureCapacity()
{
if (m_iLocalSymCount == 0)
{
// First time. Allocate the arrays.
m_strName = new string[InitialSize];
m_ubSignature = new byte[InitialSize][];
m_iLocalSlot = new int[InitialSize];
m_iStartOffset = new int[InitialSize];
m_iEndOffset = new int[InitialSize];
}
else if (m_iLocalSymCount == m_strName.Length)
{
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
int[] temp = new int[newSize];
Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount);
m_iLocalSlot = temp;
temp = new int[newSize];
Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount);
m_iStartOffset = temp;
temp = new int[newSize];
Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount);
m_iEndOffset = temp;
string[] strTemp = new string[newSize];
Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount);
m_ubSignature = ubTemp;
}
}
#endregion
#region Internal Members
internal void AddLocalSymInfo(string strName, byte[] signature, int slot, int startOffset, int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
m_iStartOffset[m_iLocalSymCount] = startOffset;
m_iEndOffset[m_iLocalSymCount] = endOffset;
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
checked { m_iLocalSymCount++; }
}
internal void AddUsingNamespace(string strNamespace)
{
EnsureCapacityNamespace();
m_namespace[m_iNameSpaceCount] = strNamespace;
checked { m_iNameSpaceCount++; }
}
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
for (i = 0; i < m_iLocalSymCount; i++)
{
symWriter.DefineLocalVariable(
m_strName[i],
FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
0, // addr2 is not used yet
0, // addr3 is not used
m_iStartOffset[i],
m_iEndOffset[i]);
}
for (i = 0; i < m_iNameSpaceCount; i++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
}
#endregion
}
/// <summary>
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
internal readonly int m_filterOffset;
internal readonly int m_handlerStartOffset;
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
#region Constructors
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
Debug.Assert(tryStartOffset >= 0);
Debug.Assert(tryEndOffset >= 0);
Debug.Assert(filterOffset >= 0);
Debug.Assert(handlerStartOffset >= 0);
Debug.Assert(handlerEndOffset >= 0);
Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerStartOffset;
m_handlerEndOffset = handlerEndOffset;
m_kind = (ExceptionHandlingClauseOptions)kind;
m_exceptionClass = exceptionTypeToken;
}
private static bool IsValidKind(ExceptionHandlingClauseOptions kind)
{
switch (kind)
{
case ExceptionHandlingClauseOptions.Clause:
case ExceptionHandlingClauseOptions.Filter:
case ExceptionHandlingClauseOptions.Finally:
case ExceptionHandlingClauseOptions.Fault:
return true;
default:
return false;
}
}
#endregion
#region Equality
public override int GetHashCode()
{
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
public override bool Equals(object? obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
public bool Equals(ExceptionHandler other)
{
return
other.m_exceptionClass == m_exceptionClass &&
other.m_tryStartOffset == m_tryStartOffset &&
other.m_tryEndOffset == m_tryEndOffset &&
other.m_filterOffset == m_filterOffset &&
other.m_handlerStartOffset == m_handlerStartOffset &&
other.m_handlerEndOffset == m_handlerEndOffset &&
other.m_kind == m_kind;
}
public static bool operator ==(ExceptionHandler left, ExceptionHandler right) => left.Equals(right);
public static bool operator !=(ExceptionHandler left, ExceptionHandler right) => !left.Equals(right);
#endregion
}
}
| |
using System;
using Avalonia.Utilities;
using Avalonia.VisualTree;
namespace Avalonia.Layout
{
/// <summary>
/// Provides helper methods needed for layout.
/// </summary>
public static class LayoutHelper
{
/// <summary>
/// Epsilon value used for certain layout calculations.
/// Based on the value in WPF LayoutDoubleUtil.
/// </summary>
public static double LayoutEpsilon { get; } = 0.00000153;
/// <summary>
/// Calculates a control's size based on its <see cref="ILayoutable.Width"/>,
/// <see cref="ILayoutable.Height"/>, <see cref="ILayoutable.MinWidth"/>,
/// <see cref="ILayoutable.MaxWidth"/>, <see cref="ILayoutable.MinHeight"/> and
/// <see cref="ILayoutable.MaxHeight"/>.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="constraints">The space available for the control.</param>
/// <returns>The control's size.</returns>
public static Size ApplyLayoutConstraints(ILayoutable control, Size constraints)
{
var minmax = new MinMax(control);
return new Size(
MathUtilities.Clamp(constraints.Width, minmax.MinWidth, minmax.MaxWidth),
MathUtilities.Clamp(constraints.Height, minmax.MinHeight, minmax.MaxHeight));
}
public static Size MeasureChild(ILayoutable control, Size availableSize, Thickness padding,
Thickness borderThickness)
{
return MeasureChild(control, availableSize, padding + borderThickness);
}
public static Size MeasureChild(ILayoutable control, Size availableSize, Thickness padding)
{
if (control != null)
{
control.Measure(availableSize.Deflate(padding));
return control.DesiredSize.Inflate(padding);
}
return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top);
}
public static Size ArrangeChild(ILayoutable child, Size availableSize, Thickness padding, Thickness borderThickness)
{
return ArrangeChild(child, availableSize, padding + borderThickness);
}
public static Size ArrangeChild(ILayoutable child, Size availableSize, Thickness padding)
{
child?.Arrange(new Rect(availableSize).Deflate(padding));
return availableSize;
}
/// <summary>
/// Invalidates measure for given control and all visual children recursively.
/// </summary>
public static void InvalidateSelfAndChildrenMeasure(ILayoutable control)
{
void InnerInvalidateMeasure(IVisual target)
{
if (target is ILayoutable targetLayoutable)
{
targetLayoutable.InvalidateMeasure();
}
var visualChildren = target.VisualChildren;
var visualChildrenCount = visualChildren.Count;
for (int i = 0; i < visualChildrenCount; i++)
{
IVisual child = visualChildren[i];
InnerInvalidateMeasure(child);
}
}
InnerInvalidateMeasure(control);
}
/// <summary>
/// Obtains layout scale of the given control.
/// </summary>
/// <param name="control">The control.</param>
/// <exception cref="Exception">Thrown when control has no root or returned layout scaling is invalid.</exception>
public static double GetLayoutScale(ILayoutable control)
{
var visualRoot = control.VisualRoot;
var result = (visualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0;
if (result == 0 || double.IsNaN(result) || double.IsInfinity(result))
{
throw new Exception($"Invalid LayoutScaling returned from {visualRoot!.GetType()}");
}
return result;
}
/// <summary>
/// Rounds a size to integer values for layout purposes, compensating for high DPI screen
/// coordinates.
/// </summary>
/// <param name="size">Input size.</param>
/// <param name="dpiScaleX">DPI along x-dimension.</param>
/// <param name="dpiScaleY">DPI along y-dimension.</param>
/// <returns>Value of size that will be rounded under screen DPI.</returns>
/// <remarks>
/// This is a layout helper method. It takes DPI into account and also does not return
/// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper
/// associated with the UseLayoutRounding property and should not be used as a general rounding
/// utility.
/// </remarks>
public static Size RoundLayoutSize(Size size, double dpiScaleX, double dpiScaleY)
{
return new Size(RoundLayoutValue(size.Width, dpiScaleX), RoundLayoutValue(size.Height, dpiScaleY));
}
/// <summary>
/// Calculates the value to be used for layout rounding at high DPI.
/// </summary>
/// <param name="value">Input value to be rounded.</param>
/// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param>
/// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns>
/// <remarks>
/// This is a layout helper method. It takes DPI into account and also does not return
/// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper
/// associated with the UseLayoutRounding property and should not be used as a general rounding
/// utility.
/// </remarks>
public static double RoundLayoutValue(double value, double dpiScale)
{
double newValue;
// If DPI == 1, don't use DPI-aware rounding.
if (!MathUtilities.IsOne(dpiScale))
{
newValue = Math.Round(value * dpiScale) / dpiScale;
// If rounding produces a value unacceptable to layout (NaN, Infinity or MaxValue),
// use the original value.
if (double.IsNaN(newValue) ||
double.IsInfinity(newValue) ||
MathUtilities.AreClose(newValue, double.MaxValue))
{
newValue = value;
}
}
else
{
newValue = Math.Round(value);
}
return newValue;
}
/// <summary>
/// Calculates the min and max height for a control. Ported from WPF.
/// </summary>
private readonly struct MinMax
{
public MinMax(ILayoutable e)
{
MaxHeight = e.MaxHeight;
MinHeight = e.MinHeight;
double l = e.Height;
double height = (double.IsNaN(l) ? double.PositiveInfinity : l);
MaxHeight = Math.Max(Math.Min(height, MaxHeight), MinHeight);
height = (double.IsNaN(l) ? 0 : l);
MinHeight = Math.Max(Math.Min(MaxHeight, height), MinHeight);
MaxWidth = e.MaxWidth;
MinWidth = e.MinWidth;
l = e.Width;
double width = (double.IsNaN(l) ? double.PositiveInfinity : l);
MaxWidth = Math.Max(Math.Min(width, MaxWidth), MinWidth);
width = (double.IsNaN(l) ? 0 : l);
MinWidth = Math.Max(Math.Min(MaxWidth, width), MinWidth);
}
public double MinWidth { get; }
public double MaxWidth { get; }
public double MinHeight { get; }
public double MaxHeight { get; }
}
}
}
| |
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 Honey.Web.Areas.HelpPage.Models;
namespace Honey.Web.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);
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive.Linq;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Controls.Presenters
{
public class TextPresenter : TextBlock
{
public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
private readonly DispatcherTimer _caretTimer;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _caretBlink;
private IBrush _highlightBrush;
public TextPresenter()
{
_caretTimer = new DispatcherTimer();
_caretTimer.Interval = TimeSpan.FromMilliseconds(500);
_caretTimer.Tick += CaretTimerTick;
Observable.Merge(
this.GetObservable(SelectionStartProperty),
this.GetObservable(SelectionEndProperty))
.Subscribe(_ => InvalidateFormattedText());
this.GetObservable(CaretIndexProperty)
.Subscribe(CaretIndexChanged);
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
}
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
public int GetCaretIndex(Point point)
{
var hit = FormattedText.HitTestPoint(point);
return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
public override void Render(DrawingContext context)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
// issue #600: set constaint before any FormattedText manipulation
// see base.Render(...) implementation
FormattedText.Constraint = Bounds.Size;
var rects = FormattedText.HitTestTextRange(start, length);
if (_highlightBrush == null)
{
_highlightBrush = (IBrush)this.FindStyleResource("HighlightBrush");
}
foreach (var rect in rects)
{
context.FillRectangle(_highlightBrush, rect);
}
}
base.Render(context);
if (selectionStart == selectionEnd)
{
var backgroundColor = (((Control)TemplatedParent).GetValue(BackgroundProperty) as SolidColorBrush)?.Color;
var caretBrush = Brushes.Black;
if(backgroundColor.HasValue)
{
byte red = (byte)~(backgroundColor.Value.R);
byte green = (byte)~(backgroundColor.Value.G);
byte blue = (byte)~(backgroundColor.Value.B);
caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
}
if (_caretBlink)
{
var charPos = FormattedText.HitTestTextPosition(CaretIndex);
var x = Math.Floor(charPos.X) + 0.5;
var y = Math.Floor(charPos.Y) + 0.5;
var b = Math.Ceiling(charPos.Bottom) - 0.5;
context.DrawLine(
new Pen(caretBrush, 1),
new Point(x, y),
new Point(x, b));
}
}
}
public void ShowCaret()
{
_caretBlink = true;
_caretTimer.Start();
InvalidateVisual();
}
public void HideCaret()
{
_caretBlink = false;
_caretTimer.Stop();
InvalidateVisual();
}
internal void CaretIndexChanged(int caretIndex)
{
if (this.GetVisualParent() != null)
{
_caretBlink = true;
_caretTimer.Stop();
_caretTimer.Start();
InvalidateVisual();
if (IsMeasureValid)
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
}
else
{
// The measure is currently invalid so there's no point trying to bring the
// current char into view until a measure has been carried out as the scroll
// viewer extents may not be up-to-date.
Dispatcher.UIThread.InvokeAsync(
() =>
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
},
DispatcherPriority.Normal);
}
}
}
protected override FormattedText CreateFormattedText(Size constraint)
{
var result = base.CreateFormattedText(constraint);
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
if (length > 0)
{
result.SetForegroundBrush(Brushes.White, start, length);
}
return result;
}
protected override Size MeasureOverride(Size availableSize)
{
var text = Text;
if (!string.IsNullOrWhiteSpace(text))
{
return base.MeasureOverride(availableSize);
}
else
{
// TODO: Pretty sure that measuring "X" isn't the right way to do this...
using (var formattedText = new FormattedText(
"X",
FontFamily,
FontSize,
FontStyle,
TextAlignment,
FontWeight))
{
return formattedText.Measure();
}
}
}
private int CoerceCaretIndex(int value)
{
var text = Text;
var length = text?.Length ?? 0;
return Math.Max(0, Math.Min(length, value));
}
private void CaretTimerTick(object sender, EventArgs e)
{
_caretBlink = !_caretBlink;
InvalidateVisual();
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation activities. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
internal partial class ActivityOperations : IServiceOperations<AutomationManagementClient>, IActivityOperations
{
/// <summary>
/// Initializes a new instance of the ActivityOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ActivityOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the activity in the module identified by module name and
/// activity name. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='moduleName'>
/// Required. The name of module.
/// </param>
/// <param name='activityName'>
/// Required. The name of activity.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get activity operation.
/// </returns>
public async Task<ActivityGetResponse> GetAsync(string resourceGroupName, string automationAccount, string moduleName, string activityName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (moduleName == null)
{
throw new ArgumentNullException("moduleName");
}
if (activityName == null)
{
throw new ArgumentNullException("activityName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("moduleName", moduleName);
tracingParameters.Add("activityName", activityName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/modules/";
url = url + Uri.EscapeDataString(moduleName);
url = url + "/activities/";
url = url + Uri.EscapeDataString(activityName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ActivityGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Activity activityInstance = new Activity();
result.Activity = activityInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityProperties propertiesInstance = new ActivityProperties();
activityInstance.Properties = propertiesInstance;
JToken definitionValue = propertiesValue["definition"];
if (definitionValue != null && definitionValue.Type != JTokenType.Null)
{
string definitionInstance = ((string)definitionValue);
propertiesInstance.Definition = definitionInstance;
}
JToken parameterSetsArray = propertiesValue["parameterSets"];
if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null)
{
foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray))
{
ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet();
propertiesInstance.ParameterSets.Add(activityParameterSetInstance);
JToken nameValue2 = parameterSetsValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
activityParameterSetInstance.Name = nameInstance2;
}
JToken parametersArray = parameterSetsValue["parameters"];
if (parametersArray != null && parametersArray.Type != JTokenType.Null)
{
foreach (JToken parametersValue in ((JArray)parametersArray))
{
ActivityParameter activityParameterInstance = new ActivityParameter();
activityParameterSetInstance.Parameters.Add(activityParameterInstance);
JToken nameValue3 = parametersValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
activityParameterInstance.Name = nameInstance3;
}
JToken typeValue = parametersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
activityParameterInstance.Type = typeInstance;
}
JToken isMandatoryValue = parametersValue["isMandatory"];
if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null)
{
bool isMandatoryInstance = ((bool)isMandatoryValue);
activityParameterInstance.IsMandatory = isMandatoryInstance;
}
JToken isDynamicValue = parametersValue["isDynamic"];
if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null)
{
bool isDynamicInstance = ((bool)isDynamicValue);
activityParameterInstance.IsDynamic = isDynamicInstance;
}
JToken positionValue = parametersValue["position"];
if (positionValue != null && positionValue.Type != JTokenType.Null)
{
bool positionInstance = ((bool)positionValue);
activityParameterInstance.Position = positionInstance;
}
JToken valueFromPipelineValue = parametersValue["valueFromPipeline"];
if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null)
{
bool valueFromPipelineInstance = ((bool)valueFromPipelineValue);
activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance;
}
JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"];
if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null)
{
bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue);
activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance;
}
JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"];
if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null)
{
bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue);
activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance;
}
}
}
}
}
JToken outputTypesArray = propertiesValue["outputTypes"];
if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null)
{
foreach (JToken outputTypesValue in ((JArray)outputTypesArray))
{
ActivityOutputType activityOutputTypeInstance = new ActivityOutputType();
propertiesInstance.OutputTypes.Add(activityOutputTypeInstance);
JToken nameValue4 = outputTypesValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
activityOutputTypeInstance.Name = nameInstance4;
}
JToken typeValue2 = outputTypesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
activityOutputTypeInstance.Type = typeInstance2;
}
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of activities in the module identified by module
/// name. (see http://aka.ms/azureautomationsdk/activityoperations
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='moduleName'>
/// Required. The name of module.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list activity operation.
/// </returns>
public async Task<ActivityListResponse> ListAsync(string resourceGroupName, string automationAccount, string moduleName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (moduleName == null)
{
throw new ArgumentNullException("moduleName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("moduleName", moduleName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/modules/";
url = url + Uri.EscapeDataString(moduleName);
url = url + "/activities";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ActivityListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Activity activityInstance = new Activity();
result.Activities.Add(activityInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityProperties propertiesInstance = new ActivityProperties();
activityInstance.Properties = propertiesInstance;
JToken definitionValue = propertiesValue["definition"];
if (definitionValue != null && definitionValue.Type != JTokenType.Null)
{
string definitionInstance = ((string)definitionValue);
propertiesInstance.Definition = definitionInstance;
}
JToken parameterSetsArray = propertiesValue["parameterSets"];
if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null)
{
foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray))
{
ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet();
propertiesInstance.ParameterSets.Add(activityParameterSetInstance);
JToken nameValue2 = parameterSetsValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
activityParameterSetInstance.Name = nameInstance2;
}
JToken parametersArray = parameterSetsValue["parameters"];
if (parametersArray != null && parametersArray.Type != JTokenType.Null)
{
foreach (JToken parametersValue in ((JArray)parametersArray))
{
ActivityParameter activityParameterInstance = new ActivityParameter();
activityParameterSetInstance.Parameters.Add(activityParameterInstance);
JToken nameValue3 = parametersValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
activityParameterInstance.Name = nameInstance3;
}
JToken typeValue = parametersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
activityParameterInstance.Type = typeInstance;
}
JToken isMandatoryValue = parametersValue["isMandatory"];
if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null)
{
bool isMandatoryInstance = ((bool)isMandatoryValue);
activityParameterInstance.IsMandatory = isMandatoryInstance;
}
JToken isDynamicValue = parametersValue["isDynamic"];
if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null)
{
bool isDynamicInstance = ((bool)isDynamicValue);
activityParameterInstance.IsDynamic = isDynamicInstance;
}
JToken positionValue = parametersValue["position"];
if (positionValue != null && positionValue.Type != JTokenType.Null)
{
bool positionInstance = ((bool)positionValue);
activityParameterInstance.Position = positionInstance;
}
JToken valueFromPipelineValue = parametersValue["valueFromPipeline"];
if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null)
{
bool valueFromPipelineInstance = ((bool)valueFromPipelineValue);
activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance;
}
JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"];
if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null)
{
bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue);
activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance;
}
JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"];
if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null)
{
bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue);
activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance;
}
}
}
}
}
JToken outputTypesArray = propertiesValue["outputTypes"];
if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null)
{
foreach (JToken outputTypesValue in ((JArray)outputTypesArray))
{
ActivityOutputType activityOutputTypeInstance = new ActivityOutputType();
propertiesInstance.OutputTypes.Add(activityOutputTypeInstance);
JToken nameValue4 = outputTypesValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
activityOutputTypeInstance.Name = nameInstance4;
}
JToken typeValue2 = outputTypesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
activityOutputTypeInstance.Type = typeInstance2;
}
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of activities in the module identified by module
/// name. (see http://aka.ms/azureautomationsdk/activityoperations
/// for more information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list activity operation.
/// </returns>
public async Task<ActivityListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ActivityListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Activity activityInstance = new Activity();
result.Activities.Add(activityInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityProperties propertiesInstance = new ActivityProperties();
activityInstance.Properties = propertiesInstance;
JToken definitionValue = propertiesValue["definition"];
if (definitionValue != null && definitionValue.Type != JTokenType.Null)
{
string definitionInstance = ((string)definitionValue);
propertiesInstance.Definition = definitionInstance;
}
JToken parameterSetsArray = propertiesValue["parameterSets"];
if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null)
{
foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray))
{
ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet();
propertiesInstance.ParameterSets.Add(activityParameterSetInstance);
JToken nameValue2 = parameterSetsValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
activityParameterSetInstance.Name = nameInstance2;
}
JToken parametersArray = parameterSetsValue["parameters"];
if (parametersArray != null && parametersArray.Type != JTokenType.Null)
{
foreach (JToken parametersValue in ((JArray)parametersArray))
{
ActivityParameter activityParameterInstance = new ActivityParameter();
activityParameterSetInstance.Parameters.Add(activityParameterInstance);
JToken nameValue3 = parametersValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
activityParameterInstance.Name = nameInstance3;
}
JToken typeValue = parametersValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
activityParameterInstance.Type = typeInstance;
}
JToken isMandatoryValue = parametersValue["isMandatory"];
if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null)
{
bool isMandatoryInstance = ((bool)isMandatoryValue);
activityParameterInstance.IsMandatory = isMandatoryInstance;
}
JToken isDynamicValue = parametersValue["isDynamic"];
if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null)
{
bool isDynamicInstance = ((bool)isDynamicValue);
activityParameterInstance.IsDynamic = isDynamicInstance;
}
JToken positionValue = parametersValue["position"];
if (positionValue != null && positionValue.Type != JTokenType.Null)
{
bool positionInstance = ((bool)positionValue);
activityParameterInstance.Position = positionInstance;
}
JToken valueFromPipelineValue = parametersValue["valueFromPipeline"];
if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null)
{
bool valueFromPipelineInstance = ((bool)valueFromPipelineValue);
activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance;
}
JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"];
if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null)
{
bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue);
activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance;
}
JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"];
if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null)
{
bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue);
activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance;
}
}
}
}
}
JToken outputTypesArray = propertiesValue["outputTypes"];
if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null)
{
foreach (JToken outputTypesValue in ((JArray)outputTypesArray))
{
ActivityOutputType activityOutputTypeInstance = new ActivityOutputType();
propertiesInstance.OutputTypes.Add(activityOutputTypeInstance);
JToken nameValue4 = outputTypesValue["name"];
if (nameValue4 != null && nameValue4.Type != JTokenType.Null)
{
string nameInstance4 = ((string)nameValue4);
activityOutputTypeInstance.Name = nameInstance4;
}
JToken typeValue2 = outputTypesValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
activityOutputTypeInstance.Type = typeInstance2;
}
}
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDate
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Date operations.
/// </summary>
public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate
{
/// <summary>
/// Initializes a new instance of the Date class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Date(AutoRestDateTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDateTestService
/// </summary>
public AutoRestDateTestService Client { get; private set; }
/// <summary>
/// Get null date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalidDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get overflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOverflowDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get underflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put max date value 9999-12-31
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(System.DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMaxDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter());
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get max date value 9999-12-31
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMaxDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put min date value 0000-01-01
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(System.DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutMinDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter());
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get min date value 0000-01-01
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMinDate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
var _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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter());
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Infrastructure.Common;
using System;
using System.Diagnostics;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public partial class ExpectedExceptionTests : ConditionalWcfTest
{
[WcfFact]
[OuterLoop]
public static void NonExistentAction_Throws_ActionNotSupportedException()
{
string exceptionMsg = "The message with Action 'http://tempuri.org/IWcfService/NotExistOnServer' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).";
BasicHttpBinding binding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
// *** VALIDATE *** \\
ActionNotSupportedException exception = Assert.Throws<ActionNotSupportedException>(() =>
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
try
{
serviceProxy.NotExistOnServer();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
// *** ADDITIONAL VALIDATION *** \\
Assert.True(String.Equals(exception.Message, exceptionMsg), String.Format("Expected exception message: {0}\nActual exception message: {1}", exceptionMsg, exception.Message));
}
// SendTimeout is set to 5 seconds, the service waits 10 seconds to respond.
// The client should throw a TimeoutException
[WcfFact]
[OuterLoop]
public static void SendTimeout_For_Long_Running_Operation_Throws_TimeoutException()
{
TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(10000);
BasicHttpBinding binding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stopwatch watch = null;
int lowRange = 4985;
int highRange = 6000;
// *** VALIDATE *** \\
TimeoutException exception = Assert.Throws<TimeoutException>(() =>
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(5000);
endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
serviceProxy = factory.CreateChannel();
watch = new Stopwatch();
// *** EXECUTE *** \\
try
{
watch = new Stopwatch();
watch.Start();
serviceProxy.EchoWithTimeout("Hello", serviceOperationTimeout);
}
finally
{
// *** ENSURE CLEANUP *** \\
watch.Stop();
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
// *** ADDITIONAL VALIDATION *** \\
// want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec
// (usual case is around 5001-5005 ms)
Assert.True((watch.ElapsedMilliseconds >= lowRange && watch.ElapsedMilliseconds <= highRange),
String.Format("Expected elapsed time to be >= to {0} and <= to {1}\nActual elapsed time was: {2}", lowRange, highRange, watch.ElapsedMilliseconds));
}
// SendTimeout is set to 0, this should trigger a TimeoutException before even attempting to call the service.
[WcfFact]
[OuterLoop]
public static void SendTimeout_Zero_Throws_TimeoutException_Immediately()
{
TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(5000);
BasicHttpBinding binding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stopwatch watch = null;
int lowRange = 0;
int highRange = 2000;
// *** VALIDATE *** \\
TimeoutException exception = Assert.Throws<TimeoutException>(() =>
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(0);
endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
serviceProxy = factory.CreateChannel();
watch = new Stopwatch();
// *** EXECUTE *** \\
try
{
watch.Start();
serviceProxy.EchoWithTimeout("Hello", serviceOperationTimeout);
}
finally
{
// *** ENSURE CLEANUP *** \\
watch.Stop();
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
// *** ADDITIONAL VALIDATION *** \\
// want to assert that this completed in < 2 s as an upper bound since the SendTimeout is 0 sec
// (usual case is around 1 - 3 ms)
Assert.True((watch.ElapsedMilliseconds >= lowRange && watch.ElapsedMilliseconds <= highRange),
String.Format("Expected elapsed time to be >= to {0} and <= to {1}\nActual elapsed time was: {2}", lowRange, highRange, watch.ElapsedMilliseconds));
}
[WcfFact]
[OuterLoop]
public static void FaultException_Throws_WithFaultDetail()
{
string faultMsg = "Test Fault Exception";
BasicHttpBinding binding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
// *** VALIDATE *** \\
FaultException<FaultDetail> exception = Assert.Throws<FaultException<FaultDetail>>(() =>
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
try
{
serviceProxy.TestFault(faultMsg);
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
// *** ADDITIONAL VALIDATION *** \\
Assert.True(String.Equals(exception.Detail.Message, faultMsg), String.Format("Expected fault message: {0}\nActual fault message: {1}", faultMsg, exception.Detail.Message));
}
[WcfFact]
[OuterLoop]
public static void UnexpectedException_Throws_FaultException()
{
string faultMsg = "This is a test fault msg";
BasicHttpBinding binding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
// *** VALIDATE *** \\
FaultException<ExceptionDetail> exception = Assert.Throws<FaultException<ExceptionDetail>>(() =>
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
try
{
serviceProxy.ThrowInvalidOperationException(faultMsg);
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
});
// *** ADDITIONAL VALIDATION *** \\
Assert.True(String.Equals(exception.Detail.Message, faultMsg), String.Format("Expected fault message: {0}\nActual fault message: {1}", faultMsg, exception.Detail.Message));
}
[WcfFact]
[OuterLoop]
public static void Abort_During_Implicit_Open_Closes_Async_Waiters()
{
// This test is a regression test of an issue with CallOnceManager.
// When a single proxy is used to make several service calls without
// explicitly opening it, the CallOnceManager queues up all the requests
// that happen while it is opening the channel (or handling previously
// queued service calls. If the channel was closed or faulted during
// the handling of any queued requests, it caused a pathological worst
// case where every queued request waited for its complete SendTimeout
// before failing.
//
// This test operates by making multiple concurrent asynchronous service
// calls, but stalls the Opening event to allow them to be queued before
// any of them are allowed to proceed. It then closes the channel when
// the first service operation is allowed to proceed. This causes the
// CallOnce manager to deal with all its queued operations and cause
// them to complete other than by timing out.
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
int timeoutMs = 20000;
long operationsQueued = 0;
int operationCount = 5;
Task<string>[] tasks = new Task<string>[operationCount];
Exception[] exceptions = new Exception[operationCount];
string[] results = new string[operationCount];
bool isClosed = false;
DateTime endOfOpeningStall = DateTime.Now;
int serverDelayMs = 100;
TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs);
string testMessage = "testMessage";
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
// SendTimeout is the timeout used for implicit opens
binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text));
serviceProxy = factory.CreateChannel();
// Force the implicit open to stall until we have multiple concurrent calls pending.
// This forces the CallOnceManager to have a queue of waiters it will need to notify.
((ICommunicationObject)serviceProxy).Opening += (s, e) =>
{
// Wait until we see sync calls have been queued
DateTime startOfOpeningStall = DateTime.Now;
while (true)
{
endOfOpeningStall = DateTime.Now;
// Don't wait forever -- if we stall longer than the SendTimeout, it means something
// is wrong other than what we are testing, so just fail early.
if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs)
{
Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test.");
}
// As soon as we have all our Tasks at least running, wait a little
// longer to allow them finish queuing up their waiters, then stop stalling the Opening
if (Interlocked.Read(ref operationsQueued) >= operationCount)
{
Task.Delay(500).Wait();
endOfOpeningStall = DateTime.Now;
return;
}
Task.Delay(100).Wait();
}
};
// Each task will make a synchronous service call, which will cause all but the
// first to be queued for the implicit open. The first call to complete then closes
// the channel so that it is forced to deal with queued waiters.
Func<string> callFunc = () =>
{
// We increment the # ops queued before making the actual sync call, which is
// technically a short race condition in the test. But reversing the order would
// timeout the implicit open and fault the channel.
Interlocked.Increment(ref operationsQueued);
// The call of the operation is what creates the entry in the CallOnceManager queue.
// So as each Task below starts, it increments the count and adds a waiter to the
// queue. We ask for a small delay on the server side just to introduce a small
// stall after the sync request has been made before it can complete. Otherwise
// fast machines can finish all the requests before the first one finishes the Close().
Task<string> t = serviceProxy.EchoWithTimeoutAsync(testMessage, serverDelayTimeSpan);
lock (tasks)
{
if (!isClosed)
{
try
{
isClosed = true;
((ICommunicationObject)serviceProxy).Abort();
}
catch { }
}
}
return t.GetAwaiter().GetResult();
};
// *** EXECUTE *** \\
DateTime startTime = DateTime.Now;
for (int i = 0; i < operationCount; ++i)
{
tasks[i] = Task.Run(callFunc);
}
for (int i = 0; i < operationCount; ++i)
{
try
{
results[i] = tasks[i].GetAwaiter().GetResult();
}
catch (Exception ex)
{
exceptions[i] = ex;
}
}
// *** VALIDATE *** \\
double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds;
// Before validating that the issue was fixed, first validate that we received the exceptions or the
// results we expected. This is to verify the fix did not introduce a behavioral change other than the
// elimination of the long unnecessary timeouts after the channel was closed.
int nFailures = 0;
for (int i = 0; i < operationCount; ++i)
{
if (exceptions[i] == null)
{
Assert.True((String.Equals("test", results[i])),
String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'",
i, testMessage, results[i]));
}
else
{
++nFailures;
TimeoutException toe = exceptions[i] as TimeoutException;
Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i));
}
}
Assert.True(nFailures > 0,
String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.",
elapsedMs));
// --- Here is the test of the actual bug fix ---
// The original issue was that sync waiters in the CallOnceManager were not notified when
// the channel became unusable and therefore continued to time out for the full amount.
// Additionally, because they were executed sequentially, it was also possible for each one
// to time out for the full amount. Given that we closed the channel, we expect all the queued
// waiters to have been immediately waked up and detected failure.
int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2;
Assert.True(elapsedMs < expectedElapsedMs,
String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms",
operationCount, elapsedMs, expectedElapsedMs));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
public class MyCertificateValidator : X509CertificateValidator
{
public const string exceptionMsg = "Throwing exception from Validate method on purpose.";
public override void Validate(X509Certificate2 certificate)
{
// Always throw an exception.
// MSDN guidance also uses a simple Exception when an exception is thrown from this method.
throw new Exception(exceptionMsg);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class PagingOperationsExtensions
{
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePages(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesAsync( this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePagesFailure(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesNextOptions pagingGetMultiplePagesNextOptions = default(PagingGetMultiplePagesNextOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesNextAsync( this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesNextOptions pagingGetMultiplePagesNextOptions = default(PagingGetMultiplePagesNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class TempTestingCancel : MonoBehaviour {
public bool isTweening = false;
public bool tweenOverride = false;
private LTDescr tween;
// Use this for initialization
void Start () {
tween = LeanTween.move(gameObject, transform.position + Vector3.one*3f, Random.Range(2,2) ).setRepeat(-1).setLoopClamp ();
}
public void Update () {
if(tween != null){
isTweening = LeanTween.isTweening(gameObject);
if(tweenOverride){
// this next line works
//tween.cancel();
// this one doesn't
LeanTween.cancel(gameObject);
}
}
}
}
public class TestingEverything : MonoBehaviour {
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
private bool eventGameObjectWasCalled = false, eventGeneralWasCalled = false;
private LTDescr lt1;
private LTDescr lt2;
private LTDescr lt3;
private LTDescr lt4;
private LTDescr[] groupTweens;
private GameObject[] groupGOs;
private int groupTweensCnt;
private int rotateRepeat;
private int rotateRepeatAngle;
void Start () {
LeanTest.expected = 21;
// add a listener
LeanTween.addListener(cube1, 0, eventGameObjectCalled);
LeanTest.debug("NOTHING TWEEENING AT BEGINNING", LeanTween.isTweening() == false );
LeanTest.debug("OBJECT NOT TWEEENING AT BEGINNING", LeanTween.isTweening(cube1) == false );
// dispatch event that is received
LeanTween.dispatchEvent(0);
LeanTest.debug("EVENT GAMEOBJECT RECEIVED", eventGameObjectWasCalled );
// do not remove listener
LeanTest.debug("EVENT GAMEOBJECT NOT REMOVED", LeanTween.removeListener(cube2, 0, eventGameObjectCalled)==false );
// remove listener
LeanTest.debug("EVENT GAMEOBJECT REMOVED", LeanTween.removeListener(cube1, 0, eventGameObjectCalled) );
// add a listener
LeanTween.addListener(1, eventGeneralCalled);
// dispatch event that is received
LeanTween.dispatchEvent(1);
LeanTest.debug("EVENT ALL RECEIVED", eventGeneralWasCalled );
// remove listener
LeanTest.debug("EVENT ALL REMOVED", LeanTween.removeListener( 1, eventGeneralCalled) );
lt1 = LeanTween.move( cube1, new Vector3(3f,2f,0.5f), 1.1f );
LeanTween.move( cube2, new Vector3(-3f,-2f,-0.5f), 1.1f );
// ping pong
// rotateAround, Repeat, DestroyOnComplete
rotateRepeat = rotateRepeatAngle = 0;
LeanTween.rotateAround(cube3, Vector3.forward, 360f, 0.1f).setRepeat(3).setOnComplete(rotateRepeatFinished).setOnCompleteOnRepeat(true).setDestroyOnComplete(true);
LeanTween.delayedCall(0.1f*8f, rotateRepeatAllFinished);
// test all onUpdates and onCompletes are removed when tween is initialized
StartCoroutine( timeBasedTesting() );
}
IEnumerator timeBasedTesting(){
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
// Groups of tweens testing
groupTweens = new LTDescr[ 300 ];
groupGOs = new GameObject[ groupTweens.Length ];
groupTweensCnt = 0;
int descriptionMatchCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy( cube.GetComponent( typeof(BoxCollider) ) as Component );
cube.transform.position = new Vector3(0,0,i*3);
cube.name = "c"+i;
groupGOs[i] = cube;
groupTweens[i] = LeanTween.move(cube, transform.position + Vector3.one*3f, 0.6f ).setOnComplete(groupTweenFinished);
if(LeanTween.description(groupTweens[i].id).trans==groupTweens[i].trans)
descriptionMatchCount++;
}
LeanTween.delayedCall(0.82f, groupTweensFinished);
LeanTest.debug("GROUP IDS MATCH", descriptionMatchCount==groupTweens.Length );
LeanTest.debug("MAX SEARCH OPTIMIZED", LeanTween.maxSearch<=groupTweens.Length+5, "maxSearch:"+LeanTween.maxSearch );
LeanTest.debug("SOMETHING IS TWEENING", LeanTween.isTweening() == true );
// resume item before calling pause should continue item along it's way
float previousXLT3 = cube3.transform.position.x;
lt3 = LeanTween.moveX( cube3, 5.0f, 1.1f);
lt3.resume();
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
lt1.cancel();
LeanTween.cancel(cube2);
int tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(LeanTween.isTweening( groupGOs[i] ))
tweenCount++;
if(i%3==0)
LeanTween.pause( groupGOs[i] );
else if(i%3==1)
groupTweens[i].pause();
else
LeanTween.pause( groupTweens[i].id );
}
LeanTest.debug("GROUP ISTWEENING", tweenCount==groupTweens.Length, "expected "+groupTweens.Length+" tweens but got "+tweenCount );
LeanTest.debug("RESUME OUT OF ORDER", previousXLT3!=cube3.transform.position.x, "previousXLT3:"+previousXLT3+" cube3.transform.position.x:"+cube3.transform.position.x);
yield return new WaitForEndOfFrame();
tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(i%3==0)
LeanTween.resume( groupGOs[i] );
else if(i%3==1)
groupTweens[i].resume();
else
LeanTween.resume( groupTweens[i].id );
if(i%2==0 ? LeanTween.isTweening( groupTweens[i].id ) : LeanTween.isTweening( groupGOs[i] ) )
tweenCount++;
}
LeanTest.debug("GROUP RESUME", tweenCount==groupTweens.Length );
LeanTest.debug("CANCEL TWEEN LTDESCR", LeanTween.isTweening(cube1)==false );
LeanTest.debug("CANCEL TWEEN LEANTWEEN", LeanTween.isTweening(cube2)==false );
Time.timeScale = 0.25f;
float start = Time.realtimeSinceStartup;
LeanTween.moveX(cube1, -5f, 0.2f).setOnComplete( ()=>{
float end = Time.realtimeSinceStartup;
float diff = end - start;
LeanTest.debug("SCALED TIMING diff:"+diff, Mathf.Abs(0.8f - diff) < 0.05f, "expected to complete in 0.8f but completed in "+diff );
LeanTest.debug("SCALED ENDING POSITION", Mathf.Approximately(cube1.transform.position.x, -5f), "expected to end at -5f, but it ended at "+cube1.transform.position.x);
});
}
void rotateRepeatFinished(){
if( Mathf.Abs(cube3.transform.eulerAngles.z)<0.0001f )
rotateRepeatAngle++;
rotateRepeat++;
}
void rotateRepeatAllFinished(){
LeanTest.debug("ROTATE AROUND MULTIPLE", rotateRepeatAngle==3, "expected 3 times received "+rotateRepeatAngle+" times" );
LeanTest.debug("ROTATE REPEAT", rotateRepeat==3 );
LeanTest.debug("DESTROY ON COMPLETE", cube3==null, "cube3:"+cube3 );
}
void groupTweenFinished(){
groupTweensCnt++;
}
void groupTweensFinished(){
LeanTest.debug("GROUP FINISH", groupTweensCnt==groupTweens.Length, "expected "+groupTweens.Length+" tweens but got "+groupTweensCnt);
}
void eventGameObjectCalled( LTEvent e ){
eventGameObjectWasCalled = true;
}
void eventGeneralCalled( LTEvent e ){
eventGeneralWasCalled = true;
}
}
| |
// 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.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using System.Security;
namespace System.ServiceProcess
{
/// This class represents an NT service. It allows you to connect to a running or stopped service
/// and manipulate it or get information about it.
public class ServiceController : IDisposable
{
private readonly string _machineName;
private readonly ManualResetEvent _waitForStatusSignal = new ManualResetEvent(false);
private const string DefaultMachineName = ".";
private string _name;
private string _eitherName;
private string _displayName;
private int _commandsAccepted;
private bool _statusGenerated;
private bool _startTypeInitialized;
private int _type;
private bool _disposed;
private SafeServiceHandle _serviceManagerHandle;
private ServiceControllerStatus _status;
private ServiceController[] _dependentServices;
private ServiceController[] _servicesDependedOn;
private ServiceStartMode _startType;
private const int SERVICENAMEMAXLENGTH = 80;
private const int DISPLAYNAMEBUFFERSIZE = 256;
/// Creates a ServiceController object, based on service name.
public ServiceController(string name)
: this(name, DefaultMachineName)
{
}
/// Creates a ServiceController object, based on machine and service name.
public ServiceController(string name, string machineName)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
if (string.IsNullOrEmpty(name))
throw new ArgumentException(SR.Format(SR.InvalidParameter, "name", name));
_machineName = machineName;
_eitherName = name;
_type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL;
}
/// Used by the GetServices and GetDevices methods. Avoids duplicating work by the static
/// methods and our own GenerateInfo().
private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS status)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
_machineName = machineName;
_name = status.serviceName;
_displayName = status.displayName;
_commandsAccepted = status.controlsAccepted;
_status = (ServiceControllerStatus)status.currentState;
_type = status.serviceType;
_statusGenerated = true;
}
/// Used by the GetServicesInGroup method.
private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
_machineName = machineName;
_name = status.serviceName;
_displayName = status.displayName;
_commandsAccepted = status.controlsAccepted;
_status = (ServiceControllerStatus)status.currentState;
_type = status.serviceType;
_statusGenerated = true;
}
/// Tells if the service referenced by this object can be paused.
public bool CanPauseAndContinue
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0;
}
}
/// Tells if the service is notified when system shutdown occurs.
public bool CanShutdown
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_SHUTDOWN) != 0;
}
}
/// Tells if the service referenced by this object can be stopped.
public bool CanStop
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_STOP) != 0;
}
}
/// The descriptive name shown for this service in the Service applet.
public string DisplayName
{
get
{
if (_displayName == null)
GenerateNames();
return _displayName;
}
}
/// The set of services that depend on this service. These are the services that will be stopped if
/// this service is stopped.
public ServiceController[] DependentServices
{
get
{
if (_dependentServices == null)
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ENUMERATE_DEPENDENTS);
try
{
// figure out how big a buffer we need to get the info
int bytesNeeded = 0;
int numEnumerated = 0;
bool result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, IntPtr.Zero, 0,
ref bytesNeeded, ref numEnumerated);
if (result)
{
_dependentServices = Array.Empty<ServiceController>();
return _dependentServices;
}
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.mincore.Errors.ERROR_MORE_DATA)
throw new Win32Exception(lastError);
// allocate the buffer
IntPtr enumBuffer = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
try
{
// get all the info
result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, enumBuffer, bytesNeeded,
ref bytesNeeded, ref numEnumerated);
if (!result)
throw new Win32Exception();
// for each of the entries in the buffer, create a new ServiceController object.
_dependentServices = new ServiceController[numEnumerated];
for (int i = 0; i < numEnumerated; i++)
{
Interop.mincore.ENUM_SERVICE_STATUS status = new Interop.mincore.ENUM_SERVICE_STATUS();
IntPtr structPtr = (IntPtr)((long)enumBuffer + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS>()));
Marshal.PtrToStructure(structPtr, status);
_dependentServices[i] = new ServiceController(_machineName, status);
}
}
finally
{
Marshal.FreeHGlobal(enumBuffer);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
return _dependentServices;
}
}
/// The name of the machine on which this service resides.
public string MachineName
{
get
{
return _machineName;
}
}
/// Returns the short name of the service referenced by this object.
public string ServiceName
{
get
{
if (_name == null)
GenerateNames();
return _name;
}
}
public unsafe ServiceController[] ServicesDependedOn
{
get
{
if (_servicesDependedOn != null)
return _servicesDependedOn;
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_CONFIG);
try
{
int bytesNeeded = 0;
bool success = Interop.mincore.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded);
if (success)
{
_servicesDependedOn = Array.Empty<ServiceController>();
return _servicesDependedOn;
}
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
throw new Win32Exception(lastError);
// get the info
IntPtr bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
try
{
success = Interop.mincore.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
Interop.mincore.QUERY_SERVICE_CONFIG config = new Interop.mincore.QUERY_SERVICE_CONFIG();
Marshal.PtrToStructure(bufPtr, config);
Dictionary<string, ServiceController> dependencyHash = null;
char* dependencyChar = config.lpDependencies;
if (dependencyChar != null)
{
// lpDependencies points to the start of multiple null-terminated strings. The list is
// double-null terminated.
int length = 0;
dependencyHash = new Dictionary<string, ServiceController>();
while (*(dependencyChar + length) != '\0')
{
length++;
if (*(dependencyChar + length) == '\0')
{
string dependencyNameStr = new string(dependencyChar, 0, length);
dependencyChar = dependencyChar + length + 1;
length = 0;
if (dependencyNameStr.StartsWith("+", StringComparison.Ordinal))
{
// this entry is actually a service load group
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] loadGroup = GetServicesInGroup(_machineName, dependencyNameStr.Substring(1));
foreach (Interop.mincore.ENUM_SERVICE_STATUS_PROCESS groupMember in loadGroup)
{
if (!dependencyHash.ContainsKey(groupMember.serviceName))
dependencyHash.Add(groupMember.serviceName, new ServiceController(MachineName, groupMember));
}
}
else
{
if (!dependencyHash.ContainsKey(dependencyNameStr))
dependencyHash.Add(dependencyNameStr, new ServiceController(dependencyNameStr, MachineName));
}
}
}
}
if (dependencyHash != null)
{
_servicesDependedOn = new ServiceController[dependencyHash.Count];
dependencyHash.Values.CopyTo(_servicesDependedOn, 0);
}
else
{
_servicesDependedOn = Array.Empty<ServiceController>();
}
return _servicesDependedOn;
}
finally
{
Marshal.FreeHGlobal(bufPtr);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
}
public ServiceStartMode StartType
{
get
{
if (_startTypeInitialized)
return _startType;
IntPtr serviceHandle = IntPtr.Zero;
try
{
serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_CONFIG);
int bytesNeeded = 0;
bool success = Interop.mincore.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded);
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
throw new Win32Exception(lastError);
// get the info
IntPtr bufPtr = IntPtr.Zero;
try
{
bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
success = Interop.mincore.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
Interop.mincore.QUERY_SERVICE_CONFIG config = new Interop.mincore.QUERY_SERVICE_CONFIG();
Marshal.PtrToStructure(bufPtr, config);
_startType = (ServiceStartMode)config.dwStartType;
_startTypeInitialized = true;
}
finally
{
if (bufPtr != IntPtr.Zero)
Marshal.FreeHGlobal(bufPtr);
}
}
finally
{
if (serviceHandle != IntPtr.Zero)
Interop.mincore.CloseServiceHandle(serviceHandle);
}
return _startType;
}
}
public SafeHandle ServiceHandle
{
get
{
return new SafeServiceHandle(GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ALL_ACCESS));
}
}
/// Gets the status of the service referenced by this object, e.g., Running, Stopped, etc.
public ServiceControllerStatus Status
{
get
{
GenerateStatus();
return _status;
}
}
/// Gets the type of service that this object references.
public ServiceType ServiceType
{
get
{
GenerateStatus();
return (ServiceType)_type;
}
}
private static bool CheckMachineName(string value)
{
return !string.IsNullOrWhiteSpace(value) && value.IndexOf('\\') == -1;
}
private void Close()
{
}
public void Dispose()
{
Dispose(true);
}
/// Disconnects this object from the service and frees any allocated resources.
protected virtual void Dispose(bool disposing)
{
if (_serviceManagerHandle != null)
{
_serviceManagerHandle.Dispose();
_serviceManagerHandle = null;
}
_statusGenerated = false;
_startTypeInitialized = false;
_type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL;
_disposed = true;
}
private unsafe void GenerateStatus()
{
if (!_statusGenerated)
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_STATUS);
try
{
Interop.mincore.SERVICE_STATUS svcStatus = new Interop.mincore.SERVICE_STATUS();
bool success = Interop.mincore.QueryServiceStatus(serviceHandle, &svcStatus);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
_commandsAccepted = svcStatus.controlsAccepted;
_status = (ServiceControllerStatus)svcStatus.currentState;
_type = svcStatus.serviceType;
_statusGenerated = true;
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
}
private unsafe void GenerateNames()
{
if (_machineName.Length == 0)
throw new ArgumentException(SR.NoMachineName);
IntPtr databaseHandle = IntPtr.Zero;
IntPtr memory = IntPtr.Zero;
int bytesNeeded;
int servicesReturned;
int resumeHandle = 0;
try
{
databaseHandle = GetDataBaseHandleWithEnumerateAccess(_machineName);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32,
Interop.mincore.StatusOptions.STATUS_ALL,
IntPtr.Zero,
0,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
null);
memory = Marshal.AllocHGlobal(bytesNeeded);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32,
Interop.mincore.StatusOptions.STATUS_ALL,
memory,
bytesNeeded,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
null);
// Since the service name of one service cannot be equal to the
// service or display name of another service, we can safely
// loop through all services checking if either the service or
// display name matches the user given name. If there is a
// match, then we've found the service.
for (int i = 0; i < servicesReturned; i++)
{
IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>()));
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS();
Marshal.PtrToStructure(structPtr, status);
if (string.Equals(_eitherName, status.serviceName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(_eitherName, status.displayName, StringComparison.OrdinalIgnoreCase))
{
if (_name == null)
{
_name = status.serviceName;
}
if (_displayName == null)
{
_displayName = status.displayName;
}
_eitherName = string.Empty;
return;
}
}
throw new InvalidOperationException(SR.Format(SR.NoService, _eitherName, _machineName));
}
finally
{
Marshal.FreeHGlobal(memory);
if (databaseHandle != IntPtr.Zero)
{
Interop.mincore.CloseServiceHandle(databaseHandle);
}
}
}
private static IntPtr GetDataBaseHandleWithAccess(string machineName, int serviceControlManagerAccess)
{
IntPtr databaseHandle = IntPtr.Zero;
if (machineName.Equals(DefaultMachineName) || machineName.Length == 0)
{
databaseHandle = Interop.mincore.OpenSCManager(null, null, serviceControlManagerAccess);
}
else
{
databaseHandle = Interop.mincore.OpenSCManager(machineName, null, serviceControlManagerAccess);
}
if (databaseHandle == IntPtr.Zero)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.OpenSC, machineName), inner);
}
return databaseHandle;
}
private void GetDataBaseHandleWithConnectAccess()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// get a handle to SCM with connect access and store it in serviceManagerHandle field.
if (_serviceManagerHandle == null)
{
_serviceManagerHandle = new SafeServiceHandle(GetDataBaseHandleWithAccess(_machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_CONNECT));
}
}
private static IntPtr GetDataBaseHandleWithEnumerateAccess(string machineName)
{
return GetDataBaseHandleWithAccess(machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_ENUMERATE_SERVICE);
}
/// Gets all the device-driver services on the local machine.
public static ServiceController[] GetDevices()
{
return GetDevices(DefaultMachineName);
}
/// Gets all the device-driver services in the machine specified.
public static ServiceController[] GetDevices(string machineName)
{
return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_DRIVER);
}
/// Opens a handle for the current service. The handle must be closed with
/// a call to Interop.CloseServiceHandle().
private IntPtr GetServiceHandle(int desiredAccess)
{
GetDataBaseHandleWithConnectAccess();
IntPtr serviceHandle = Interop.mincore.OpenService(_serviceManagerHandle.DangerousGetHandle(), ServiceName, desiredAccess);
if (serviceHandle == IntPtr.Zero)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.OpenService, ServiceName, _machineName), inner);
}
return serviceHandle;
}
/// Gets the services (not including device-driver services) on the local machine.
public static ServiceController[] GetServices()
{
return GetServices(DefaultMachineName);
}
/// Gets the services (not including device-driver services) on the machine specified.
public static ServiceController[] GetServices(string machineName)
{
return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32);
}
/// Helper function for ServicesDependedOn.
private static Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] GetServicesInGroup(string machineName, string group)
{
return GetServices<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32, group, status => { return status; });
}
/// Helper function for GetDevices and GetServices.
private static ServiceController[] GetServicesOfType(string machineName, int serviceType)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
return GetServices<ServiceController>(machineName, serviceType, null, status => { return new ServiceController(machineName, status); });
}
/// Helper for GetDevices, GetServices, and ServicesDependedOn
private static T[] GetServices<T>(string machineName, int serviceType, string group, Func<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS, T> selector)
{
IntPtr databaseHandle = IntPtr.Zero;
IntPtr memory = IntPtr.Zero;
int bytesNeeded;
int servicesReturned;
int resumeHandle = 0;
T[] services;
try
{
databaseHandle = GetDataBaseHandleWithEnumerateAccess(machineName);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
serviceType,
Interop.mincore.StatusOptions.STATUS_ALL,
IntPtr.Zero,
0,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
group);
memory = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
//
// Get the set of services
//
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
serviceType,
Interop.mincore.StatusOptions.STATUS_ALL,
memory,
bytesNeeded,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
group);
//
// Go through the block of memory it returned to us and select the results
//
services = new T[servicesReturned];
for (int i = 0; i < servicesReturned; i++)
{
IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>()));
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS();
Marshal.PtrToStructure(structPtr, status);
services[i] = selector(status);
}
}
finally
{
Marshal.FreeHGlobal(memory);
if (databaseHandle != IntPtr.Zero)
{
Interop.mincore.CloseServiceHandle(databaseHandle);
}
}
return services;
}
/// Suspends a service's operation.
public unsafe void Pause()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE);
try
{
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_PAUSE, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.PauseService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Continues a service after it has been paused.
public unsafe void Continue()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE);
try
{
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_CONTINUE, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.ResumeService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Refreshes all property values.
public void Refresh()
{
_statusGenerated = false;
_startTypeInitialized = false;
_dependentServices = null;
_servicesDependedOn = null;
}
/// Starts the service.
public void Start()
{
Start(Array.Empty<string>());
}
/// Starts a service in the machine specified.
public void Start(string[] args)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_START);
try
{
IntPtr[] argPtrs = new IntPtr[args.Length];
int i = 0;
try
{
for (i = 0; i < args.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException($"{nameof(args)}[{i}]", SR.ArgsCantBeNull);
argPtrs[i] = Marshal.StringToHGlobalUni(args[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
Marshal.FreeHGlobal(argPtrs[i]);
throw;
}
GCHandle argPtrsHandle = new GCHandle();
try
{
argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);
bool result = Interop.mincore.StartService(serviceHandle, args.Length, (IntPtr)argPtrsHandle.AddrOfPinnedObject());
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.CannotStart, ServiceName, _machineName), inner);
}
}
finally
{
for (i = 0; i < args.Length; i++)
Marshal.FreeHGlobal(argPtrs[i]);
if (argPtrsHandle.IsAllocated)
argPtrsHandle.Free();
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Stops the service. If any other services depend on this one for operation,
/// they will be stopped first. The DependentServices property lists this set
/// of services.
public unsafe void Stop()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_STOP);
try
{
// Before stopping this service, stop all the dependent services that are running.
// (It's OK not to cache the result of getting the DependentServices property because it caches on its own.)
for (int i = 0; i < DependentServices.Length; i++)
{
ServiceController currentDependent = DependentServices[i];
currentDependent.Refresh();
if (currentDependent.Status != ServiceControllerStatus.Stopped)
{
currentDependent.Stop();
currentDependent.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30));
}
}
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_STOP, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.StopService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Waits infinitely until the service has reached the given status.
public void WaitForStatus(ServiceControllerStatus desiredStatus)
{
WaitForStatus(desiredStatus, TimeSpan.MaxValue);
}
/// Waits until the service has reached the given status or until the specified time
/// has expired
public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout)
{
if (!Enum.IsDefined(typeof(ServiceControllerStatus), desiredStatus))
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "desiredStatus", (int)desiredStatus, typeof(ServiceControllerStatus)));
DateTime start = DateTime.UtcNow;
Refresh();
while (Status != desiredStatus)
{
if (DateTime.UtcNow - start > timeout)
throw new System.ServiceProcess.TimeoutException(SR.Timeout);
_waitForStatusSignal.WaitOne(250);
Refresh();
}
}
}
}
| |
//
// 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.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// Contains operations for getting dropped Azure SQL Databases that can be
/// restored.
/// </summary>
internal partial class RestorableDroppedDatabaseOperations : IServiceOperations<SqlManagementClient>, IRestorableDroppedDatabaseOperations
{
/// <summary>
/// Initializes a new instance of the
/// RestorableDroppedDatabaseOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RestorableDroppedDatabaseOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Returns information about a dropped Azure SQL Database that can be
/// restored.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database was hosted.
/// </param>
/// <param name='entityId'>
/// Required. The entity ID of the restorable dropped Azure SQL
/// Database to be obtained.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response to the Get Restorable Dropped Database
/// request.
/// </returns>
public async Task<RestorableDroppedDatabaseGetResponse> GetAsync(string serverName, string entityId, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (entityId == null)
{
throw new ArgumentNullException("entityId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("entityId", entityId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/restorabledroppeddatabases/";
url = url + Uri.EscapeDataString(entityId);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RestorableDroppedDatabaseGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RestorableDroppedDatabaseGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
RestorableDroppedDatabase serviceResourceInstance = new RestorableDroppedDatabase();
result.Database = serviceResourceInstance;
XElement entityIdElement = serviceResourceElement.Element(XName.Get("EntityId", "http://schemas.microsoft.com/windowsazure"));
if (entityIdElement != null)
{
string entityIdInstance = entityIdElement.Value;
serviceResourceInstance.EntityId = entityIdInstance;
}
XElement serverNameElement = serviceResourceElement.Element(XName.Get("ServerName", "http://schemas.microsoft.com/windowsazure"));
if (serverNameElement != null)
{
string serverNameInstance = serverNameElement.Value;
serviceResourceInstance.ServerName = serverNameInstance;
}
XElement editionElement = serviceResourceElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement != null)
{
string editionInstance = editionElement.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeBytesElement = serviceResourceElement.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement creationDateElement = serviceResourceElement.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement deletionDateElement = serviceResourceElement.Element(XName.Get("DeletionDate", "http://schemas.microsoft.com/windowsazure"));
if (deletionDateElement != null)
{
DateTime deletionDateInstance = DateTime.Parse(deletionDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.DeletionDate = deletionDateInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourceElement.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && !string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value))
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns a collection of databases that has been dropped but can
/// still be restored from a specified server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to query for
/// dropped databases that can still be restored.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Contains the response to the List Restorable Dropped Databases
/// request.
/// </returns>
public async Task<RestorableDroppedDatabaseListResponse> ListAsync(string serverName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/sqlservers/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/restorabledroppeddatabases";
List<string> queryParameters = new List<string>();
queryParameters.Add("contentview=generic");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RestorableDroppedDatabaseListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RestorableDroppedDatabaseListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
RestorableDroppedDatabase serviceResourceInstance = new RestorableDroppedDatabase();
result.Databases.Add(serviceResourceInstance);
XElement entityIdElement = serviceResourcesElement.Element(XName.Get("EntityId", "http://schemas.microsoft.com/windowsazure"));
if (entityIdElement != null)
{
string entityIdInstance = entityIdElement.Value;
serviceResourceInstance.EntityId = entityIdInstance;
}
XElement serverNameElement = serviceResourcesElement.Element(XName.Get("ServerName", "http://schemas.microsoft.com/windowsazure"));
if (serverNameElement != null)
{
string serverNameInstance = serverNameElement.Value;
serviceResourceInstance.ServerName = serverNameInstance;
}
XElement editionElement = serviceResourcesElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure"));
if (editionElement != null)
{
string editionInstance = editionElement.Value;
serviceResourceInstance.Edition = editionInstance;
}
XElement maxSizeBytesElement = serviceResourcesElement.Element(XName.Get("MaxSizeBytes", "http://schemas.microsoft.com/windowsazure"));
if (maxSizeBytesElement != null)
{
long maxSizeBytesInstance = long.Parse(maxSizeBytesElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.MaximumDatabaseSizeInBytes = maxSizeBytesInstance;
}
XElement creationDateElement = serviceResourcesElement.Element(XName.Get("CreationDate", "http://schemas.microsoft.com/windowsazure"));
if (creationDateElement != null)
{
DateTime creationDateInstance = DateTime.Parse(creationDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.CreationDate = creationDateInstance;
}
XElement deletionDateElement = serviceResourcesElement.Element(XName.Get("DeletionDate", "http://schemas.microsoft.com/windowsazure"));
if (deletionDateElement != null)
{
DateTime deletionDateInstance = DateTime.Parse(deletionDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.DeletionDate = deletionDateInstance;
}
XElement recoveryPeriodStartDateElement = serviceResourcesElement.Element(XName.Get("RecoveryPeriodStartDate", "http://schemas.microsoft.com/windowsazure"));
if (recoveryPeriodStartDateElement != null && !string.IsNullOrEmpty(recoveryPeriodStartDateElement.Value))
{
DateTime recoveryPeriodStartDateInstance = DateTime.Parse(recoveryPeriodStartDateElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.RecoveryPeriodStartDate = recoveryPeriodStartDateInstance;
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
internal class DecoderNLS : Decoder
{
// Remember our encoding
protected Encoding m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_bytesUsed;
internal DecoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.DecoderFallback;
this.Reset();
}
// This is used by our child deserializers
internal DecoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, flush);
}
[System.Security.SecurityCritical] // auto-generated
internal unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember the flush
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex",
SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
internal unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? "bytes" : "chars"),
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = bytes)
{
fixed (char* pChars = chars)
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
[System.Security.SecurityCritical] // auto-generated
internal unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? "chars" : "bytes",
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_bytesUsed = 0;
// Do conversion
charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = this.m_bytesUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.PerformanceData;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Diagnostics;
using System.Management.Automation.Tracing;
namespace System.Management.Automation.PerformanceData
{
/// <summary>
/// An abstract class that forms the base class for any Counter Set type.
/// A Counter Set Instance is required to register a given performance counter category
/// with PSPerfCountersMgr.
/// </summary>
public abstract class CounterSetInstanceBase : IDisposable
{
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#region Protected Members
/// <summary>
/// An instance of counterSetRegistrarBase type encapsulates all the information
/// about a counter set and its associated counters.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected CounterSetRegistrarBase _counterSetRegistrarBase;
// NOTE: Check whether the following dictionaries need to be concurrent
// because there would be only 1 thread creating the instance,
// and that instance would then be shared by multiple threads for data access.
// Those threads won't modify/manipulate the dictionary, but they would only access it.
/// <summary>
/// Dictionary mapping counter name to id.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected ConcurrentDictionary<string, int> _counterNameToIdMapping;
/// <summary>
/// Dictionary mapping counter id to counter type.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected ConcurrentDictionary<int, CounterType> _counterIdToTypeMapping;
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
protected CounterSetInstanceBase(CounterSetRegistrarBase counterSetRegistrarInst)
{
this._counterSetRegistrarBase = counterSetRegistrarInst;
_counterNameToIdMapping = new ConcurrentDictionary<string, int>();
_counterIdToTypeMapping = new ConcurrentDictionary<int, CounterType>();
CounterInfo[] counterInfoArray = this._counterSetRegistrarBase.CounterInfoArray;
for (int i = 0; i < counterInfoArray.Length; i++)
{
this._counterIdToTypeMapping.TryAdd(counterInfoArray[i].Id, counterInfoArray[i].Type);
if (!string.IsNullOrWhiteSpace(counterInfoArray[i].Name))
{
this._counterNameToIdMapping.TryAdd(counterInfoArray[i].Name, counterInfoArray[i].Id);
}
}
}
#endregion
/// <summary>
/// Method that retrieves the target counter id.
/// NOTE: If isNumerator is true, then input counter id is returned.
/// But, if isNumerator is false, then a check is made on the input
/// counter's type to ensure that denominator is indeed value for such a counter.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow", Justification = "countId is validated as known denominator before it is incremented.")]
protected bool RetrieveTargetCounterIdIfValid(int counterId, bool isNumerator, out int targetCounterId)
{
targetCounterId = counterId;
if (isNumerator == false)
{
bool isDenominatorValid = false;
CounterType counterType = this._counterIdToTypeMapping[counterId];
switch (counterType)
{
case CounterType.MultiTimerPercentageActive:
case CounterType.MultiTimerPercentageActive100Ns:
case CounterType.MultiTimerPercentageNotActive:
case CounterType.MultiTimerPercentageNotActive100Ns:
case CounterType.RawFraction32:
case CounterType.RawFraction64:
case CounterType.SampleFraction:
case CounterType.AverageCount64:
case CounterType.AverageTimer32:
isDenominatorValid = true;
break;
}
if (isDenominatorValid == false)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Denominator for update not valid for the given counter id {0}",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
targetCounterId = counterId + 1;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterId' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public abstract bool UpdateCounterByValue(
int counterId,
long stepAmount,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public abstract bool UpdateCounterByValue(
string counterName,
long stepAmount,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then sets the numerator component of target
/// counter 'counterId' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public abstract bool SetCounterValue(
int counterId,
long counterValue,
bool isNumerator);
/// <summary>
/// If isNumerator is true, then sets the numerator component of target
/// Counter 'counterName' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public abstract bool SetCounterValue(
string counterName,
long counterValue,
bool isNumerator);
/// <summary>
/// This method retrieves the counter value associated with counter 'counterId'
/// based on isNumerator parameter.
/// </summary>
public abstract bool GetCounterValue(int counterId, bool isNumerator, out long counterValue);
/// <summary>
/// This method retrieves the counter value associated with counter 'counterName'
/// based on isNumerator parameter.
/// </summary>
public abstract bool GetCounterValue(string counterName, bool isNumerator, out long counterValue);
/// <summary>
/// An abstract method that will be implemented by the derived type
/// so as to dispose the appropriate counter set instance.
/// </summary>
public abstract void Dispose();
/*
/// <summary>
/// Resets the target counter 'counterId' to 0. If the given
/// counter has both numerator and denominator components, then
/// they both are set to 0.
/// </summary>
public bool ResetCounter(
int counterId)
{
this.SetCounterValue(counterId, 0, true);
this.SetCounterValue(counterId, 0, false);
}
/// <summary>
/// Resets the target counter 'counterName' to 0. If the given
/// counter has both numerator and denominator components, then
/// they both are set to 0.
/// </summary>
public void ResetCounter(string counterName)
{
this.SetCounterValue(counterName, 0, true);
this.SetCounterValue(counterName, 0, false);
}
*/
#endregion
}
/// <summary>
/// PSCounterSetInstance is a thin wrapper
/// on System.Diagnostics.PerformanceData.CounterSetInstance.
/// </summary>
public class PSCounterSetInstance : CounterSetInstanceBase
{
#region Private Members
private bool _Disposed;
private CounterSet _CounterSet;
private CounterSetInstance _CounterSetInstance;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#region Private Methods
private void CreateCounterSetInstance()
{
_CounterSet =
new CounterSet(
base._counterSetRegistrarBase.ProviderId,
base._counterSetRegistrarBase.CounterSetId,
base._counterSetRegistrarBase.CounterSetInstType);
// Add the counters to the counter set definition.
foreach (CounterInfo counterInfo in base._counterSetRegistrarBase.CounterInfoArray)
{
if (counterInfo.Name == null)
{
_CounterSet.AddCounter(counterInfo.Id, counterInfo.Type);
}
else
{
_CounterSet.AddCounter(counterInfo.Id, counterInfo.Type, counterInfo.Name);
}
}
string instanceName = PSPerfCountersMgr.Instance.GetCounterSetInstanceName();
// Create an instance of the counter set (contains the counter data).
_CounterSetInstance = _CounterSet.CreateCounterSetInstance(instanceName);
}
private void UpdateCounterByValue(CounterData TargetCounterData, long stepAmount)
{
Debug.Assert(TargetCounterData != null);
if (stepAmount == -1)
{
TargetCounterData.Decrement();
}
else if (stepAmount == 1)
{
TargetCounterData.Increment();
}
else
{
TargetCounterData.IncrementBy(stepAmount);
}
}
#endregion
#endregion
#region Constructors
/// <summary>
/// Constructor for creating an instance of PSCounterSetInstance.
/// </summary>
public PSCounterSetInstance(CounterSetRegistrarBase counterSetRegBaseObj)
: base(counterSetRegBaseObj)
{
CreateCounterSetInstance();
}
#endregion
#region Destructor
/// <summary>
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives the base class opportunity to finalize.
/// </summary>
~PSCounterSetInstance()
{
Dispose(false);
}
#endregion
#region Protected Methods
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!_Disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
_CounterSetInstance.Dispose();
_CounterSet.Dispose();
}
// Note disposing has been done.
_Disposed = true;
}
}
#endregion
#region IDisposable Overrides
/// <summary>
/// Dispose Method implementation for IDisposable interface.
/// </summary>
public override void Dispose()
{
this.Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
#region CounterSetInstanceBase Overrides
#region Public Methods
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterId' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public override bool UpdateCounterByValue(int counterId, long stepAmount, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
this.UpdateCounterByValue(targetCounterData, stepAmount);
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'stepAmount'.
/// Otherwise, updates the denominator component by 'stepAmount'.
/// </summary>
public override bool UpdateCounterByValue(string counterName, long stepAmount, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException("counterName");
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.UpdateCounterByValue(targetCounterId, stepAmount, isNumerator);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// If isNumerator is true, then sets the numerator component
/// of target counter 'counterId' to 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public override bool SetCounterValue(int counterId, long counterValue, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
targetCounterData.Value = counterValue;
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// If isNumerator is true, then updates the numerator component
/// of target counter 'counterName' by a value given by 'counterValue'.
/// Otherwise, sets the denominator component to 'counterValue'.
/// </summary>
public override bool SetCounterValue(string counterName, long counterValue, bool isNumerator)
{
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException("counterName");
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.SetCounterValue(targetCounterId, counterValue, isNumerator);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
/// <summary>
/// This method retrieves the counter value associated with counter 'counterId'
/// based on isNumerator parameter.
/// </summary>
public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue)
{
counterValue = -1;
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
int targetCounterId;
if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
{
CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];
if (targetCounterData != null)
{
counterValue = targetCounterData.Value;
return true;
}
else
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter id {0} failed",
counterId));
_tracer.TraceException(invalidOperationException);
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// This method retrieves the counter value associated with counter 'counterName'
/// based on isNumerator parameter.
/// </summary>
public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue)
{
counterValue = -1;
if (_Disposed)
{
ObjectDisposedException objectDisposedException =
new ObjectDisposedException("PSCounterSetInstance");
_tracer.TraceException(objectDisposedException);
return false;
}
// retrieve counter id associated with the counter name
if (counterName == null)
{
ArgumentNullException argNullException = new ArgumentNullException("counterName");
_tracer.TraceException(argNullException);
return false;
}
try
{
int targetCounterId = this._counterNameToIdMapping[counterName];
return this.GetCounterValue(targetCounterId, isNumerator, out counterValue);
}
catch (KeyNotFoundException)
{
InvalidOperationException invalidOperationException =
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Lookup for counter corresponding to counter name {0} failed",
counterName));
_tracer.TraceException(invalidOperationException);
return false;
}
}
#endregion
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Avalonia.Input;
using static System.Math;
namespace Avalonia.Controls
{
/// <summary>
/// Positions child elements in sequential position from left to right,
/// breaking content to the next line at the edge of the containing box.
/// Subsequent ordering happens sequentially from top to bottom or from right to left,
/// depending on the value of the Orientation property.
/// </summary>
internal class WrapPanel : Panel, INavigableContainer
{
/// <summary>
/// Defines the <see cref="Orientation"/> property.
/// </summary>
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<WrapPanel, Orientation>(nameof(Orientation), defaultValue: Orientation.Horizontal);
/// <summary>
/// Initializes static members of the <see cref="WrapPanel"/> class.
/// </summary>
static WrapPanel()
{
AffectsMeasure(OrientationProperty);
}
/// <summary>
/// Gets or sets the orientation in which child controls will be layed out.
/// </summary>
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Gets the next control in the specified direction.
/// </summary>
/// <param name="direction">The movement direction.</param>
/// <param name="from">The control from which movement begins.</param>
/// <returns>The control.</returns>
IInputElement INavigableContainer.GetControl(NavigationDirection direction, IInputElement from)
{
var horiz = Orientation == Orientation.Horizontal;
int index = Children.IndexOf((IControl)from);
switch (direction)
{
case NavigationDirection.First:
index = 0;
break;
case NavigationDirection.Last:
index = Children.Count - 1;
break;
case NavigationDirection.Next:
++index;
break;
case NavigationDirection.Previous:
--index;
break;
case NavigationDirection.Left:
index = horiz ? index - 1 : -1;
break;
case NavigationDirection.Right:
index = horiz ? index + 1 : -1;
break;
case NavigationDirection.Up:
index = horiz ? -1 : index - 1;
break;
case NavigationDirection.Down:
index = horiz ? -1 : index + 1;
break;
}
if (index >= 0 && index < Children.Count)
{
return Children[index];
}
else
{
return null;
}
}
private UVSize CreateUVSize(Size size) => new UVSize(Orientation, size);
private UVSize CreateUVSize() => new UVSize(Orientation);
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = CreateUVSize();
var lineSize = CreateUVSize();
var uvAvailableSize = CreateUVSize(availableSize);
foreach (var child in Children)
{
child.Measure(availableSize);
var childSize = CreateUVSize(child.DesiredSize);
if (lineSize.U + childSize.U <= uvAvailableSize.U) // same line
{
lineSize.U += childSize.U;
lineSize.V = Max(lineSize.V, childSize.V);
}
else // moving to next line
{
desiredSize.U = Max(lineSize.U, uvAvailableSize.U);
desiredSize.V += lineSize.V;
lineSize = childSize;
}
}
// last element
desiredSize.U = Max(lineSize.U, desiredSize.U);
desiredSize.V += lineSize.V;
return desiredSize.ToSize();
}
/// <inheritdoc/>
protected override Size ArrangeOverride(Size finalSize)
{
double accumulatedV = 0;
var uvFinalSize = CreateUVSize(finalSize);
var lineSize = CreateUVSize();
int firstChildInLineindex = 0;
for (int index = 0; index < Children.Count; index++)
{
var child = Children[index];
var childSize = CreateUVSize(child.DesiredSize);
if (lineSize.U + childSize.U <= uvFinalSize.U) // same line
{
lineSize.U += childSize.U;
lineSize.V = Max(lineSize.V, childSize.V);
}
else // moving to next line
{
var controlsInLine = GetContolsBetween(firstChildInLineindex, index);
ArrangeLine(accumulatedV, lineSize.V, controlsInLine);
accumulatedV += lineSize.V;
lineSize = childSize;
firstChildInLineindex = index;
}
}
if (firstChildInLineindex < Children.Count)
{
var controlsInLine = GetContolsBetween(firstChildInLineindex, Children.Count);
ArrangeLine(accumulatedV, lineSize.V, controlsInLine);
}
return finalSize;
}
private IEnumerable<IControl> GetContolsBetween(int first, int last)
{
return Children.Skip(first).Take(last - first);
}
private void ArrangeLine(double v, double lineV, IEnumerable<IControl> contols)
{
double u = 0;
bool isHorizontal = (Orientation == Orientation.Horizontal);
foreach (var child in contols)
{
var childSize = CreateUVSize(child.DesiredSize);
var x = isHorizontal ? u : v;
var y = isHorizontal ? v : u;
var width = isHorizontal ? childSize.U : lineV;
var height = isHorizontal ? lineV : childSize.U;
child.Arrange(new Rect(x, y, width, height));
u += childSize.U;
}
}
/// <summary>
/// Used to not not write sepearate code for horizontal and vertical orientation.
/// U is direction in line. (x if orientation is horizontal)
/// V is direction of lines. (y if orientation is horizonral)
/// </summary>
[DebuggerDisplay("U = {U} V = {V}")]
private struct UVSize
{
private readonly Orientation _orientation;
internal double U;
internal double V;
private UVSize(Orientation orientation, double width, double height)
{
U = V = 0d;
_orientation = orientation;
Width = width;
Height = height;
}
internal UVSize(Orientation orientation, Size size)
: this(orientation, size.Width, size.Height)
{
}
internal UVSize(Orientation orientation)
{
U = V = 0d;
_orientation = orientation;
}
private double Width
{
get { return (_orientation == Orientation.Horizontal ? U : V); }
set
{
if (_orientation == Orientation.Horizontal)
{
U = value;
}
else
{
V = value;
}
}
}
private double Height
{
get { return (_orientation == Orientation.Horizontal ? V : U); }
set
{
if (_orientation == Orientation.Horizontal)
{
V = value;
}
else
{
U = value;
}
}
}
public Size ToSize()
{
return new Size(Width, Height);
}
}
}
}
| |
using Loon.Core;
using Loon.Core.Timer;
using Loon.Core.Graphics;
using Loon.Core.Graphics.Opengl;
using Loon.Java;
using Loon.Core.Geom;
using Loon.Utils;
using Microsoft.Xna.Framework;
namespace Loon.Action.Sprite.Effect
{
public class FractionEffect : LObject , ISprite {
private int maxElements = 6;
private LTimer timer = new LTimer(40);
private int width, height, scaleWidth, scaleHeight, size;
private float expandLimit = 1.2f;
private int exWidth, exHeigth;
// 0 = x
// 1 = y
// 2 = vx
// 3 = vy
// 4 = color
// 5 = countToCrush;
private float[] fractions;
private LPixmapData pixmap;
private bool isClose, isVisible;
private int loopCount, loopMaxCount = 16;
private long elapsed;
private LTexture tmp;
private PixelThread pixelThread;
public FractionEffect(string resName, bool remove, float scale) {
Init(LTextures.LoadTexture(resName), 1.2f, remove, scale);
}
public FractionEffect(string resName, float limit, bool remove,
float scale) {
Init(LTextures.LoadTexture(resName), limit, remove, scale);
}
public FractionEffect(string resName):this(resName, 1.2f) {
}
public FractionEffect(string resName, float scale) {
Init(LTextures.LoadTexture(resName), 1.2f, false, scale);
}
public FractionEffect(string resName, float limit, float scale) {
Init(LTextures.LoadTexture(resName), limit, false, scale);
}
public FractionEffect(LTexture texture, float scale) {
Init(texture, 1.2f, false, scale);
}
public FractionEffect(LTexture texture, float limit, float scale) {
Init(texture, limit, false, scale);
}
public FractionEffect(LTexture texture, float limit, bool remove,
float scale) {
Init(texture, limit, remove, scale);
}
private void Init(LTexture tex2d, float limit, bool remove, float scale) {
this.isVisible = true;
this.expandLimit = limit;
this.width = tex2d.GetWidth();
this.height = tex2d.GetHeight();
this.scaleWidth = (int) (width * scale);
this.scaleHeight = (int) (height * scale);
this.loopMaxCount = (MathUtils.Max(scaleWidth, scaleHeight) / 2) + 1;
this.fractions = new float[(scaleWidth * scaleHeight) * maxElements];
this.exWidth = (int) (scaleWidth * expandLimit);
this.exHeigth = (int) (scaleHeight * expandLimit);
LImage image = tex2d.GetImage().ScaledInstance(scaleWidth, scaleHeight);
Color[] pixels = image.GetPixels();
if (image != null) {
image.Dispose();
image = null;
}
this.size = pixels.Length;
this.pixmap = new LPixmapData(exWidth, exHeigth, true);
int no = 0, idx = 0;
int length = fractions.Length;
float angle = 0;
float speed = 0;
System.Random random = LSystem.random;
for (int y = 0; y < scaleHeight; y++) {
for (int x = 0; x < scaleWidth; x++) {
if (idx + maxElements < length) {
no = y * scaleWidth + x;
angle = random.Next(360);
speed = 10f / random.Next(30);
fractions[idx + 0] = x;
fractions[idx + 1] = y;
fractions[idx + 2] = (MathUtils.Cos(angle * MathUtils.PI
/ 180) * speed);
fractions[idx + 3] = (MathUtils.Sin(angle * MathUtils.PI
/ 180) * speed);
fractions[idx + 4] = (pixels[no].PackedValue == 0xff00 ? 0xffffff
: pixels[no].PackedValue);
fractions[idx + 5] = x / 6 + random.Next(10);
idx += maxElements;
}
}
}
if (remove) {
if (tex2d != null) {
tex2d.Destroy();
tex2d = null;
}
}
this.tmp = tex2d;
this.StartUsePixelThread();
}
public void SetDelay(long d) {
timer.SetDelay(d);
}
public long GetDelay() {
return timer.GetDelay();
}
private class PixelThread : Thread {
private FractionEffect effect;
public PixelThread(FractionEffect e)
{
this.effect = e;
}
static void FilterFractions(int size, float[] fractions, int width,
int height, Color[] pixels, int numElements)
{
int x, y;
int idx = 0;
for (int j = 0; j < size; j++)
{
idx = j * numElements;
if (fractions[idx + 4] != 0xffffff)
{
if (fractions[idx + 5] <= 0)
{
fractions[idx + 0] += fractions[idx + 2];
fractions[idx + 1] += fractions[idx + 3];
fractions[idx + 3] += 0.1f;
}
else
{
fractions[idx + 5]--;
}
x = (int)fractions[idx + 0];
y = (int)fractions[idx + 1];
if (x > -1 && y > -1 && x < width && y < height)
{
pixels[x + y * width].PackedValue = System.Convert.ToUInt32(fractions[idx + 4]);
}
}
}
}
public override void Run() {
for (; !effect.isClose && !effect.IsComplete(); )
{
if (!effect.isVisible)
{
continue;
}
if (effect.timer.Action(effect.elapsed))
{
if (effect.pixmap.IsDirty())
{
continue;
}
effect.pixmap.Reset();
FilterFractions(effect.size, effect.fractions,
effect.pixmap.GetWidth(), effect.pixmap.GetHeight(),
effect.pixmap.GetPixels(), effect.maxElements);
effect.pixmap.Submit();
effect.loopCount++;
}
}
}
}
void StartUsePixelThread() {
if (pixelThread == null) {
pixelThread = new PixelThread(this);
pixelThread.Start();
}
}
void EndUsePixelThread() {
if (pixelThread != null) {
try {
pixelThread.Interrupt();
pixelThread = null;
} catch (System.Exception) {
pixelThread = null;
}
}
}
public override void Update(long elapsedTime) {
this.elapsed = elapsedTime;
}
public void CreateUI(GLEx g) {
if (isClose) {
return;
}
if (!isVisible) {
return;
}
if (IsComplete()) {
return;
}
if (alpha > 0 && alpha < 1) {
g.SetAlpha(alpha);
}
pixmap.Draw(g, X(), Y(), width, height);
if (alpha > 0 && alpha < 1) {
g.SetAlpha(1f);
}
}
public void Reset() {
pixmap.Reset();
loopCount = 0;
}
public bool IsComplete() {
bool stop = pixmap.IsClose() || loopCount > loopMaxCount;
if (!stop) {
StartUsePixelThread();
} else {
EndUsePixelThread();
}
return stop;
}
public override int GetHeight() {
return height;
}
public override int GetWidth()
{
return width;
}
public LTexture GetBitmap() {
return tmp;
}
public RectBox GetCollisionBox() {
return GetRect(X(), Y(), width, height);
}
public bool IsVisible() {
return isVisible;
}
public void SetVisible(bool visible) {
this.isVisible = true;
}
public int GetLoopCount() {
return loopCount;
}
public void SetLoopCount(int loopCount) {
this.loopCount = loopCount;
}
public int GetLoopMaxCount() {
return loopMaxCount;
}
public void SetLoopMaxCount(int loopMaxCount) {
this.loopMaxCount = loopMaxCount;
}
public void Dispose() {
this.isClose = true;
this.EndUsePixelThread();
if (pixmap != null) {
pixmap.Dispose();
}
if (tmp != null) {
tmp.Destroy();
tmp = null;
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Imports
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.DataMapper.Scope;
using IBatisNet.DataMapper.TypeHandlers;
#endregion
namespace IBatisNet.DataMapper.Configuration.ResultMapping
{
/// <summary>
/// Summary description for ResultProperty.
/// </summary>
[Serializable]
[XmlRoot("result", Namespace="http://ibatis.apache.org/mapping")]
public class ResultProperty
{
#region Const
/// <summary>
///
/// </summary>
public const int UNKNOWN_COLUMN_INDEX = -999999;
#endregion
#region Fields
[NonSerialized]
private PropertyInfo _propertyInfo = null;
[NonSerialized]
private string _nullValue = null;
[NonSerialized]
private string _propertyName = string.Empty;
[NonSerialized]
private string _columnName = string.Empty;
[NonSerialized]
private int _columnIndex = UNKNOWN_COLUMN_INDEX;
[NonSerialized]
private string _select = string.Empty;
[NonSerialized]
private string _nestedResultMapName = string.Empty;
[NonSerialized]
private ResultMap _nestedResultMap = null;
[NonSerialized]
private string _dbType = null;
[NonSerialized]
private string _clrType = string.Empty;
[NonSerialized]
private bool _isLazyLoad = false;
[NonSerialized]
private ITypeHandler _typeHandler = null;
[NonSerialized]
private string _callBackName= string.Empty;
#endregion
#region Properties
/// <summary>
/// Specify the custom type handlers to used.
/// </summary>
/// <remarks>Will be an alias to a class wchic implement ITypeHandlerCallback</remarks>
[XmlAttribute("typeHandler")]
public string CallBackName
{
get { return _callBackName; }
set { _callBackName = value; }
}
/// <summary>
/// Tell us if we must lazy load this property..
/// </summary>
[XmlAttribute("lazyLoad")]
public bool IsLazyLoad
{
get { return _isLazyLoad; }
set { _isLazyLoad = value; }
}
/// <summary>
/// The typeHandler used to work with the result property.
/// </summary>
[XmlIgnore]
public ITypeHandler TypeHandler
{
get { return _typeHandler; }
set { _typeHandler = value; }
}
/// <summary>
/// Give an entry in the 'DbType' enumeration
/// </summary>
/// <example >
/// For Sql Server, give an entry of SqlDbType : Bit, Decimal, Money...
/// <br/>
/// For Oracle, give an OracleType Enumeration : Byte, Int16, Number...
/// </example>
[XmlAttribute("dbType")]
public string DbType
{
get { return _dbType; }
set { _dbType = value; }
}
/// <summary>
/// Specify the CLR type of the result.
/// </summary>
/// <remarks>
/// The type attribute is used to explicitly specify the property type of the property to be set.
/// Normally this can be derived from a property through reflection, but certain mappings such as
/// HashTable cannot provide the type to the framework.
/// </remarks>
[XmlAttribute("type")]
public string CLRType
{
get { return _clrType; }
set { _clrType = value; }
}
/// <summary>
/// Column Index
/// </summary>
[XmlAttribute("columnIndex")]
public int ColumnIndex
{
get { return _columnIndex; }
set { _columnIndex = value; }
}
/// <summary>
/// The name of the statement to retrieve the property
/// </summary>
[XmlAttribute("select")]
public string Select
{
get { return _select; }
set { _select = value; }
}
/// <summary>
/// The name of a nested ResultMap to set the property
/// </summary>
[XmlAttribute("resultMapping")]
public string NestedResultMapName
{
get { return _nestedResultMapName; }
set { _nestedResultMapName = value; }
}
/// <summary>
/// Column Name
/// </summary>
[XmlAttribute("column")]
public string ColumnName
{
get { return _columnName; }
set { _columnName = value; }
}
/// <summary>
/// The property name used to identify the property amongst the others.
/// </summary>
[XmlAttribute("property")]
public string PropertyName
{
get { return _propertyName; }
set { _propertyName = value; }
}
/// <summary>
///
/// </summary>
[XmlIgnore]
public PropertyInfo PropertyInfo
{
get { return _propertyInfo; }
}
/// <summary>
/// Tell if a nullValue is defined.
/// </summary>
[XmlIgnore]
public bool HasNullValue
{
get { return (_nullValue!=null); }
}
/// <summary>
/// Null value replacement.
/// </summary>
/// <example>"no_email@provided.com"</example>
[XmlAttribute("nullValue")]
public string NullValue
{
get { return _nullValue; }
set { _nullValue = value; }
}
/// <summary>
/// A nested ResultMap use to set a property
/// </summary>
[XmlIgnore]
public ResultMap NestedResultMap
{
get { return _nestedResultMap; }
set { _nestedResultMap = value; }
}
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Do not use direclty, only for serialization.
/// </summary>
public ResultProperty()
{
}
#endregion
#region Methods
/// <summary>
/// Initialize the PropertyInfo of the result property.
/// </summary>
/// <param name="resultClass"></param>
/// <param name="configScope"></param>
public void Initialize( ConfigurationScope configScope, Type resultClass )
{
if ( _propertyName.Length>0 &&_propertyName != "value" && !typeof(IDictionary).IsAssignableFrom(resultClass) )
{
_propertyInfo = ObjectProbe.GetPropertyInfoForSetter(resultClass, _propertyName);
}
if (this.CallBackName!=null && this.CallBackName.Length >0)
{
configScope.ErrorContext.MoreInfo = "Result property '"+_propertyName+"' check the typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation).";
try
{
Type type = configScope.SqlMapper.GetType(this.CallBackName);
ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback) Activator.CreateInstance( type );
_typeHandler = new CustomTypeHandler(typeHandlerCallback);
}
catch (Exception e)
{
throw new ConfigurationException("Error occurred during custom type handler configuration. Cause: " + e.Message, e);
}
}
else
{
configScope.ErrorContext.MoreInfo = "Result property '"+_propertyName+"' set the typeHandler attribute.";
_typeHandler = configScope.ResolveTypeHandler( resultClass, _propertyName, _clrType, _dbType);
}
}
/// <summary>
/// Initialize the PropertyInfo of the result property
/// for AutoMapper
/// </summary>
/// <param name="propertyInfo">A PropertyInfoot.</param>
/// <param name="typeHandlerFactory"></param>
internal void Initialize(TypeHandlerFactory typeHandlerFactory, PropertyInfo propertyInfo )
{
_propertyInfo = propertyInfo;
_typeHandler = typeHandlerFactory.GetTypeHandler(propertyInfo.PropertyType);
}
/// <summary>
///
/// </summary>
/// <param name="dataReader"></param>
/// <returns></returns>
public object GetDataBaseValue(IDataReader dataReader)
{
object value = null;
if (_columnIndex == UNKNOWN_COLUMN_INDEX)
{
value = _typeHandler.GetValueByName(this, dataReader);
}
else
{
value = _typeHandler.GetValueByIndex(this, dataReader);
}
bool wasNull = (value == DBNull.Value);
if (wasNull)
{
if (this.HasNullValue)
{
if (_propertyInfo!=null)
{
value = _typeHandler.ValueOf(_propertyInfo.PropertyType, _nullValue);
}
else
{
value = _typeHandler.ValueOf(null, _nullValue);
}
}
else
{
value = null;
}
}
return value;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using CjClutter.OpenGl.Camera;
using CjClutter.OpenGl.CoordinateSystems;
using CjClutter.OpenGl.EntityComponent;
using CjClutter.OpenGl.Input.Keboard;
using CjClutter.OpenGl.Input.Mouse;
using CjClutter.OpenGl.Noise;
using CjClutter.OpenGl.SceneGraph;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using OpenTK.Platform;
using FrameEventArgs = OpenTK.FrameEventArgs;
namespace CjClutter.OpenGl.Gui
{
public class OpenGlWindow : GameWindow
{
private readonly FrameTimeCounter _frameTimeCounter = new FrameTimeCounter();
private Stopwatch _stopwatch;
private readonly MouseInputProcessor _mouseInputProcessor;
private readonly MouseInputObservable _mouseInputObservable;
private readonly KeyboardInputProcessor _keyboardInputProcessor = new KeyboardInputProcessor();
private readonly KeyboardInputObservable _keyboardInputObservable;
private readonly ICamera _camera;
private EntityManager _entityManager;
private List<IEntitySystem> _systems;
private LookAtCamera _lodCamera;
private bool _synchronizeCameras = true;
private Terrain _terrain;
private Cube _cube;
public OpenGlWindow(int width, int height, string title, OpenGlVersion openGlVersion)
: base(
width,
height,
GraphicsMode.Default,
title,
GameWindowFlags.Default,
DisplayDevice.Default,
openGlVersion.Major,
openGlVersion.Minor,
GraphicsContextFlags.Default)
{
_mouseInputProcessor = new MouseInputProcessor(this, new GuiToRelativeCoordinateTransformer());
var buttonUpEventEvaluator = new ButtonUpActionEvaluator(_mouseInputProcessor);
_mouseInputObservable = new MouseInputObservable(buttonUpEventEvaluator);
_keyboardInputObservable = new KeyboardInputObservable(_keyboardInputProcessor);
_camera = new LookAtCamera();
_lodCamera = new LookAtCamera();
}
private void StartJobThread()
{
Context.MakeCurrent(null);
var contextReady = new AutoResetEvent(false);
var thread = new Thread(() =>
{
var window = new NativeWindow();
var context = new GraphicsContext(Context.GraphicsMode, window.WindowInfo);
context.MakeCurrent(window.WindowInfo);
contextReady.Set();
while (true)
{
var action = JobDispatcher.Instance.Dequeue();
action();
}
});
thread.IsBackground = true;
thread.Start();
contextReady.WaitOne();
MakeCurrent();
}
protected override void OnLoad(EventArgs e)
{
StartJobThread();
StartJobThread();
StartJobThread();
StartJobThread();
StartJobThread();
StartJobThread();
StartJobThread();
StartJobThread();
_stopwatch = new Stopwatch();
_stopwatch.Start();
_keyboardInputObservable.SubscribeKey(KeyCombination.LeftAlt && KeyCombination.Enter, CombinationDirection.Down, ToggleFullScren);
_keyboardInputObservable.SubscribeKey(KeyCombination.Esc, CombinationDirection.Down, Exit);
_keyboardInputObservable.SubscribeKey(KeyCombination.P, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Perspective);
_keyboardInputObservable.SubscribeKey(KeyCombination.O, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Orthographic);
_keyboardInputObservable.SubscribeKey(KeyCombination.F, CombinationDirection.Down, () => _synchronizeCameras = !_synchronizeCameras);
_entityManager = new EntityManager();
var terrainSystem = new TerrainSystem(FractalBrownianMotionSettings.Default);
_systems = new List<IEntitySystem>
{
terrainSystem,
new FreeCameraSystem(_keyboardInputProcessor, _mouseInputProcessor,_camera),
new LightMoverSystem(),
new OceanSystem(),
new CubeMeshSystem(),
new InputSystem(_keyboardInputProcessor)
//new ChunkedLODSystem(_lodCamera),
//new RenderSystem(_camera),
};
var light = new Entity(Guid.NewGuid().ToString());
_entityManager.Add(light);
_entityManager.AddComponentToEntity(light, new PositionalLightComponent { Position = new Vector3d(0, 20, 0) });
_entityManager.AddComponentToEntity(light, new InputComponent(Key.J, Key.L, Key.M, Key.N, Key.U, Key.I));
const int numberOfChunksX = 20;
const int numberOfChunksY = 20;
for (var i = 0; i < numberOfChunksX; i++)
{
for (var j = 0; j < numberOfChunksY; j++)
{
var entity = new Entity(Guid.NewGuid().ToString());
_entityManager.Add(entity);
_entityManager.AddComponentToEntity(entity, new ChunkComponent(i, j));
_entityManager.AddComponentToEntity(entity, new StaticMesh());
}
}
var settingsViewModel = new SettingsViewModel(new NoiseFactory.NoiseParameters());
settingsViewModel.SettingsChanged += () =>
{
var settings = settingsViewModel.Assemble();
terrainSystem.SetTerrainSettings(new NoiseFactory.RidgedMultiFractal().Create(settings));
};
_terrain = new Terrain(new ChunkedLod());
_cube = new Cube();
}
private void ToggleFullScren()
{
if (WindowState == WindowState.Fullscreen)
{
WindowState = WindowState.Normal;
}
else if (WindowState == WindowState.Normal)
{
WindowState = WindowState.Fullscreen;
}
}
protected override void OnResize(EventArgs e)
{
GL.Viewport(0, 0, Width, Height);
_camera.Width = Width;
_camera.Height = Height;
}
protected override void OnUpdateFrame(FrameEventArgs e)
{
ProcessMouseInput();
ProcessKeyboardInput();
}
protected override void OnRenderFrame(FrameEventArgs e)
{
if (_synchronizeCameras)
{
_lodCamera.Position = _camera.Position;
_lodCamera.Target = _camera.Target;
_lodCamera.Up = _camera.Up;
_lodCamera.Width = _camera.Width;
_lodCamera.Height = _camera.Height;
}
_frameTimeCounter.UpdateFrameTime(e.Time);
GL.Clear(ClearBufferMask.DepthBufferBit);
foreach (var system in _systems)
{
system.Update(ElapsedTime.TotalSeconds, _entityManager);
}
_terrain.Render(_camera, _lodCamera, _entityManager.GetComponent<PositionalLightComponent>(_entityManager.GetEntitiesWithComponent<PositionalLightComponent>().Single()).Position);
_cube.Render(_camera, _entityManager.GetComponent<PositionalLightComponent>(_entityManager.GetEntitiesWithComponent<PositionalLightComponent>().Single()).Position);
SwapBuffers();
}
private void ProcessKeyboardInput()
{
if (!Focused)
{
return;
}
var keyboardState = OpenTK.Input.Keyboard.GetState();
_keyboardInputProcessor.Update(keyboardState);
_keyboardInputObservable.ProcessKeys();
}
private void ProcessMouseInput()
{
if (!Focused)
{
return;
}
var mouseState = OpenTK.Input.Mouse.GetState();
_mouseInputProcessor.Update(mouseState);
_mouseInputObservable.ProcessMouseButtons();
}
public TimeSpan ElapsedTime
{
get { return _stopwatch.Elapsed; }
}
}
}
| |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// 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 Sharpex2D.Math
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
[Serializable]
public struct Vector2
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Vector2" /> struct.
/// </summary>
/// <param name="value">The value.</param>
public Vector2(float value)
{
_x = value;
_y = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Vector2" /> struct.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public Vector2(float x, float y)
{
_x = x;
_y = y;
}
#endregion
#region Fields
private float _x;
private float _y;
#endregion
#region Vectors
/// <summary>
/// Returns a null vector.
/// </summary>
public static Vector2 Zero
{
get { return new Vector2(0, 0); }
}
/// <summary>
/// Returns a vector that represents the x-axis.
/// </summary>
public static Vector2 UnitX
{
get { return new Vector2(1, 0); }
}
/// <summary>
/// Returns a vector that represents the y-axis.
/// </summary>
public static Vector2 UnitY
{
get { return new Vector2(0, 1); }
}
#endregion
#region Coordinates
/// <summary>
/// Gets or sets the X coordinate.
/// </summary>
public float X
{
get { return _x; }
set { _x = value; }
}
/// <summary>
/// Gets or sets the Y coordinate.
/// </summary>
public float Y
{
get { return _y; }
set { _y = value; }
}
#endregion
#region Properties
/// <summary>
/// Gets the length.
/// </summary>
public float Length
{
get { return MathHelper.Sqrt(LengthSquared); }
}
/// <summary>
/// Gets the length squared.
/// </summary>
public float LengthSquared
{
get { return _x*_x + _y*_y; }
}
#endregion
#region Methods
/// <summary>
/// Normalizes this vector.
/// </summary>
public void Normalize()
{
if (LengthSquared > 0)
{
float divider = 1.0f/Length;
_x *= divider;
_y *= divider;
}
}
/// <summary>
/// Translates the vector.
/// </summary>
/// <param name="translation">The translation.</param>
public void Translate(Vector2 translation)
{
_x += translation.X;
_y += translation.Y;
}
#endregion
#region Vector Methods
/// <summary>
/// Truncates the specified vector and removes all decimal places.
/// </summary>
/// <param name="a">The vector.</param>
public static Vector2 Truncate(Vector2 a)
{
return new Vector2((int) a.X, (int) a.Y);
}
/// <summary>
/// Normalizes the specified vector.
/// </summary>
/// <param name="a">The vector.</param>
public static Vector2 Normalize(Vector2 a)
{
if (a.LengthSquared == 0)
return Zero;
float divider = 1.0f/a.Length;
return new Vector2(
a.X*divider,
a.Y*divider);
}
/// <summary>
/// Returns the absolute values of the specified vector.
/// </summary>
/// <param name="a">The vector.</param>
public static Vector2 Abs(Vector2 a)
{
return new Vector2(
MathHelper.Abs(a.X),
MathHelper.Abs(a.Y));
}
/// <summary>
/// Clamps the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <returns></returns>
public static Vector2 Clamp(Vector2 value, Vector2 min, Vector2 max)
{
return new Vector2(
MathHelper.Clamp(value.X, min.X, max.X),
MathHelper.Clamp(value.Y, min.Y, max.Y));
}
/// <summary>
/// Linear interpolation between the two values.
/// </summary>
/// <param name="a">The first value.</param>
/// <param name="b">The second value.</param>
/// <param name="amount">The amount.</param>
public static Vector2 Lerp(Vector2 a, Vector2 b, float amount)
{
Vector2 result = Zero;
result.X = MathHelper.Lerp(a.X, b.X, amount);
result.Y = MathHelper.Lerp(a.Y, b.Y, amount);
return result;
}
/// <summary>
/// Rotates the specified vector.
/// </summary>
/// <param name="vector">The vector.</param>
/// <param name="angle">The angle.</param>
public static Vector2 Rotate(Vector2 vector, float angle)
{
float rx = vector.X*MathHelper.Cos(angle) - vector.Y*MathHelper.Sin(angle);
float ry = vector.X*MathHelper.Sin(angle) + vector.Y*MathHelper.Cos(angle);
return new Vector2(rx, ry);
}
/// <summary>
/// Rounds the specified vector.
/// </summary>
/// <param name="vector">The vector.</param>
public static Vector2 Round(Vector2 vector)
{
vector.X = MathHelper.Round(vector.X);
vector.Y = MathHelper.Round(vector.Y);
return vector;
}
/// <summary>
/// Interpolates between two values using a cubic equation.
/// </summary>
/// <param name="a">The first value.</param>
/// <param name="b">The second value.</param>
/// <param name="amount">The amount.</param>
public static Vector2 SmoothStep(Vector2 a, Vector2 b, float amount)
{
Vector2 result = Zero;
result.X = MathHelper.SmoothStep(a.X, b.X, amount);
result.Y = MathHelper.SmoothStep(a.Y, b.Y, amount);
return result;
}
/// <summary>
/// Returns the lesser components of the two values.
/// </summary>
/// <param name="a">The first value.</param>
/// <param name="b">The second value.</param>
public static Vector2 Min(Vector2 a, Vector2 b)
{
return new Vector2(
MathHelper.Min(a.X, b.X),
MathHelper.Min(a.Y, b.Y));
}
/// <summary>
/// Returns the greater components of the two values.
/// </summary>
/// <param name="a">The first value.</param>
/// <param name="b">The second value.</param>
public static Vector2 Max(Vector2 a, Vector2 b)
{
return new Vector2(
MathHelper.Max(a.X, b.X),
MathHelper.Max(a.Y, b.Y));
}
/// <summary>
/// Returns the dot product for the specified vectors.
/// </summary>
/// <param name="a">The first value.</param>
/// <param name="b">The second value.</param>
/// <returns></returns>
public static float Dot(Vector2 a, Vector2 b)
{
return a.X*b.X + a.Y*b.Y;
}
/// <summary>
/// Reflects the specified vector.
/// </summary>
/// <param name="vector">The vector.</param>
/// <param name="normal">The normal.</param>
public static Vector2 Reflect(Vector2 vector, Vector2 normal)
{
Vector2 result = Zero;
float sub = 2*Dot(vector, normal);
result.X = vector.X - sub*normal.X;
result.Y = vector.Y - sub*normal.Y;
return result;
}
/// <summary>
/// Negates the specified vector.
/// </summary>
/// <param name="vector">The vector.</param>
public static Vector2 Negate(Vector2 vector)
{
return new Vector2(-vector.X, -vector.Y);
}
/// <summary>
/// Returns the vector product.
/// </summary>
public static float VectorProduct(Vector2 left, Vector2 right)
{
return left.X*right.Y - left.Y*right.X;
}
/// <summary>
/// Returns the vector cross product.
/// </summary>
public Vector2 CrossProduct()
{
return new Vector2(-Y, X);
}
#endregion
#region Object Member
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
public override bool Equals(object obj)
{
return this == (Vector2) obj;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return X.GetHashCode() + Y.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
public override string ToString()
{
return "{" + X + "," + Y + "}";
}
#endregion
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static bool operator ==(Vector2 a, Vector2 b)
{
return (a.X == b.X) && (a.Y == b.Y);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static bool operator !=(Vector2 a, Vector2 b)
{
return (a.X != b.X) || (a.Y != b.Y);
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static Vector2 operator +(Vector2 a, Vector2 b)
{
return new Vector2(a.X + b.X, a.Y + b.Y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static Vector2 operator -(Vector2 a, Vector2 b)
{
return new Vector2(a.X - b.X, a.Y - b.Y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="a">The vector.</param>
public static Vector2 operator -(Vector2 a)
{
return new Vector2(-a.X, -a.Y);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static Vector2 operator *(Vector2 a, Vector2 b)
{
return new Vector2(a.X*b.X, a.Y*b.Y);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="a">The vector.</param>
/// <param name="scale">The scale.</param>
public static Vector2 operator *(Vector2 a, float scale)
{
return new Vector2(a.X*scale, a.Y*scale);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="a">The first vector.</param>
/// <param name="b">The second vector.</param>
public static Vector2 operator /(Vector2 a, Vector2 b)
{
return new Vector2(a.X/b.X, a.Y/b.Y);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="a">The vector.</param>
/// <param name="scale">The scale.</param>
public static Vector2 operator /(Vector2 a, float scale)
{
return new Vector2(a.X/scale, a.Y/scale);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// system.Array.LastIndexOf<>(T[],T,int32,int32)
/// </summary>
public class ArrayIndexOf3
{
#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;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Test the array of elements which have the same value ");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
int value = TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
for (int i = 0; i < length; i++)
{
i1[i] = value;
}
for (int i = length - 1; i >= 0; i--) // travel the array
{
if (Array.LastIndexOf<int>(i1, value, i, i + 1) != i)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Test the empty string ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
s1[i] = "";
}
for (int i = length - 1; i >= 0; i--) // travel the array
{
if (Array.LastIndexOf<string>(s1, "", i, i + 1) != i)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Generic convert byte to int32");
try
{
int[] i1 = new int[6] { 2356, 255, 988874, 90875, 255, 123334564 };
byte b1 = 255;
if (Array.LastIndexOf<int>(i1, b1, 5, 6) != 4)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Test the array of char");
try
{
char[] i1 = new char[6] { 't', 'r', 'c', '4', 'r', 'c' };
char b1 = 'c';
if (Array.LastIndexOf<char>(i1, b1, 4, 5) != 2)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Test the null element of the string array ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
null,
"Mary"};
if (Array.LastIndexOf<string>(s1, null, 5, 6) != 4)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest6: Find out no result ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tim",
"Mary"};
if (Array.LastIndexOf<string>(s1, "mary", 5, 6) != -1)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The array is a null reference ");
try
{
string[] s1 = null;
int i1 = Array.LastIndexOf<string>(s1, "", 1, 0);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: Set the negative startIndex argument");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Mary",
"Joan"};
int i1 = Array.LastIndexOf<string>(s1, "", -1, 3);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: Set the startIndex greater than the max index of the array");
try
{
int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 };
int i2 = Array.LastIndexOf<int>(i1, 56, 6, 3);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: Count argument is less than zero");
try
{
int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 };
int i2 = Array.LastIndexOf<int>(i1, 56, 3, -3);
TestLibrary.TestFramework.LogError("107", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: Count argument do not specify a valid section in array");
try
{
int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 };
int i2 = Array.LastIndexOf<int>(i1, 56, 3, 5);
TestLibrary.TestFramework.LogError("109", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArrayIndexOf3 test = new ArrayIndexOf3();
TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Microsoft.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
namespace Microsoft.Xml.XPath
{
using System;
using Microsoft.Xml;
/// <summary>
/// Reader that traverses the subtree rooted at the current position of the specified navigator.
/// </summary>
internal class XPathNavigatorReader : XmlReader, IXmlNamespaceResolver
{
private enum State
{
Initial,
Content,
EndElement,
Attribute,
AttrVal,
InReadBinary,
EOF,
Closed,
Error,
}
private XPathNavigator _nav;
private XPathNavigator _navToRead;
private int _depth;
private State _state;
private XmlNodeType _nodeType;
private int _attrCount;
private bool _readEntireDocument;
protected IXmlLineInfo lineInfo;
protected IXmlSchemaInfo schemaInfo;
private ReadContentAsBinaryHelper _readBinaryHelper;
private State _savedState;
internal const string space = "space";
internal static XmlNodeType[] convertFromXPathNodeType = {
XmlNodeType.Document, // XPathNodeType.Root
XmlNodeType.Element, // XPathNodeType.Element
XmlNodeType.Attribute, // XPathNodeType.Attribute
XmlNodeType.Attribute, // XPathNodeType.Namespace
XmlNodeType.Text, // XPathNodeType.Text
XmlNodeType.SignificantWhitespace, // XPathNodeType.SignificantWhitespace
XmlNodeType.Whitespace, // XPathNodeType.Whitespace
XmlNodeType.ProcessingInstruction, // XPathNodeType.ProcessingInstruction
XmlNodeType.Comment, // XPathNodeType.Comment
XmlNodeType.None // XPathNodeType.All
};
/// <summary>
/// Translates an XPathNodeType value into the corresponding XmlNodeType value.
/// XPathNodeType.Whitespace and XPathNodeType.SignificantWhitespace are mapped into XmlNodeType.Text.
/// </summary>
internal static XmlNodeType ToXmlNodeType(XPathNodeType typ)
{
return XPathNavigatorReader.convertFromXPathNodeType[(int)typ];
}
internal object UnderlyingObject
{
get
{
return _nav.UnderlyingObject;
}
}
static public XPathNavigatorReader Create(XPathNavigator navToRead)
{
XPathNavigator nav = navToRead.Clone();
IXmlLineInfo xli = nav as IXmlLineInfo;
IXmlSchemaInfo xsi = nav as IXmlSchemaInfo;
#if NAVREADER_SUPPORTSLINEINFO
if (null == xsi) {
if (null == xli) {
return new XPathNavigatorReader(nav, xli, xsi);
}
else {
return new XPathNavigatorReaderWithLI(nav, xli, xsi);
}
}
else {
if (null == xli) {
return new XPathNavigatorReaderWithSI(nav, xli, xsi);
}
else {
return new XPathNavigatorReaderWithLIAndSI(nav, xli, xsi);
}
}
#else
if (null == xsi)
{
return new XPathNavigatorReader(nav, xli, xsi);
}
else
{
return new XPathNavigatorReaderWithSI(nav, xli, xsi);
}
#endif
}
protected XPathNavigatorReader(XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi)
{
// Need clone that can be moved independently of original navigator
_navToRead = navToRead;
this.lineInfo = xli;
this.schemaInfo = xsi;
_nav = XmlEmptyNavigator.Singleton;
_state = State.Initial;
_depth = 0;
_nodeType = XPathNavigatorReader.ToXmlNodeType(_nav.NodeType);
}
protected bool IsReading
{
get { return _state > State.Initial && _state < State.EOF; }
}
internal override XmlNamespaceManager NamespaceManager
{
get { return XPathNavigator.GetNamespaces(this); }
}
//-----------------------------------------------
// IXmlNamespaceResolver -- pass through to Navigator
//-----------------------------------------------
public override XmlNameTable NameTable
{
get
{
return _navToRead.NameTable;
}
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return _nav.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _nav.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _nav.LookupPrefix(namespaceName);
}
//-----------------------------------------------
// XmlReader -- pass through to Navigator
//-----------------------------------------------
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.NameTable = this.NameTable;
rs.ConformanceLevel = ConformanceLevel.Fragment;
rs.CheckCharacters = false;
rs.ReadOnly = true;
return rs;
}
}
public override IXmlSchemaInfo SchemaInfo
{
get
{
// Special case attribute text (this.nav points to attribute even though current state is Text)
if (_nodeType == XmlNodeType.Text)
return null;
return _nav.SchemaInfo;
}
}
public override System.Type ValueType
{
get { return _nav.ValueType; }
}
public override XmlNodeType NodeType
{
get { return _nodeType; }
}
public override string NamespaceURI
{
get
{
//NamespaceUri for namespace nodes is different in case of XPathNavigator and Reader
if (_nav.NodeType == XPathNodeType.Namespace)
return this.NameTable.Add(XmlReservedNs.NsXmlNs);
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.NamespaceURI;
}
}
public override string LocalName
{
get
{
//Default namespace in case of reader has a local name value of 'xmlns'
if (_nav.NodeType == XPathNodeType.Namespace && _nav.LocalName.Length == 0)
return this.NameTable.Add("xmlns");
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.LocalName;
}
}
public override string Prefix
{
get
{
//Prefix for namespace nodes is different in case of XPathNavigator and Reader
if (_nav.NodeType == XPathNodeType.Namespace && _nav.LocalName.Length != 0)
return this.NameTable.Add("xmlns");
//Special case attribute text node
if (this.NodeType == XmlNodeType.Text)
return string.Empty;
return _nav.Prefix;
}
}
public override string BaseURI
{
get
{
//reader returns BaseUri even before read method is called.
if (_state == State.Initial)
return _navToRead.BaseURI;
return _nav.BaseURI;
}
}
public override bool IsEmptyElement
{
get
{
return _nav.IsEmptyElement;
}
}
public override XmlSpace XmlSpace
{
get
{
XPathNavigator tempNav = _nav.Clone();
do
{
if (tempNav.MoveToAttribute(XPathNavigatorReader.space, XmlReservedNs.NsXml))
{
switch (XmlConvert.TrimString(tempNav.Value))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
break;
}
tempNav.MoveToParent();
}
}
while (tempNav.MoveToParent());
return XmlSpace.None;
}
}
public override string XmlLang
{
get
{
return _nav.XmlLang;
}
}
public override bool HasValue
{
get
{
if ((_nodeType != XmlNodeType.Element)
&& (_nodeType != XmlNodeType.Document)
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.None))
return true;
return false;
}
}
public override string Value
{
get
{
if ((_nodeType != XmlNodeType.Element)
&& (_nodeType != XmlNodeType.Document)
&& (_nodeType != XmlNodeType.EndElement)
&& (_nodeType != XmlNodeType.None))
return _nav.Value;
return string.Empty;
}
}
private XPathNavigator GetElemNav()
{
XPathNavigator tempNav;
switch (_state)
{
case State.Content:
return _nav.Clone();
case State.Attribute:
case State.AttrVal:
tempNav = _nav.Clone();
if (tempNav.MoveToParent())
return tempNav;
break;
case State.InReadBinary:
_state = _savedState;
XPathNavigator nav = GetElemNav();
_state = State.InReadBinary;
return nav;
}
return null;
}
private XPathNavigator GetElemNav(out int depth)
{
XPathNavigator nav = null;
switch (_state)
{
case State.Content:
if (_nodeType == XmlNodeType.Element)
nav = _nav.Clone();
depth = _depth;
break;
case State.Attribute:
nav = _nav.Clone();
nav.MoveToParent();
depth = _depth - 1;
break;
case State.AttrVal:
nav = _nav.Clone();
nav.MoveToParent();
depth = _depth - 2;
break;
case State.InReadBinary:
_state = _savedState;
nav = GetElemNav(out depth);
_state = State.InReadBinary;
break;
default:
depth = _depth;
break;
}
return nav;
}
private void MoveToAttr(XPathNavigator nav, int depth)
{
_nav.MoveTo(nav);
_depth = depth;
_nodeType = XmlNodeType.Attribute;
_state = State.Attribute;
}
public override int AttributeCount
{
get
{
if (_attrCount < 0)
{
// attribute count works for element, regardless of where you are in start tag
XPathNavigator tempNav = GetElemNav();
int count = 0;
if (null != tempNav)
{
if (tempNav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
count++;
} while (tempNav.MoveToNextNamespace((XPathNamespaceScope.Local)));
tempNav.MoveToParent();
}
if (tempNav.MoveToFirstAttribute())
{
do
{
count++;
} while (tempNav.MoveToNextAttribute());
}
}
_attrCount = count;
}
return _attrCount;
}
}
public override string GetAttribute(string name)
{
// reader allows calling GetAttribute, even when positioned inside attributes
XPathNavigator nav = _nav;
switch (nav.NodeType)
{
case XPathNodeType.Element:
break;
case XPathNodeType.Attribute:
nav = nav.Clone();
if (!nav.MoveToParent())
return null;
break;
default:
return null;
}
string prefix, localname;
ValidateNames.SplitQName(name, out prefix, out localname);
if (0 == prefix.Length)
{
if (localname == "xmlns")
return nav.GetNamespace(string.Empty);
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToAttribute(localname, string.Empty))
return nav.Value;
}
else
{
if (prefix == "xmlns")
return nav.GetNamespace(localname);
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToFirstAttribute())
{
do
{
if (nav.LocalName == localname && nav.Prefix == prefix)
return nav.Value;
} while (nav.MoveToNextAttribute());
}
}
return null;
}
public override string GetAttribute(string localName, string namespaceURI)
{
if (null == localName)
throw new ArgumentNullException("localName");
// reader allows calling GetAttribute, even when positioned inside attributes
XPathNavigator nav = _nav;
switch (nav.NodeType)
{
case XPathNodeType.Element:
break;
case XPathNodeType.Attribute:
nav = nav.Clone();
if (!nav.MoveToParent())
return null;
break;
default:
return null;
}
// are they really looking for a namespace-decl?
if (namespaceURI == XmlReservedNs.NsXmlNs)
{
if (localName == "xmlns")
localName = string.Empty;
return nav.GetNamespace(localName);
}
if (null == namespaceURI)
namespaceURI = string.Empty;
// We need to clone the navigator and move the clone to the attribute to see whether the attribute exists,
// because XPathNavigator.GetAttribute return string.Empty for both when the the attribute is not there or when
// it has an empty value. XmlReader.GetAttribute must return null if the attribute does not exist.
if ((object)nav == (object)_nav)
nav = nav.Clone();
if (nav.MoveToAttribute(localName, namespaceURI))
{
return nav.Value;
}
else
{
return null;
}
}
private static string GetNamespaceByIndex(XPathNavigator nav, int index, out int count)
{
string thisValue = nav.Value;
string value = null;
if (nav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
value = GetNamespaceByIndex(nav, index, out count);
}
else
{
count = 0;
}
if (count == index)
{
Debug.Assert(value == null);
value = thisValue;
}
count++;
return value;
}
public override string GetAttribute(int index)
{
if (index < 0)
goto Error;
XPathNavigator nav = GetElemNav();
if (null == nav)
goto Error;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
// namespaces are returned in reverse order,
// but we want to return them in the correct order,
// so first count the namespaces
int nsCount;
string value = GetNamespaceByIndex(nav, index, out nsCount);
if (null != value)
{
return value;
}
index -= nsCount;
nav.MoveToParent();
}
if (nav.MoveToFirstAttribute())
{
do
{
if (index == 0)
return nav.Value;
index--;
} while (nav.MoveToNextAttribute());
}
// can't find it... error
Error:
throw new ArgumentOutOfRangeException("index");
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
if (null == localName)
throw new ArgumentNullException("localName");
int depth = _depth;
XPathNavigator nav = GetElemNav(out depth);
if (null != nav)
{
if (namespaceName == XmlReservedNs.NsXmlNs)
{
if (localName == "xmlns")
localName = string.Empty;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
if (nav.LocalName == localName)
goto FoundMatch;
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
else
{
if (null == namespaceName)
namespaceName = string.Empty;
if (nav.MoveToAttribute(localName, namespaceName))
goto FoundMatch;
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToFirstAttribute()
{
int depth;
XPathNavigator nav = GetElemNav(out depth);
if (null != nav)
{
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
// attributes are in reverse order
while (nav.MoveToNextNamespace(XPathNamespaceScope.Local))
;
goto FoundMatch;
}
if (nav.MoveToFirstAttribute())
{
goto FoundMatch;
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToNextAttribute()
{
switch (_state)
{
case State.Content:
return MoveToFirstAttribute();
case State.Attribute:
{
if (XPathNodeType.Attribute == _nav.NodeType)
return _nav.MoveToNextAttribute();
// otherwise it is on a namespace... namespace are in reverse order
Debug.Assert(XPathNodeType.Namespace == _nav.NodeType);
XPathNavigator nav = _nav.Clone();
if (!nav.MoveToParent())
return false; // shouldn't happen
if (!nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
return false; // shouldn't happen
if (nav.IsSamePosition(_nav))
{
// this was the last one... start walking attributes
nav.MoveToParent();
if (!nav.MoveToFirstAttribute())
return false;
// otherwise we are there
_nav.MoveTo(nav);
return true;
}
else
{
XPathNavigator prev = nav.Clone();
for (; ; )
{
if (!nav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
Debug.Fail("Couldn't find Namespace Node! Should not happen!");
return false;
}
if (nav.IsSamePosition(_nav))
{
_nav.MoveTo(prev);
return true;
}
prev.MoveTo(nav);
}
// found previous namespace position
}
}
case State.AttrVal:
_depth--;
_state = State.Attribute;
if (!MoveToNextAttribute())
{
_depth++;
_state = State.AttrVal;
return false;
}
_nodeType = XmlNodeType.Attribute;
return true;
case State.InReadBinary:
_state = _savedState;
if (!MoveToNextAttribute())
{
_state = State.InReadBinary;
return false;
}
_readBinaryHelper.Finish();
return true;
default:
return false;
}
}
public override bool MoveToAttribute(string name)
{
int depth;
XPathNavigator nav = GetElemNav(out depth);
if (null == nav)
return false;
string prefix, localname;
ValidateNames.SplitQName(name, out prefix, out localname);
// watch for a namespace name
bool IsXmlnsNoPrefix = false;
if ((IsXmlnsNoPrefix = (0 == prefix.Length && localname == "xmlns"))
|| (prefix == "xmlns"))
{
if (IsXmlnsNoPrefix)
localname = string.Empty;
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
if (nav.LocalName == localname)
goto FoundMatch;
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
else if (0 == prefix.Length)
{
// the empty prefix always means empty namespaceUri for attributes
if (nav.MoveToAttribute(localname, string.Empty))
goto FoundMatch;
}
else
{
if (nav.MoveToFirstAttribute())
{
do
{
if (nav.LocalName == localname && nav.Prefix == prefix)
goto FoundMatch;
} while (nav.MoveToNextAttribute());
}
}
return false;
FoundMatch:
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
MoveToAttr(nav, depth + 1);
return true;
}
public override bool MoveToElement()
{
switch (_state)
{
case State.Attribute:
case State.AttrVal:
if (!_nav.MoveToParent())
return false;
_depth--;
if (_state == State.AttrVal)
_depth--;
_state = State.Content;
_nodeType = XmlNodeType.Element;
return true;
case State.InReadBinary:
_state = _savedState;
if (!MoveToElement())
{
_state = State.InReadBinary;
return false;
}
_readBinaryHelper.Finish();
break;
}
return false;
}
public override bool EOF
{
get
{
return _state == State.EOF;
}
}
public override ReadState ReadState
{
get
{
switch (_state)
{
case State.Initial:
return ReadState.Initial;
case State.Content:
case State.EndElement:
case State.Attribute:
case State.AttrVal:
case State.InReadBinary:
return ReadState.Interactive;
case State.EOF:
return ReadState.EndOfFile;
case State.Closed:
return ReadState.Closed;
default:
return ReadState.Error;
}
}
}
public override void ResolveEntity()
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
public override bool ReadAttributeValue()
{
if (_state == State.InReadBinary)
{
_readBinaryHelper.Finish();
_state = _savedState;
}
if (_state == State.Attribute)
{
_state = State.AttrVal;
_nodeType = XmlNodeType.Text;
_depth++;
return true;
}
return false;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_state != State.InReadBinary)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _state;
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
_state = _savedState;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// turn on InReadBinary state again and return
_savedState = _state;
_state = State.InReadBinary;
return readCount;
}
public override string LookupNamespace(string prefix)
{
return _nav.LookupNamespace(prefix);
}
/// <summary>
/// Current depth in subtree.
/// </summary>
public override int Depth
{
get { return _depth; }
}
/// <summary>
/// Move to the next reader state. Return false if that is ReaderState.Closed.
/// </summary>
public override bool Read()
{
_attrCount = -1;
switch (_state)
{
case State.Error:
case State.Closed:
case State.EOF:
return false;
case State.Initial:
// Starting state depends on the navigator's item type
_nav = _navToRead;
_state = State.Content;
if (XPathNodeType.Root == _nav.NodeType)
{
if (!_nav.MoveToFirstChild())
{
SetEOF();
return false;
}
_readEntireDocument = true;
}
else if (XPathNodeType.Attribute == _nav.NodeType)
{
_state = State.Attribute;
}
_nodeType = ToXmlNodeType(_nav.NodeType);
break;
case State.Content:
if (_nav.MoveToFirstChild())
{
_nodeType = ToXmlNodeType(_nav.NodeType);
_depth++;
_state = State.Content;
}
else if (_nodeType == XmlNodeType.Element
&& !_nav.IsEmptyElement)
{
_nodeType = XmlNodeType.EndElement;
_state = State.EndElement;
}
else
goto case State.EndElement;
break;
case State.EndElement:
if (0 == _depth && !_readEntireDocument)
{
SetEOF();
return false;
}
else if (_nav.MoveToNext())
{
_nodeType = ToXmlNodeType(_nav.NodeType);
_state = State.Content;
}
else if (_depth > 0 && _nav.MoveToParent())
{
Debug.Assert(_nav.NodeType == XPathNodeType.Element, _nav.NodeType.ToString() + " == XPathNodeType.Element");
_nodeType = XmlNodeType.EndElement;
_state = State.EndElement;
_depth--;
}
else
{
SetEOF();
return false;
}
break;
case State.Attribute:
case State.AttrVal:
if (!_nav.MoveToParent())
{
SetEOF();
return false;
}
_nodeType = ToXmlNodeType(_nav.NodeType);
_depth--;
if (_state == State.AttrVal)
_depth--;
goto case State.Content;
case State.InReadBinary:
_state = _savedState;
_readBinaryHelper.Finish();
return Read();
}
return true;
}
/// <summary>
/// End reading by transitioning into the Closed state.
/// </summary>
public override void Close()
{
_nav = XmlEmptyNavigator.Singleton;
_nodeType = XmlNodeType.None;
_state = State.Closed;
_depth = 0;
}
/// <summary>
/// set reader to EOF state
/// </summary>
private void SetEOF()
{
_nav = XmlEmptyNavigator.Singleton;
_nodeType = XmlNodeType.None;
_state = State.EOF;
_depth = 0;
}
}
#if NAVREADER_SUPPORTSLINEINFO
internal class XPathNavigatorReaderWithLI : XPathNavigatorReader, Microsoft.Xml.IXmlLineInfo {
internal XPathNavigatorReaderWithLI( XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi )
: base( navToRead, xli, xsi ) {
}
//-----------------------------------------------
// IXmlLineInfo
//-----------------------------------------------
public virtual bool HasLineInfo() { return IsReading ? this.lineInfo.HasLineInfo() : false; }
public virtual int LineNumber { get { return IsReading ? this.lineInfo.LineNumber : 0; } }
public virtual int LinePosition { get { return IsReading ? this.lineInfo.LinePosition : 0; } }
}
internal class XPathNavigatorReaderWithLIAndSI : XPathNavigatorReaderWithLI, Microsoft.Xml.IXmlLineInfo, Microsoft.Xml.Schema.IXmlSchemaInfo {
internal XPathNavigatorReaderWithLIAndSI( XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi )
: base( navToRead, xli, xsi ) {
}
//-----------------------------------------------
// IXmlSchemaInfo
//-----------------------------------------------
public virtual XmlSchemaValidity Validity { get { return IsReading ? this.schemaInfo.Validity : XmlSchemaValidity.NotKnown; } }
public override bool IsDefault { get { return IsReading ? this.schemaInfo.IsDefault : false; } }
public virtual bool IsNil { get { return IsReading ? this.schemaInfo.IsNil : false; } }
public virtual XmlSchemaSimpleType MemberType { get { return IsReading ? this.schemaInfo.MemberType : null; } }
public virtual XmlSchemaType SchemaType { get { return IsReading ? this.schemaInfo.SchemaType : null; } }
public virtual XmlSchemaElement SchemaElement { get { return IsReading ? this.schemaInfo.SchemaElement : null; } }
public virtual XmlSchemaAttribute SchemaAttribute { get { return IsReading ? this.schemaInfo.SchemaAttribute : null; } }
}
#endif
internal class XPathNavigatorReaderWithSI : XPathNavigatorReader, Microsoft.Xml.Schema.IXmlSchemaInfo
{
internal XPathNavigatorReaderWithSI(XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi)
: base(navToRead, xli, xsi)
{
}
//-----------------------------------------------
// IXmlSchemaInfo
//-----------------------------------------------
public virtual XmlSchemaValidity Validity { get { return IsReading ? this.schemaInfo.Validity : XmlSchemaValidity.NotKnown; } }
public override bool IsDefault { get { return IsReading ? this.schemaInfo.IsDefault : false; } }
public virtual bool IsNil { get { return IsReading ? this.schemaInfo.IsNil : false; } }
public virtual XmlSchemaSimpleType MemberType { get { return IsReading ? this.schemaInfo.MemberType : null; } }
public virtual XmlSchemaType SchemaType { get { return IsReading ? this.schemaInfo.SchemaType : null; } }
public virtual XmlSchemaElement SchemaElement { get { return IsReading ? this.schemaInfo.SchemaElement : null; } }
public virtual XmlSchemaAttribute SchemaAttribute { get { return IsReading ? this.schemaInfo.SchemaAttribute : null; } }
}
/// <summary>
/// The XmlEmptyNavigator exposes a document node with no children.
/// Only one XmlEmptyNavigator exists per AppDomain (Singleton). That's why the constructor is private.
/// Use the Singleton property to get the EmptyNavigator.
/// </summary>
internal class XmlEmptyNavigator : XPathNavigator
{
private static volatile XmlEmptyNavigator s_singleton;
private XmlEmptyNavigator()
{
}
public static XmlEmptyNavigator Singleton
{
get
{
if (XmlEmptyNavigator.s_singleton == null)
XmlEmptyNavigator.s_singleton = new XmlEmptyNavigator();
return XmlEmptyNavigator.s_singleton;
}
}
//-----------------------------------------------
// XmlReader
//-----------------------------------------------
public override XPathNodeType NodeType
{
get { return XPathNodeType.All; }
}
public override string NamespaceURI
{
get { return string.Empty; }
}
public override string LocalName
{
get { return string.Empty; }
}
public override string Name
{
get { return string.Empty; }
}
public override string Prefix
{
get { return string.Empty; }
}
public override string BaseURI
{
get { return string.Empty; }
}
public override string Value
{
get { return string.Empty; }
}
public override bool IsEmptyElement
{
get { return false; }
}
public override string XmlLang
{
get { return string.Empty; }
}
public override bool HasAttributes
{
get { return false; }
}
public override bool HasChildren
{
get { return false; }
}
//-----------------------------------------------
// IXmlNamespaceResolver
//-----------------------------------------------
public override XmlNameTable NameTable
{
get { return new NameTable(); }
}
public override bool MoveToFirstChild()
{
return false;
}
public override void MoveToRoot()
{
//always on root
return;
}
public override bool MoveToNext()
{
return false;
}
public override bool MoveToPrevious()
{
return false;
}
public override bool MoveToFirst()
{
return false;
}
public override bool MoveToFirstAttribute()
{
return false;
}
public override bool MoveToNextAttribute()
{
return false;
}
public override bool MoveToId(string id)
{
return false;
}
public override string GetAttribute(string localName, string namespaceName)
{
return null;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
return false;
}
public override string GetNamespace(string name)
{
return null;
}
public override bool MoveToNamespace(string prefix)
{
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
return false;
}
public override bool MoveToParent()
{
return false;
}
public override bool MoveTo(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return (object)this == (object)other;
}
public override XmlNodeOrder ComparePosition(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return ((object)this == (object)other) ? XmlNodeOrder.Same : XmlNodeOrder.Unknown;
}
public override bool IsSamePosition(XPathNavigator other)
{
// Only one instance of XmlEmptyNavigator exists on the system
return (object)this == (object)other;
}
//-----------------------------------------------
// XPathNavigator2
//-----------------------------------------------
public override XPathNavigator Clone()
{
// Singleton, so clone just returns this
return this;
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.V2.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Dialogflow.V2;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedIntentsClientSnippets
{
/// <summary>Snippet for ListIntentsAsync</summary>
public async Task ListIntentsAsync1()
{
// Snippet: ListIntentsAsync(ProjectAgentName,string,int?,CallSettings)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Intent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIntents</summary>
public void ListIntents1()
{
// Snippet: ListIntents(ProjectAgentName,string,int?,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
// Make the request
PagedEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntents(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Intent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListIntentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIntentsAsync</summary>
public async Task ListIntentsAsync2()
{
// Snippet: ListIntentsAsync(ProjectAgentName,string,string,int?,CallSettings)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
string languageCode = "";
// Make the request
PagedAsyncEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntentsAsync(parent: parent, languageCode: languageCode);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Intent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIntents</summary>
public void ListIntents2()
{
// Snippet: ListIntents(ProjectAgentName,string,string,int?,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
string languageCode = "";
// Make the request
PagedEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntents(parent: parent, languageCode: languageCode);
// Iterate over all response items, lazily performing RPCs as required
foreach (Intent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListIntentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIntentsAsync</summary>
public async Task ListIntentsAsync_RequestObject()
{
// Snippet: ListIntentsAsync(ListIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ListIntentsRequest request = new ListIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Intent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListIntents</summary>
public void ListIntents_RequestObject()
{
// Snippet: ListIntents(ListIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ListIntentsRequest request = new ListIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListIntentsResponse, Intent> response =
intentsClient.ListIntents(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Intent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListIntentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Intent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Intent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Intent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetIntentAsync</summary>
public async Task GetIntentAsync1()
{
// Snippet: GetIntentAsync(IntentName,CallSettings)
// Additional: GetIntentAsync(IntentName,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
// Make the request
Intent response = await intentsClient.GetIntentAsync(name);
// End snippet
}
/// <summary>Snippet for GetIntent</summary>
public void GetIntent1()
{
// Snippet: GetIntent(IntentName,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
// Make the request
Intent response = intentsClient.GetIntent(name);
// End snippet
}
/// <summary>Snippet for GetIntentAsync</summary>
public async Task GetIntentAsync2()
{
// Snippet: GetIntentAsync(IntentName,string,CallSettings)
// Additional: GetIntentAsync(IntentName,string,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
string languageCode = "";
// Make the request
Intent response = await intentsClient.GetIntentAsync(name, languageCode);
// End snippet
}
/// <summary>Snippet for GetIntent</summary>
public void GetIntent2()
{
// Snippet: GetIntent(IntentName,string,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
string languageCode = "";
// Make the request
Intent response = intentsClient.GetIntent(name, languageCode);
// End snippet
}
/// <summary>Snippet for GetIntentAsync</summary>
public async Task GetIntentAsync_RequestObject()
{
// Snippet: GetIntentAsync(GetIntentRequest,CallSettings)
// Additional: GetIntentAsync(GetIntentRequest,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
GetIntentRequest request = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
// Make the request
Intent response = await intentsClient.GetIntentAsync(request);
// End snippet
}
/// <summary>Snippet for GetIntent</summary>
public void GetIntent_RequestObject()
{
// Snippet: GetIntent(GetIntentRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
GetIntentRequest request = new GetIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
// Make the request
Intent response = intentsClient.GetIntent(request);
// End snippet
}
/// <summary>Snippet for CreateIntentAsync</summary>
public async Task CreateIntentAsync1()
{
// Snippet: CreateIntentAsync(ProjectAgentName,Intent,CallSettings)
// Additional: CreateIntentAsync(ProjectAgentName,Intent,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
// Make the request
Intent response = await intentsClient.CreateIntentAsync(parent, intent);
// End snippet
}
/// <summary>Snippet for CreateIntent</summary>
public void CreateIntent1()
{
// Snippet: CreateIntent(ProjectAgentName,Intent,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
// Make the request
Intent response = intentsClient.CreateIntent(parent, intent);
// End snippet
}
/// <summary>Snippet for CreateIntentAsync</summary>
public async Task CreateIntentAsync2()
{
// Snippet: CreateIntentAsync(ProjectAgentName,Intent,string,CallSettings)
// Additional: CreateIntentAsync(ProjectAgentName,Intent,string,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
string languageCode = "";
// Make the request
Intent response = await intentsClient.CreateIntentAsync(parent, intent, languageCode);
// End snippet
}
/// <summary>Snippet for CreateIntent</summary>
public void CreateIntent2()
{
// Snippet: CreateIntent(ProjectAgentName,Intent,string,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
Intent intent = new Intent();
string languageCode = "";
// Make the request
Intent response = intentsClient.CreateIntent(parent, intent, languageCode);
// End snippet
}
/// <summary>Snippet for CreateIntentAsync</summary>
public async Task CreateIntentAsync_RequestObject()
{
// Snippet: CreateIntentAsync(CreateIntentRequest,CallSettings)
// Additional: CreateIntentAsync(CreateIntentRequest,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
CreateIntentRequest request = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
// Make the request
Intent response = await intentsClient.CreateIntentAsync(request);
// End snippet
}
/// <summary>Snippet for CreateIntent</summary>
public void CreateIntent_RequestObject()
{
// Snippet: CreateIntent(CreateIntentRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
CreateIntentRequest request = new CreateIntentRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intent = new Intent(),
};
// Make the request
Intent response = intentsClient.CreateIntent(request);
// End snippet
}
/// <summary>Snippet for UpdateIntentAsync</summary>
public async Task UpdateIntentAsync1()
{
// Snippet: UpdateIntentAsync(Intent,string,CallSettings)
// Additional: UpdateIntentAsync(Intent,string,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
Intent intent = new Intent();
string languageCode = "";
// Make the request
Intent response = await intentsClient.UpdateIntentAsync(intent, languageCode);
// End snippet
}
/// <summary>Snippet for UpdateIntent</summary>
public void UpdateIntent1()
{
// Snippet: UpdateIntent(Intent,string,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
Intent intent = new Intent();
string languageCode = "";
// Make the request
Intent response = intentsClient.UpdateIntent(intent, languageCode);
// End snippet
}
/// <summary>Snippet for UpdateIntentAsync</summary>
public async Task UpdateIntentAsync2()
{
// Snippet: UpdateIntentAsync(Intent,string,FieldMask,CallSettings)
// Additional: UpdateIntentAsync(Intent,string,FieldMask,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
Intent intent = new Intent();
string languageCode = "";
FieldMask updateMask = new FieldMask();
// Make the request
Intent response = await intentsClient.UpdateIntentAsync(intent, languageCode, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateIntent</summary>
public void UpdateIntent2()
{
// Snippet: UpdateIntent(Intent,string,FieldMask,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
Intent intent = new Intent();
string languageCode = "";
FieldMask updateMask = new FieldMask();
// Make the request
Intent response = intentsClient.UpdateIntent(intent, languageCode, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateIntentAsync</summary>
public async Task UpdateIntentAsync_RequestObject()
{
// Snippet: UpdateIntentAsync(UpdateIntentRequest,CallSettings)
// Additional: UpdateIntentAsync(UpdateIntentRequest,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
UpdateIntentRequest request = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "",
};
// Make the request
Intent response = await intentsClient.UpdateIntentAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateIntent</summary>
public void UpdateIntent_RequestObject()
{
// Snippet: UpdateIntent(UpdateIntentRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
UpdateIntentRequest request = new UpdateIntentRequest
{
Intent = new Intent(),
LanguageCode = "",
};
// Make the request
Intent response = intentsClient.UpdateIntent(request);
// End snippet
}
/// <summary>Snippet for DeleteIntentAsync</summary>
public async Task DeleteIntentAsync()
{
// Snippet: DeleteIntentAsync(IntentName,CallSettings)
// Additional: DeleteIntentAsync(IntentName,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
// Make the request
await intentsClient.DeleteIntentAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteIntent</summary>
public void DeleteIntent()
{
// Snippet: DeleteIntent(IntentName,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
IntentName name = new IntentName("[PROJECT]", "[INTENT]");
// Make the request
intentsClient.DeleteIntent(name);
// End snippet
}
/// <summary>Snippet for DeleteIntentAsync</summary>
public async Task DeleteIntentAsync_RequestObject()
{
// Snippet: DeleteIntentAsync(DeleteIntentRequest,CallSettings)
// Additional: DeleteIntentAsync(DeleteIntentRequest,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
DeleteIntentRequest request = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
// Make the request
await intentsClient.DeleteIntentAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteIntent</summary>
public void DeleteIntent_RequestObject()
{
// Snippet: DeleteIntent(DeleteIntentRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
DeleteIntentRequest request = new DeleteIntentRequest
{
IntentName = new IntentName("[PROJECT]", "[INTENT]"),
};
// Make the request
intentsClient.DeleteIntent(request);
// End snippet
}
/// <summary>Snippet for BatchUpdateIntentsAsync</summary>
public async Task BatchUpdateIntentsAsync_RequestObject()
{
// Snippet: BatchUpdateIntentsAsync(BatchUpdateIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
BatchUpdateIntentsRequest request = new BatchUpdateIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
LanguageCode = "",
};
// Make the request
Operation<BatchUpdateIntentsResponse, Struct> response =
await intentsClient.BatchUpdateIntentsAsync(request);
// Poll until the returned long-running operation is complete
Operation<BatchUpdateIntentsResponse, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
BatchUpdateIntentsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchUpdateIntentsResponse, Struct> retrievedResponse =
await intentsClient.PollOnceBatchUpdateIntentsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchUpdateIntentsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchUpdateIntents</summary>
public void BatchUpdateIntents_RequestObject()
{
// Snippet: BatchUpdateIntents(BatchUpdateIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
BatchUpdateIntentsRequest request = new BatchUpdateIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
LanguageCode = "",
};
// Make the request
Operation<BatchUpdateIntentsResponse, Struct> response =
intentsClient.BatchUpdateIntents(request);
// Poll until the returned long-running operation is complete
Operation<BatchUpdateIntentsResponse, Struct> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
BatchUpdateIntentsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<BatchUpdateIntentsResponse, Struct> retrievedResponse =
intentsClient.PollOnceBatchUpdateIntents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
BatchUpdateIntentsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for BatchDeleteIntentsAsync</summary>
public async Task BatchDeleteIntentsAsync()
{
// Snippet: BatchDeleteIntentsAsync(ProjectAgentName,IEnumerable<Intent>,CallSettings)
// Additional: BatchDeleteIntentsAsync(ProjectAgentName,IEnumerable<Intent>,CancellationToken)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
IEnumerable<Intent> intents = new List<Intent>();
// Make the request
Operation<Empty, Struct> response =
await intentsClient.BatchDeleteIntentsAsync(parent, intents);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await intentsClient.PollOnceBatchDeleteIntentsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for BatchDeleteIntents</summary>
public void BatchDeleteIntents()
{
// Snippet: BatchDeleteIntents(ProjectAgentName,IEnumerable<Intent>,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
ProjectAgentName parent = new ProjectAgentName("[PROJECT]");
IEnumerable<Intent> intents = new List<Intent>();
// Make the request
Operation<Empty, Struct> response =
intentsClient.BatchDeleteIntents(parent, intents);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
intentsClient.PollOnceBatchDeleteIntents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for BatchDeleteIntentsAsync</summary>
public async Task BatchDeleteIntentsAsync_RequestObject()
{
// Snippet: BatchDeleteIntentsAsync(BatchDeleteIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = await IntentsClient.CreateAsync();
// Initialize request argument(s)
BatchDeleteIntentsRequest request = new BatchDeleteIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intents = { },
};
// Make the request
Operation<Empty, Struct> response =
await intentsClient.BatchDeleteIntentsAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await intentsClient.PollOnceBatchDeleteIntentsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for BatchDeleteIntents</summary>
public void BatchDeleteIntents_RequestObject()
{
// Snippet: BatchDeleteIntents(BatchDeleteIntentsRequest,CallSettings)
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
BatchDeleteIntentsRequest request = new BatchDeleteIntentsRequest
{
ParentAsProjectAgentName = new ProjectAgentName("[PROJECT]"),
Intents = { },
};
// Make the request
Operation<Empty, Struct> response =
intentsClient.BatchDeleteIntents(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
intentsClient.PollOnceBatchDeleteIntents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("2D Toolkit/Backend/tk2dBaseSprite")]
/// <summary>
/// Sprite base class. Performs target agnostic functionality and manages state parameters.
/// </summary>
public abstract class tk2dBaseSprite : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild
{
/// <summary>
/// Anchor.
/// NOTE: The order in this enum is deliberate, to initialize at LowerLeft for backwards compatibility.
/// This is also the reason it is local here. Other Anchor enums are NOT compatbile. Do not cast.
/// </summary>
public enum Anchor
{
/// <summary>Lower left</summary>
LowerLeft,
/// <summary>Lower center</summary>
LowerCenter,
/// <summary>Lower right</summary>
LowerRight,
/// <summary>Middle left</summary>
MiddleLeft,
/// <summary>Middle center</summary>
MiddleCenter,
/// <summary>Middle right</summary>
MiddleRight,
/// <summary>Upper left</summary>
UpperLeft,
/// <summary>Upper center</summary>
UpperCenter,
/// <summary>Upper right</summary>
UpperRight,
}
/// <summary>
/// This is now private. You should use <see cref="tk2dBaseSprite.Collection">Collection</see> if you wish to read this value.
/// Use <see cref="tk2dBaseSprite.SetSprite">SetSprite</see> when you need to switch sprite collection.
/// </summary>
[SerializeField]
private tk2dSpriteCollectionData collection;
/// <summary>
/// Deprecation warning: the set accessor will be removed in a future version.
/// Use <see cref="tk2dBaseSprite.SetSprite">SetSprite</see> when you need to switch sprite collection.
/// </summary>
public tk2dSpriteCollectionData Collection
{
get { return collection; }
set { collection = value; collectionInst = collection.inst; }
}
// This is the active instance of the sprite collection
protected tk2dSpriteCollectionData collectionInst;
[SerializeField] protected Color _color = Color.white;
[SerializeField] protected Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f);
[SerializeField] protected int _spriteId = 0;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
public BoxCollider2D boxCollider2D = null;
public List<PolygonCollider2D> polygonCollider2D = new List<PolygonCollider2D>(1);
public List<EdgeCollider2D> edgeCollider2D = new List<EdgeCollider2D>(1);
#endif
/// <summary>
/// Internal cached version of the box collider created for this sprite, if present.
/// </summary>
public BoxCollider boxCollider = null;
/// <summary>
/// Internal cached version of the mesh collider created for this sprite, if present.
/// </summary>
public MeshCollider meshCollider = null;
public Vector3[] meshColliderPositions = null;
public Mesh meshColliderMesh = null;
/// <summary>
/// This event is called whenever a sprite is changed.
/// A sprite is considered to be changed when the sprite itself
/// is changed, or the scale applied to the sprite is changed.
/// </summary>
public event System.Action<tk2dBaseSprite> SpriteChanged;
// This is unfortunate, but required due to the unpredictable script execution order in Unity.
// The only problem happens in Awake(), where if another class is Awaken before this one, and tries to
// modify this instance before it is initialized, very bad things could happen.
// Awake also never gets called on an object which is inactive.
void InitInstance()
{
if (collectionInst == null && collection != null)
collectionInst = collection.inst;
}
/// <summary>
/// Gets or sets the color.
/// </summary>
/// <value>
/// Please note the range for a Unity Color is 0..1 and not 0..255.
/// </value>
public Color color
{
get { return _color; }
set
{
if (value != _color)
{
_color = value;
InitInstance();
UpdateColors();
}
}
}
/// <summary>
/// Gets or sets the scale.
/// </summary>
/// <value>
/// Use the sprite scale method as opposed to transform.localScale to avoid breaking dynamic batching.
/// </value>
public Vector3 scale
{
get { return _scale; }
set
{
if (value != _scale)
{
_scale = value;
InitInstance();
UpdateVertices();
#if UNITY_EDITOR
EditMode__CreateCollider();
#else
UpdateCollider();
#endif
if (SpriteChanged != null) {
SpriteChanged( this );
}
}
}
}
Renderer _cachedRenderer = null;
Renderer CachedRenderer {
get {
if (_cachedRenderer == null) {
_cachedRenderer = renderer;
}
return _cachedRenderer;
}
}
[SerializeField] protected int renderLayer = 0;
/// <summary>
/// Gets or sets the sorting order
/// The sorting order lets you override draw order for sprites which are at the same z position
/// It is similar to offsetting in z - the sprite stays at the original position
/// This corresponds to the renderer.sortingOrder property in Unity 4.3
/// </summary>
public int SortingOrder {
get {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
return renderLayer;
#else
return CachedRenderer.sortingOrder;
#endif
}
set {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (renderLayer != value) {
renderLayer = value; InitInstance(); UpdateVertices();
}
#else
if (CachedRenderer.sortingOrder != value) {
renderLayer = value; // for awake
CachedRenderer.sortingOrder = value;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(CachedRenderer);
#endif
}
#endif
}
}
/// <summary>
/// Flips the sprite horizontally. Set FlipX to true to flip it horizontally.
/// Note: The sprite itself may be flipped by the hierarchy above it or localScale
/// These functions do not consider those cases.
/// </summary>
public bool FlipX {
get { return _scale.x < 0; }
set { scale = new Vector3( Mathf.Abs(_scale.x) * (value?-1:1), _scale.y, _scale.z ); }
}
/// <summary>
/// Flips the sprite vertically. Set FlipY to true to flip it vertically.
/// Note: The sprite itself may be flipped by the hierarchy above it or localScale
/// These functions do not consider those cases.
/// </summary>
public bool FlipY {
get { return _scale.y < 0; }
set { scale = new Vector3( _scale.x, Mathf.Abs(_scale.y) * (value?-1:1), _scale.z ); }
}
/// <summary>
/// Gets or sets the sprite identifier.
/// </summary>
/// <value>
/// The spriteId is a unique number identifying each sprite.
/// Use <see cref="tk2dBaseSprite.GetSpriteIdByName">GetSpriteIdByName</see> to resolve an identifier from the current sprite collection.
/// </value>
public int spriteId
{
get { return _spriteId; }
set
{
if (value != _spriteId)
{
InitInstance();
value = Mathf.Clamp(value, 0, collectionInst.spriteDefinitions.Length - 1);
if (_spriteId < 0 || _spriteId >= collectionInst.spriteDefinitions.Length ||
GetCurrentVertexCount() != collectionInst.spriteDefinitions[value].positions.Length ||
collectionInst.spriteDefinitions[_spriteId].complexGeometry != collectionInst.spriteDefinitions[value].complexGeometry)
{
_spriteId = value;
UpdateGeometry();
}
else
{
_spriteId = value;
UpdateVertices();
}
UpdateMaterial();
UpdateCollider();
if (SpriteChanged != null) {
SpriteChanged( this );
}
}
}
}
/// <summary>
/// Sets the sprite by identifier.
/// </summary>
public void SetSprite(int newSpriteId) {
this.spriteId = newSpriteId;
}
/// <summary>
/// Sets the sprite by name. The sprite will be selected from the current collection.
/// </summary>
public bool SetSprite(string spriteName) {
int spriteId = collection.GetSpriteIdByName(spriteName, -1);
if (spriteId != -1) {
SetSprite(spriteId);
}
else {
Debug.LogError("SetSprite - Sprite not found in collection: " + spriteName);
}
return spriteId != -1;
}
/// <summary>
/// Sets sprite by identifier from the new collection.
/// </summary>
public void SetSprite(tk2dSpriteCollectionData newCollection, int newSpriteId) {
bool switchedCollection = false;
if (Collection != newCollection) {
collection = newCollection;
collectionInst = collection.inst;
_spriteId = -1; // force an update, but only when the collection has changed
switchedCollection = true;
}
spriteId = newSpriteId;
if (switchedCollection) {
UpdateMaterial();
}
}
/// <summary>
/// Sets sprite by name from the new collection.
/// </summary>
public bool SetSprite(tk2dSpriteCollectionData newCollection, string spriteName) {
int spriteId = newCollection.GetSpriteIdByName(spriteName, -1);
if (spriteId != -1) {
SetSprite(newCollection, spriteId);
}
else {
Debug.LogError("SetSprite - Sprite not found in collection: " + spriteName);
}
return spriteId != -1;
}
/// <summary>
/// Makes the sprite pixel perfect to the active camera.
/// Automatically detects <see cref="tk2dCamera"/> if present
/// Otherwise uses Camera.main
/// </summary>
public void MakePixelPerfect()
{
float s = 1.0f;
tk2dCamera cam = tk2dCamera.CameraForLayer(gameObject.layer);
if (cam != null)
{
if (Collection.version < 2)
{
Debug.LogError("Need to rebuild sprite collection.");
}
float zdist = (transform.position.z - cam.transform.position.z);
float spriteSize = (Collection.invOrthoSize * Collection.halfTargetHeight);
s = cam.GetSizeAtDistance(zdist) * spriteSize;
}
else if (Camera.main)
{
if (Camera.main.isOrthoGraphic)
{
s = Camera.main.orthographicSize;
}
else
{
float zdist = (transform.position.z - Camera.main.transform.position.z);
s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fieldOfView, zdist);
}
s *= Collection.invOrthoSize;
}
else
{
Debug.LogError("Main camera not found.");
}
scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s);
}
protected abstract void UpdateMaterial(); // update material when switching spritecollection
protected abstract void UpdateColors(); // reupload color data only
protected abstract void UpdateVertices(); // reupload vertex data only
protected abstract void UpdateGeometry(); // update full geometry (including indices)
protected abstract int GetCurrentVertexCount(); // return current vertex count
/// <summary>
/// Rebuilds the mesh data for this sprite. Not usually necessary to call this, unless some internal states are modified.
/// </summary>
public abstract void Build();
/// <summary>
/// Resolves a sprite name and returns a unique id for the sprite.
/// Convenience alias of <see cref="tk2dSpriteCollectionData.GetSpriteIdByName"/>
/// </summary>
/// <returns>
/// Unique Sprite Id.
/// </returns>
/// <param name='name'>Case sensitive sprite name, as defined in the sprite collection. This is usually the source filename excluding the extension</param>
public int GetSpriteIdByName(string name)
{
InitInstance();
return collectionInst.GetSpriteIdByName(name);
}
/// <summary>
/// Adds a tk2dBaseSprite derived class as a component to the gameObject passed in, setting up necessary parameters
/// and building geometry.
/// </summary>
public static T AddComponent<T>(GameObject go, tk2dSpriteCollectionData spriteCollection, int spriteId) where T : tk2dBaseSprite
{
T sprite = go.AddComponent<T>();
sprite._spriteId = -1;
sprite.SetSprite(spriteCollection, spriteId);
sprite.Build();
return sprite;
}
/// <summary>
/// Adds a tk2dBaseSprite derived class as a component to the gameObject passed in, setting up necessary parameters
/// and building geometry. Shorthand using sprite name
/// </summary>
public static T AddComponent<T>(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName) where T : tk2dBaseSprite
{
int spriteId = spriteCollection.GetSpriteIdByName(spriteName, -1);
if (spriteId == -1) {
Debug.LogError( string.Format("Unable to find sprite named {0} in sprite collection {1}", spriteName, spriteCollection.spriteCollectionName) );
return null;
}
else {
return AddComponent<T>(go, spriteCollection, spriteId);
}
}
protected int GetNumVertices()
{
InitInstance();
return collectionInst.spriteDefinitions[spriteId].positions.Length;
}
protected int GetNumIndices()
{
InitInstance();
return collectionInst.spriteDefinitions[spriteId].indices.Length;
}
protected void SetPositions(Vector3[] positions, Vector3[] normals, Vector4[] tangents)
{
var sprite = collectionInst.spriteDefinitions[spriteId];
int numVertices = GetNumVertices();
for (int i = 0; i < numVertices; ++i)
{
positions[i].x = sprite.positions[i].x * _scale.x;
positions[i].y = sprite.positions[i].y * _scale.y;
positions[i].z = sprite.positions[i].z * _scale.z;
}
// The secondary test sprite.normals != null must have been performed prior to this function call
if (normals.Length > 0)
{
for (int i = 0; i < numVertices; ++i)
{
normals[i] = sprite.normals[i];
}
}
// The secondary test sprite.tangents != null must have been performed prior to this function call
if (tangents.Length > 0)
{
for (int i = 0; i < numVertices; ++i)
{
tangents[i] = sprite.tangents[i];
}
}
}
protected void SetColors(Color32[] dest)
{
Color c = _color;
if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; }
Color32 c32 = c;
int numVertices = GetNumVertices();
for (int i = 0; i < numVertices; ++i)
dest[i] = c32;
}
/// <summary>
/// Gets the local space bounds of the sprite.
/// </summary>
/// <returns>
/// Local space bounds
/// </returns>
public Bounds GetBounds()
{
InitInstance();
var sprite = collectionInst.spriteDefinitions[_spriteId];
return new Bounds(new Vector3(sprite.boundsData[0].x * _scale.x, sprite.boundsData[0].y * _scale.y, sprite.boundsData[0].z * _scale.z),
new Vector3(sprite.boundsData[1].x * Mathf.Abs(_scale.x), sprite.boundsData[1].y * Mathf.Abs(_scale.y), sprite.boundsData[1].z * Mathf.Abs(_scale.z) ));
}
/// <summary>
/// Gets untrimmed local space bounds of the sprite. This is the size of the sprite before 2D Toolkit trims away empty space in the sprite.
/// Use this when you need to position sprites in a grid, etc, when the trimmed bounds is not sufficient.
/// </summary>
/// <returns>
/// Local space untrimmed bounds
/// </returns>
public Bounds GetUntrimmedBounds()
{
InitInstance();
var sprite = collectionInst.spriteDefinitions[_spriteId];
return new Bounds(new Vector3(sprite.untrimmedBoundsData[0].x * _scale.x, sprite.untrimmedBoundsData[0].y * _scale.y, sprite.untrimmedBoundsData[0].z * _scale.z),
new Vector3(sprite.untrimmedBoundsData[1].x * Mathf.Abs(_scale.x), sprite.untrimmedBoundsData[1].y * Mathf.Abs(_scale.y), sprite.untrimmedBoundsData[1].z * Mathf.Abs(_scale.z) ));
}
public static Bounds AdjustedMeshBounds(Bounds bounds, int renderLayer) {
Vector3 center = bounds.center;
center.z = -renderLayer * 0.01f;
bounds.center = center;
return bounds;
}
/// <summary>
/// Gets the current sprite definition.
/// </summary>
/// <returns>
/// <see cref="tk2dSpriteDefinition"/> for the currently active sprite.
/// </returns>
public tk2dSpriteDefinition GetCurrentSpriteDef()
{
InitInstance();
return (collectionInst == null) ? null : collectionInst.spriteDefinitions[_spriteId];
}
/// <summary>
/// Gets the current sprite definition.
/// </summary>
/// <returns>
/// <see cref="tk2dSpriteDefinition"/> for the currently active sprite.
/// </returns>
public tk2dSpriteDefinition CurrentSprite {
get {
InitInstance();
return (collectionInst == null) ? null : collectionInst.spriteDefinitions[_spriteId];
}
}
/// <summary>
/// Used for sprite resizing in Editor, and UILayout.
/// </summary>
public virtual void ReshapeBounds(Vector3 dMin, Vector3 dMax) {
;
}
// Collider setup
protected virtual bool NeedBoxCollider() { return false; }
protected virtual void UpdateCollider()
{
tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[_spriteId];
if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) {
if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box && boxCollider == null)
{
// Has the user created a box collider?
boxCollider = gameObject.GetComponent<BoxCollider>();
if (boxCollider == null)
{
// create box collider at runtime. this won't get removed from the object
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
if (boxCollider != null)
{
if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box)
{
boxCollider.center = new Vector3(sprite.colliderVertices[0].x * _scale.x, sprite.colliderVertices[0].y * _scale.y, sprite.colliderVertices[0].z * _scale.z);
boxCollider.size = new Vector3(2 * sprite.colliderVertices[1].x * _scale.x, 2 * sprite.colliderVertices[1].y * _scale.y, 2 * sprite.colliderVertices[1].z * _scale.z);
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset)
{
// Don't do anything here, for backwards compatibility
}
else // in all cases, if the collider doesn't match is requested, null it out
{
if (boxCollider != null)
{
// move the box far far away, boxes with zero extents still collide
boxCollider.center = new Vector3(0, 0, -100000.0f);
boxCollider.size = Vector3.zero;
}
}
}
}
else if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box)
{
if (boxCollider2D == null) {
// Has the user created a box collider?
boxCollider2D = gameObject.GetComponent<BoxCollider2D>();
if (boxCollider2D == null)
{
// create box collider at runtime. this won't get removed from the object
boxCollider2D = gameObject.AddComponent<BoxCollider2D>();
}
}
// Turn off existing polygon colliders
if (polygonCollider2D.Count > 0) {
foreach (PolygonCollider2D polyCollider in polygonCollider2D) {
if (polyCollider != null && polyCollider.enabled) {
polyCollider.enabled = false;
}
}
}
// Turn off existing edge colliders
if (edgeCollider2D.Count > 0) {
foreach (EdgeCollider2D edgeCollider in edgeCollider2D) {
if (edgeCollider != null && edgeCollider.enabled) {
edgeCollider.enabled = false;
}
}
}
if (!boxCollider2D.enabled) {
boxCollider2D.enabled = true;
}
boxCollider2D.center = new Vector2(sprite.colliderVertices[0].x * _scale.x, sprite.colliderVertices[0].y * _scale.y);
boxCollider2D.size = new Vector2(Mathf.Abs(2 * sprite.colliderVertices[1].x * _scale.x), Mathf.Abs(2 * sprite.colliderVertices[1].y * _scale.y));
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh)
{
// Turn of existing box collider
if (boxCollider2D != null && boxCollider2D.enabled) {
boxCollider2D.enabled = false;
}
// Make sure none in our array are null (manually deleted, etc)
// This doesn't handle the case where the user has deleted something manually from the polygonCOllider2D list
int numPolyColliders = sprite.polygonCollider2D.Length;
for (int i = 0; i < polygonCollider2D.Count; ++i) {
if (polygonCollider2D[i] == null) {
polygonCollider2D[i] = gameObject.AddComponent<PolygonCollider2D>();
}
}
while (polygonCollider2D.Count < numPolyColliders) {
polygonCollider2D.Add( gameObject.AddComponent<PolygonCollider2D>() );
}
for (int i = 0; i < numPolyColliders; ++i) {
if (!polygonCollider2D[i].enabled) {
polygonCollider2D[i].enabled = true;
}
if (_scale.x != 1 || _scale.y != 1) {
Vector2[] sourcePoints = sprite.polygonCollider2D[i].points;
Vector2[] scaledPoints = new Vector2[sourcePoints.Length];
for (int j = 0; j < sourcePoints.Length; ++j) {
scaledPoints[j] = Vector2.Scale( sourcePoints[j], _scale );
}
polygonCollider2D[i].points = scaledPoints;
}
else {
polygonCollider2D[i].points = sprite.polygonCollider2D[i].points;
}
}
for (int i = numPolyColliders; i < polygonCollider2D.Count; ++i) {
if (polygonCollider2D[i].enabled) {
polygonCollider2D[i].enabled = false;
}
}
// Make sure none in our array are null (manually deleted, etc)
// This doesn't handle the case where the user has deleted something manually from the polygonCOllider2D list
int numEdgeColliders = sprite.edgeCollider2D.Length;
for (int i = 0; i < edgeCollider2D.Count; ++i) {
if (edgeCollider2D[i] == null) {
edgeCollider2D[i] = gameObject.AddComponent<EdgeCollider2D>();
}
}
while (edgeCollider2D.Count < numEdgeColliders) {
edgeCollider2D.Add( gameObject.AddComponent<EdgeCollider2D>() );
}
for (int i = 0; i < numEdgeColliders; ++i) {
if (!edgeCollider2D[i].enabled) {
edgeCollider2D[i].enabled = true;
}
if (_scale.x != 1 || _scale.y != 1) {
Vector2[] sourcePoints = sprite.edgeCollider2D[i].points;
Vector2[] scaledPoints = new Vector2[sourcePoints.Length];
for (int j = 0; j < sourcePoints.Length; ++j) {
scaledPoints[j] = Vector2.Scale( sourcePoints[j], _scale );
}
edgeCollider2D[i].points = scaledPoints;
}
else {
edgeCollider2D[i].points = sprite.edgeCollider2D[i].points;
}
}
for (int i = numEdgeColliders; i < edgeCollider2D.Count; ++i) {
if (edgeCollider2D[i].enabled) {
edgeCollider2D[i].enabled = false;
}
}
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.None) {
// Turn of existing box collider
if (boxCollider2D != null && boxCollider2D.enabled) {
boxCollider2D.enabled = false;
}
// Turn off existing polygon colliders
if (polygonCollider2D.Count > 0) {
foreach (PolygonCollider2D polyCollider in polygonCollider2D) {
if (polyCollider != null && polyCollider.enabled) {
polyCollider.enabled = false;
}
}
}
// Turn off existing edge colliders
if (edgeCollider2D.Count > 0) {
foreach (EdgeCollider2D edgeCollider in edgeCollider2D) {
if (edgeCollider != null && edgeCollider.enabled) {
edgeCollider.enabled = false;
}
}
}
}
#endif
}
}
// This is separate to UpdateCollider, as UpdateCollider can only work with BoxColliders, and will NOT create colliders
protected virtual void CreateCollider()
{
tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[_spriteId];
if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset)
{
// do not attempt to create or modify anything if it is Unset
return;
}
if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) {
// User has created a collider
if (collider != null)
{
boxCollider = GetComponent<BoxCollider>();
meshCollider = GetComponent<MeshCollider>();
}
if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null)
{
if (boxCollider == null)
{
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh && boxCollider == null)
{
// this should not be updated again (apart from scale changes in the editor, where we force regeneration of colliders)
if (meshCollider == null)
meshCollider = gameObject.AddComponent<MeshCollider>();
if (meshColliderMesh == null)
meshColliderMesh = new Mesh();
meshColliderMesh.Clear();
meshColliderPositions = new Vector3[sprite.colliderVertices.Length];
for (int i = 0; i < meshColliderPositions.Length; ++i)
meshColliderPositions[i] = new Vector3(sprite.colliderVertices[i].x * _scale.x, sprite.colliderVertices[i].y * _scale.y, sprite.colliderVertices[i].z * _scale.z);
meshColliderMesh.vertices = meshColliderPositions;
float s = _scale.x * _scale.y * _scale.z;
meshColliderMesh.triangles = (s >= 0.0f)?sprite.colliderIndicesFwd:sprite.colliderIndicesBack;
meshCollider.sharedMesh = meshColliderMesh;
meshCollider.convex = sprite.colliderConvex;
meshCollider.smoothSphereCollisions = sprite.colliderSmoothSphereCollisions;
// this is required so our mesh pivot is at the right point
if (rigidbody) rigidbody.centerOfMass = Vector3.zero;
}
else if (sprite.colliderType != tk2dSpriteDefinition.ColliderType.None)
{
// This warning is not applicable in the editor
if (Application.isPlaying)
{
Debug.LogError("Invalid mesh collider on sprite '" + name + "', please remove and try again.");
}
}
UpdateCollider();
}
else if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
UpdateCollider();
#endif
}
}
#if UNITY_EDITOR
public virtual void EditMode__CreateCollider()
{
// Revert to runtime behaviour when the game is running
if (Application.isPlaying)
{
UpdateCollider();
return;
}
tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[_spriteId];
if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset)
return;
PhysicMaterial physicsMaterial = collider?collider.sharedMaterial:null;
bool isTrigger = collider?collider.isTrigger:false;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
PhysicsMaterial2D physicsMaterial2D = collider2D?collider2D.sharedMaterial:null;
if (collider2D != null) {
isTrigger = collider2D.isTrigger;
}
#endif
boxCollider = gameObject.GetComponent<BoxCollider>();
meshCollider = gameObject.GetComponent<MeshCollider>();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
boxCollider2D = gameObject.GetComponent<BoxCollider2D>();
edgeCollider2D.Clear();
edgeCollider2D.AddRange( gameObject.GetComponents<EdgeCollider2D>() );
polygonCollider2D.Clear();
polygonCollider2D.AddRange( gameObject.GetComponents<PolygonCollider2D>() );
#endif
// Sanitize colliders - get rid of unused / incorrect ones in editor
if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) {
// Delete colliders from wrong physics engine
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (boxCollider2D != null) {
DestroyImmediate(boxCollider2D, true);
}
foreach (PolygonCollider2D c2d in polygonCollider2D) {
if (c2d != null) {
DestroyImmediate(c2d, true);
}
}
polygonCollider2D.Clear();
foreach (EdgeCollider2D e2d in edgeCollider2D) {
if (e2d != null) {
DestroyImmediate(e2d, true);
}
}
edgeCollider2D.Clear();
#endif
// Delete mismatched collider
if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null)
{
if (meshCollider != null) {
DestroyImmediate(meshCollider, true);
}
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh) {
if (boxCollider != null) {
DestroyImmediate(boxCollider, true);
}
}
else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.None) {
if (meshCollider != null) {
DestroyImmediate(meshCollider, true);
}
if (boxCollider != null) {
DestroyImmediate(boxCollider, true);
}
}
}
else if (sprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
// Delete colliders from wrong physics engine
if (boxCollider != null) {
DestroyImmediate(boxCollider, true);
}
if (meshCollider != null) {
DestroyImmediate(meshCollider, true);
}
foreach (PolygonCollider2D c2d in polygonCollider2D) {
if (c2d != null) {
DestroyImmediate(c2d, true);
}
}
polygonCollider2D.Clear();
foreach (EdgeCollider2D e2d in edgeCollider2D) {
if (e2d != null) {
DestroyImmediate(e2d, true);
}
}
edgeCollider2D.Clear();
if (boxCollider2D != null) {
DestroyImmediate(boxCollider2D, true);
boxCollider2D = null;
}
#endif
}
CreateCollider();
if (collider)
{
collider.isTrigger = isTrigger;
collider.material = physicsMaterial;
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (boxCollider2D) {
boxCollider2D.isTrigger = isTrigger;
boxCollider2D.sharedMaterial = physicsMaterial2D;
}
foreach (EdgeCollider2D ec in edgeCollider2D) {
ec.isTrigger = isTrigger;
ec.sharedMaterial = physicsMaterial2D;
}
foreach (PolygonCollider2D pc in polygonCollider2D) {
pc.isTrigger = isTrigger;
pc.sharedMaterial = physicsMaterial2D;
}
#endif
}
#endif
protected void Awake()
{
if (collection != null)
{
collectionInst = collection.inst;
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
CachedRenderer.sortingOrder = renderLayer;
#endif
}
// Used by derived classes only
public void CreateSimpleBoxCollider() {
if (CurrentSprite == null) {
return;
}
if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
boxCollider2D = GetComponent<BoxCollider2D>();
if (boxCollider2D != null) {
Object.DestroyImmediate(boxCollider2D, true);
}
#endif
boxCollider = GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
else if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
boxCollider = GetComponent<BoxCollider>();
if (boxCollider != null) {
Object.DestroyImmediate(boxCollider, true);
}
boxCollider2D = GetComponent<BoxCollider2D>();
if (boxCollider2D == null) {
boxCollider2D = gameObject.AddComponent<BoxCollider2D>();
}
#endif
}
}
// tk2dRuntime.ISpriteCollectionEditor
public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
return Collection == spriteCollection;
}
public virtual void ForceBuild()
{
if (collection == null) {
return;
}
collectionInst = collection.inst;
if (spriteId < 0 || spriteId >= collectionInst.spriteDefinitions.Length)
spriteId = 0;
#if UNITY_EDITOR
EditMode__CreateCollider();
#endif
Build();
if (SpriteChanged != null) {
SpriteChanged(this);
}
}
/// <summary>
/// Create a sprite (and gameObject) displaying the region of the texture specified.
/// Use <see cref="tk2dSpriteCollectionData.CreateFromTexture"/> if you need to create a sprite collection
/// with multiple sprites.
/// </summary>
public static GameObject CreateFromTexture<T>(Texture texture, tk2dSpriteCollectionSize size, Rect region, Vector2 anchor) where T : tk2dBaseSprite
{
tk2dSpriteCollectionData data = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(texture, size, region, anchor);
if (data == null)
return null;
GameObject spriteGo = new GameObject();
tk2dBaseSprite.AddComponent<T>(spriteGo, data, 0);
return spriteGo;
}
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using CyPhy2ComponentModel.Validation;
using GME.CSharp;
using GME;
using GME.MGA;
using GME.MGA.Core;
using ISIS.GME.Common;
using System.Windows.Forms;
using CyPhyML = ISIS.GME.Dsml.CyPhyML.Interfaces;
using CyPhyMLClasses = ISIS.GME.Dsml.CyPhyML.Classes;
using avm;
using CyPhy2ComponentModel;
using System.Reflection;
using Microsoft.Win32;
namespace CyPhyComponentImporterCL {
public class CyPhyComponentImporterCL {
private static void WriteLine(Func<string, string, string> f, IMgaFCO a, IMgaFCO b) {
//if (GMEConsole != null)
//{
// GMEConsole.Out.WriteLine(f(GetLink(a, a.Name), GetLink(b, b.Name)));
//}
//else
{
Console.Out.WriteLine( f( a.AbsPath, b.AbsPath ) );
}
}
public static string Meta_Path
{
get
{
const string keyName = "Software\\META";
RegistryKey metaKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
.OpenSubKey(keyName, false);
string metaPath = "C:\\Program Files (x86)\\META";
if (metaKey != null)
{
metaPath = (string)metaKey.GetValue("META_PATH", metaPath);
}
return metaPath;
}
}
private static MgaProject GetProject( String filename ) {
MgaProject result = null;
if( filename != null && filename != "" ) {
if( Path.GetExtension( filename ) == ".mga" ) {
result = new MgaProject();
if( System.IO.File.Exists( filename ) ) {
Console.Out.Write( "Opening {0} ... ", filename );
bool ro_mode;
result.Open( "MGA=" + Path.GetFullPath(filename), out ro_mode );
} else {
Console.Out.Write( "Creating {0} ... ", filename );
result.Create( "MGA=" + filename, "CyPhyML" );
}
Console.Out.WriteLine( "Done." );
} else {
Console.Error.WriteLine( "{0} file must be an mga project.", filename );
}
} else {
Console.Error.WriteLine( "Please specify an Mga project." );
}
return result;
}
private static void usage() {
Console.Out.WriteLine( "Usage: <program> AVMFile [ -p <path-to-component-to-replace> ] CyPhyMLFile.mga" );
Console.Out.WriteLine( "Usage: <program> -r <path> CyPhyMLFile.mga" );
Environment.Exit( 1 );
}
[STAThread]
public static int Main( String[] args ) {
if( args.Length < 2 || args.Length > 4 ) usage();
MgaProject mgaProject;
List<String> lp_FilesToImport = new List<string>();
string avmFilePath = "";
string mgaProjectPath = "";
string componentReplacementPath = "";
bool rOptionUsed = false;
bool pOptionUsed = false;
for( int ix = 0 ; ix < args.Length ; ++ix ) {
if( args[ ix ].ToLower() == "-r" ) {
if( pOptionUsed ) usage();
rOptionUsed = true;
if ( ++ix >= args.Length ) usage();
if( avmFilePath != null && avmFilePath != "" ) {
if( mgaProjectPath != null && mgaProjectPath != "" ) usage();
mgaProjectPath = avmFilePath;
avmFilePath = "";
lp_FilesToImport.Clear();
}
String sImportDirectory = args[ ix ];
String startingDirectory = Path.GetFullPath( sImportDirectory );
string[] xmlFiles = Directory.GetFiles( startingDirectory, "*.acm", SearchOption.AllDirectories );
foreach( String p_XMLFile in xmlFiles ) {
lp_FilesToImport.Add( Path.GetFullPath( p_XMLFile ) );
}
} else if( args[ ix ].ToLower() == "-p" ) {
if( rOptionUsed ) usage();
pOptionUsed = true;
if ( ++ix >= args.Length ) usage();
componentReplacementPath = args[ ix ];
} else if ( lp_FilesToImport.Count == 0 && avmFilePath == "" ) {
avmFilePath = args[ ix ];
try
{
lp_FilesToImport.Add(Path.GetFullPath(avmFilePath));
}
catch (System.ArgumentException ex)
{
Console.Out.WriteLine(ex.Message);
Console.Out.WriteLine(avmFilePath);
throw ex;
}
} else {
if( mgaProjectPath != null && mgaProjectPath != "" ) usage();
mgaProjectPath = args[ ix ];
}
}
mgaProject = GetProject( mgaProjectPath );
try
{
bool bExceptionOccurred = false;
if (mgaProject != null)
{
MgaGateway mgaGateway = new MgaGateway(mgaProject);
mgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
mgaGateway.PerformInTransaction(delegate
{
string libroot = Path.GetDirectoryName(Path.GetFullPath(mgaProjectPath));
CyPhyML.RootFolder cyPhyMLRootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyMLClasses.RootFolder>(mgaProject.RootFolder as MgaObject);
#region Attach QUDT library if needed
IMgaFolder oldQudt = mgaProject.RootFolder.ChildFolders.Cast<IMgaFolder>().Where(x => x.LibraryName != "" && (x.Name.ToLower().Contains("qudt"))).FirstOrDefault();
string mgaQudtPath = Meta_Path + "\\meta\\CyPhyMLQudt.mga";
bool needAttach = false;
if (oldQudt == null)
{
needAttach = true;
}
else
{
long loldModTime;
DateTime oldModTime = long.TryParse(oldQudt.RegistryValue["modtime"], out loldModTime) ? DateTime.FromFileTimeUtc(loldModTime) : DateTime.MinValue;
needAttach = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).CompareTo(oldModTime) > 0;
if (!needAttach)
{
Console.Error.WriteLine("QUDT is up-to-date: embedded library modified " + oldModTime.ToString() + ", CyPhyMLQudt.mga modified " + System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).ToString());
}
}
if (needAttach)
{
Console.Error.WriteLine("Attaching library " + mgaQudtPath);
ISIS.GME.Common.Interfaces.RootFolder newQudt = ISIS.GME.Common.Classes.RootFolder.GetRootFolder(mgaProject).AttachLibrary("MGA=" + mgaQudtPath);
DateTime modtime = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath);
((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] =
modtime.ToFileTimeUtc().ToString();
if (oldQudt != null)
{
ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldQudt, newQudt.Impl, null);
sw.UpdateSublibrary();
oldQudt.DestroyObject();
}
((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = "UnitLibrary QUDT";
Console.Error.WriteLine((oldQudt == null ? "Attached " : "Refreshed") + " Qudt library.");
}
#endregion
var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
importer.Initialize(cyPhyMLRootFolder.Impl.Project);
importer.ImportFiles(cyPhyMLRootFolder.Impl.Project, libroot, lp_FilesToImport.ToArray(), true);
importer.DisposeLogger();
bExceptionOccurred = importer.Errors.Count > 0;
});
mgaProject.Save();
if (mgaGateway.territory != null)
{
mgaGateway.territory.Destroy();
}
if (bExceptionOccurred)
{
return -1;
}
}
}
finally
{
mgaProject.Close(true);
}
return 0;
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace Alphaleonis.Win32.Filesystem
{
#region AlphaFS
/// <summary>Provides access to a file system object, using Shell32.</summary>
public static class Shell32
{
#region Enum / Struct
#region AssociationAttributes
/// <summary>Provides information for the IQueryAssociations interface methods, used by Shell32.</summary>
[Flags]
public enum AssociationAttributes
{
/// <summary>None.</summary>
None = 0,
/// <summary>Instructs not to map CLSID values to ProgID values.</summary>
InitNoRemapClsid = 1,
/// <summary>Identifies the value of the supplied file parameter (3rd parameter of function GetFileAssociation()) as an executable file name.</summary>
/// <remarks>If this flag is not set, the root key will be set to the ProgID associated with the .exe key instead of the executable file's ProgID.</remarks>
InitByExeName = 2,
/// <summary>Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the * subkey.</summary>
InitDefaultToStar = 4,
/// <summary>Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the Folder subkey.</summary>
InitDefaultToFolder = 8,
/// <summary>Specifies that only HKEY_CLASSES_ROOT should be searched, and that HKEY_CURRENT_USER should be ignored.</summary>
NoUserSettings = 16,
/// <summary>Specifies that the return string should not be truncated. Instead, return an error value and the required size for the complete string.</summary>
NoTruncate = 32,
/// <summary>
/// Instructs IQueryAssociations methods to verify that data is accurate.
/// This setting allows IQueryAssociations methods to read data from the user's hard disk for verification.
/// For example, they can check the friendly name in the registry against the one stored in the .exe file.
/// </summary>
/// <remarks>Setting this flag typically reduces the efficiency of the method.</remarks>
Verify = 64,
/// <summary>
/// Instructs IQueryAssociations methods to ignore Rundll.exe and return information about its target.
/// Typically IQueryAssociations methods return information about the first .exe or .dll in a command string.
/// If a command uses Rundll.exe, setting this flag tells the method to ignore Rundll.exe and return information about its target.
/// </summary>
RemapRunDll = 128,
/// <summary>Instructs IQueryAssociations methods not to fix errors in the registry, such as the friendly name of a function not matching the one found in the .exe file.</summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FixUps")]
NoFixUps = 256,
/// <summary>Specifies that the BaseClass value should be ignored.</summary>
IgnoreBaseClass = 512,
/// <summary>Specifies that the "Unknown" ProgID should be ignored; instead, fail.</summary>
/// <remarks>Introduced in Windows 7.</remarks>
InitIgnoreUnknown = 1024,
/// <summary>Specifies that the supplied ProgID should be mapped using the system defaults, rather than the current user defaults.</summary>
/// <remarks>Introduced in Windows 8.</remarks>
InitFixedProgId = 2048,
/// <summary>Specifies that the value is a protocol, and should be mapped using the current user defaults.</summary>
/// <remarks>Introduced in Windows 8.</remarks>
IsProtocol = 4096
}
#endregion // AssociationAttributes
#region AssociationData
//internal enum AssociationData
//{
// MsiDescriptor = 1,
// NoActivateHandler = 2 ,
// QueryClassStore = 3,
// HasPerUserAssoc = 4,
// EditFlags = 5,
// Value = 6
//}
#endregion // AssociationData
#region AssociationKey
//internal enum AssociationKey
//{
// ShellExecClass = 1,
// App = 2,
// Class = 3,
// BaseClass = 4
//}
#endregion // AssociationKey
#region AssociationString
/// <summary>ASSOCSTR enumeration - Used by the AssocQueryString() function to define the type of string that is to be returned.</summary>
public enum AssociationString
{
/// <summary>None.</summary>
None = 0,
/// <summary>A command string associated with a Shell verb.</summary>
Command = 1,
/// <summary>
/// An executable from a Shell verb command string.
/// For example, this string is found as the (Default) value for a subkey such as HKEY_CLASSES_ROOT\ApplicationName\shell\Open\command.
/// If the command uses Rundll.exe, set the <see cref="AssociationAttributes.RemapRunDll"/> flag in the attributes parameter of IQueryAssociations::GetString to retrieve the target executable.
/// </summary>
Executable = 2,
/// <summary>The friendly name of a document type.</summary>
FriendlyDocName = 3,
/// <summary>The friendly name of an executable file.</summary>
FriendlyAppName = 4,
/// <summary>Ignore the information associated with the open subkey.</summary>
NoOpen = 5,
/// <summary>Look under the ShellNew subkey.</summary>
ShellNewValue = 6,
/// <summary>A template for DDE commands.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")]
DdeCommand = 7,
/// <summary>The DDE command to use to create a process.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")]
DdeIfExec = 8,
/// <summary>The application name in a DDE broadcast.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")]
DdeApplication = 9,
/// <summary>The topic name in a DDE broadcast.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")]
DdeTopic = 10,
/// <summary>
/// Corresponds to the InfoTip registry value.
/// Returns an info tip for an item, or list of properties in the form of an IPropertyDescriptionList from which to create an info tip, such as when hovering the cursor over a file name.
/// The list of properties can be parsed with PSGetPropertyDescriptionListFromString.
/// </summary>
InfoTip = 11,
/// <summary>
/// Corresponds to the QuickTip registry value. This is the same as <see cref="InfoTip"/>, except that it always returns a list of property names in the form of an IPropertyDescriptionList.
/// The difference between this value and <see cref="InfoTip"/> is that this returns properties that are safe for any scenario that causes slow property retrieval, such as offline or slow networks.
/// Some of the properties returned from <see cref="InfoTip"/> might not be appropriate for slow property retrieval scenarios.
/// The list of properties can be parsed with PSGetPropertyDescriptionListFromString.
/// </summary>
QuickTip = 12,
/// <summary>
/// Corresponds to the TileInfo registry value. Contains a list of properties to be displayed for a particular file type in a Windows Explorer window that is in tile view.
/// This is the same as <see cref="InfoTip"/>, but, like <see cref="QuickTip"/>, it also returns a list of property names in the form of an IPropertyDescriptionList.
/// The list of properties can be parsed with PSGetPropertyDescriptionListFromString.
/// </summary>
TileInfo = 13,
/// <summary>
/// Describes a general type of MIME file association, such as image and bmp,
/// so that applications can make general assumptions about a specific file type.
/// </summary>
ContentType = 14,
/// <summary>
/// Returns the path to the icon resources to use by default for this association.
/// Positive numbers indicate an index into the dll's resource table, while negative numbers indicate a resource ID.
/// An example of the syntax for the resource is "c:\myfolder\myfile.dll,-1".
/// </summary>
DefaultIcon = 15,
/// <summary>
/// For an object that has a Shell extension associated with it,
/// you can use this to retrieve the CLSID of that Shell extension object by passing a string representation
/// of the IID of the interface you want to retrieve as the pwszExtra parameter of IQueryAssociations::GetString.
/// For example, if you want to retrieve a handler that implements the IExtractImage interface,
/// you would specify "{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}", which is the IID of IExtractImage.
/// </summary>
ShellExtension = 16,
/// <summary>
/// For a verb invoked through COM and the IDropTarget interface, you can use this flag to retrieve the IDropTarget object's CLSID.
/// This CLSID is registered in the DropTarget subkey.
/// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString.
/// </summary>
DropTarget = 17,
/// <summary>
/// For a verb invoked through COM and the IExecuteCommand interface, you can use this flag to retrieve the IExecuteCommand object's CLSID.
/// This CLSID is registered in the verb's command subkey as the DelegateExecute entry.
/// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString.
/// </summary>
DelegateExecute = 18,
/// <summary>(No description available on MSDN)</summary>
/// <remarks>Introduced in Windows 8.</remarks>
SupportedUriProtocols = 19,
/// <summary>The maximum defined <see cref="AssociationString"/> value, used for validation purposes.</summary>
Max = 20
}
#endregion // AssociationString
#region FileAttributes
/// <summary>Shell32 FileAttributes structure, used to retrieve the different types of a file system object.</summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
[Flags]
public enum FileAttributes
{
/// <summary>0x000000000 - Get file system object large icon.</summary>
/// <remarks>The <see cref="Icon"/> flag must also be set.</remarks>
LargeIcon = 0,
/// <summary>0x000000001 - Get file system object small icon.</summary>
/// <remarks>The <see cref="Icon"/> flag must also be set.</remarks>
SmallIcon = 1,
/// <summary>0x000000002 - Get file system object open icon.</summary>
/// <remarks>A container object displays an open icon to indicate that the container is open.</remarks>
/// <remarks>The <see cref="Icon"/> and/or <see cref="SysIconIndex"/> flag must also be set.</remarks>
OpenIcon = 2,
/// <summary>0x000000004 - Get file system object Shell-sized icon.</summary>
/// <remarks>If this attribute is not specified the function sizes the icon according to the system metric values.</remarks>
ShellIconSize = 4,
/// <summary>0x000000008 - Get file system object by its PIDL.</summary>
/// <remarks>Indicate that the given file contains the address of an ITEMIDLIST structure rather than a path name.</remarks>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pidl")]
Pidl = 8,
/// <summary>0x000000010 - Indicates that the given file should not be accessed. Rather, it should act as if the given file exists and use the supplied attributes.</summary>
/// <remarks>This flag cannot be combined with the <see cref="Attributes"/>, <see cref="ExeType"/> or <see cref="Pidl"/> attributes.</remarks>
UseFileAttributes = 16,
/// <summary>0x000000020 - Apply the appropriate overlays to the file's icon.</summary>
/// <remarks>The <see cref="Icon"/> flag must also be set.</remarks>
AddOverlays = 32,
/// <summary>0x000000040 - Returns the index of the overlay icon.</summary>
/// <remarks>The value of the overlay index is returned in the upper eight bits of the iIcon member of the structure specified by psfi.</remarks>
OverlayIndex = 64,
/// <summary>0x000000100 - Retrieve the handle to the icon that represents the file and the index of the icon within the system image list. The handle is copied to the <see cref="FileInfo.IconHandle"/> member of the structure, and the index is copied to the <see cref="FileInfo.IconIndex"/> member.</summary>
Icon = 256,
/// <summary>0x000000200 - Retrieve the display name for the file. The name is copied to the <see cref="FileInfo.DisplayName"/> member of the structure.</summary>
/// <remarks>The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name.</remarks>
DisplayName = 512,
/// <summary>0x000000400 - Retrieve the string that describes the file's type.</summary>
TypeName = 1024,
/// <summary>0x000000800 - Retrieve the item attributes. The attributes are copied to the <see cref="FileInfo.Attributes"/> member of the structure.</summary>
/// <remarks>Will touch every file, degrading performance.</remarks>
Attributes = 2048,
/// <summary>0x000001000 - Retrieve the name of the file that contains the icon representing the file specified by pszPath. The name of the file containing the icon is copied to the <see cref="FileInfo.DisplayName"/> member of the structure. The icon's index is copied to that structure's <see cref="FileInfo.IconIndex"/> member.</summary>
IconLocation = 4096,
/// <summary>0x000002000 - Retrieve the type of the executable file if pszPath identifies an executable file.</summary>
/// <remarks>This flag cannot be specified with any other attributes.</remarks>
ExeType = 8192,
/// <summary>0x000004000 - Retrieve the index of a system image list icon.</summary>
SysIconIndex = 16384,
/// <summary>0x000008000 - Add the link overlay to the file's icon.</summary>
/// <remarks>The <see cref="Icon"/> flag must also be set.</remarks>
LinkOverlay = 32768,
/// <summary>0x000010000 - Blend the file's icon with the system highlight color.</summary>
Selected = 65536,
/// <summary>0x000020000 - Modify <see cref="Attributes"/> to indicate that <see cref="FileInfo.Attributes"/> contains specific attributes that are desired.</summary>
/// <remarks>This flag cannot be specified with the <see cref="Icon"/> attribute. Will touch every file, degrading performance.</remarks>
AttributesSpecified = 131072
}
#endregion // FileAttributes
#region FileInfo
/// <summary>SHFILEINFO structure, contains information about a file system object.</summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sh")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sh")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FileInfo
{
/// <summary>A handle to the icon that represents the file.</summary>
/// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public readonly IntPtr IconHandle;
/// <summary>The index of the icon image within the system image list.</summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public int IconIndex;
/// <summary>An array of values that indicates the attributes of the file object.</summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
[MarshalAs(UnmanagedType.U4)]
public readonly GetAttributesOf Attributes;
/// <summary>The name of the file as it appears in the Windows Shell, or the path and file name of the file that contains the icon representing the file.</summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MaxPath)]
public string DisplayName;
/// <summary>The type of file.</summary>
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string TypeName;
}
#endregion // FileInfo
#region GetAttributesOf
/// <summary>SFGAO - Attributes that can be retrieved from a file system object.</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags"), SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sh")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sh")]
[SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")]
[Flags]
public enum GetAttributesOf : int
{
/// <summary>0x00000000 - None.</summary>
None = 0,
/// <summary>0x00000001 - The specified items can be copied.</summary>
CanCopy = 1,
/// <summary>0x00000002 - The specified items can be moved.</summary>
CanMove = 2,
/// <summary>0x00000004 - Shortcuts can be created for the specified items.</summary>
CanLink = 4,
/// <summary>0x00000008 - The specified items can be bound to an IStorage object through IShellFolder::BindToObject. For more information about namespace manipulation capabilities, see IStorage.</summary>
Storage = 8,
/// <summary>0x00000010 - The specified items can be renamed. Note that this value is essentially a suggestion; not all namespace clients allow items to be renamed. However, those that do must have this attribute set.</summary>
CanRename = 16,
/// <summary>0x00000020 - The specified items can be deleted.</summary>
CanDelete = 32,
/// <summary>0x00000040 - The specified items have property sheets.</summary>
HasPropSheet = 64,
/// <summary>0x00000100 - The specified items are drop targets.</summary>
DropTarget = 256,
/// <summary>0x00001000 - The specified items are system items.</summary>
/// <remarks>Windows 7 and later.</remarks>
System = 4096,
/// <summary>0x00002000 - The specified items are encrypted and might require special presentation.</summary>
Encrypted = 8192,
/// <summary>0x00004000 - Accessing the item (through IStream or other storage interfaces) is expected to be a slow operation.</summary>
IsSlow = 16384,
/// <summary>0x00008000 - The specified items are shown as dimmed and unavailable to the user.</summary>
Ghosted = 32768,
/// <summary>0x00010000 - The specified items are shortcuts.</summary>
Link = 65536,
/// <summary>0x00020000 - The specified objects are shared.</summary>
Share = 131072,
/// <summary>0x00040000 - The specified items are read-only. In the case of folders, this means that new items cannot be created in those folders.</summary>
ReadOnly = 262144,
/// <summary>0x00080000 - The item is hidden and should not be displayed unless the Show hidden files and folders option is enabled in Folder Settings.</summary>
Hidden = 524288,
/// <summary>0x00100000 - The items are nonenumerated items and should be hidden. They are not returned through an enumerator such as that created by the IShellFolder::EnumObjects method.</summary>
NonEnumerated = 1048576,
/// <summary>0x00200000 - The items contain new content, as defined by the particular application.</summary>
NewContent = 2097152,
/// <summary>0x00400000 - Indicates that the item has a stream associated with it.</summary>
Stream = 4194304,
/// <summary>0x00800000 - Children of this item are accessible through IStream or IStorage.</summary>
StorageAncestor = 8388608,
/// <summary>0x01000000 - When specified as input, instructs the folder to validate that the items contained in a folder or Shell item array exist.</summary>
Validate = 16777216,
/// <summary>0x02000000 - The specified items are on removable media or are themselves removable devices.</summary>
Removable = 33554432,
/// <summary>0x04000000 - The specified items are compressed.</summary>
Compressed = 67108864,
/// <summary>0x08000000 - The specified items can be hosted inside a web browser or Windows Explorer frame.</summary>
Browsable = 134217728,
/// <summary>0x10000000 - The specified folders are either file system folders or contain at least one descendant (child, grandchild, or later) that is a file system folder.</summary>
FileSysAncestor = 268435456,
/// <summary>0x20000000 - The specified items are folders.</summary>
Folder = 536870912,
/// <summary>0x40000000 - The specified folders or files are part of the file system (that is, they are files, directories, or root directories).</summary>
FileSystem = 1073741824,
/// <summary>0x80000000 - The specified folders have subfolders.</summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubFolder")]
HasSubFolder = unchecked ((int)0x80000000)
}
#endregion // GetAttributesOf
#region UrlType
/// <summary>Used by method UrlIs() to define a URL type.</summary>
public enum UrlType
{
/// <summary>Is the URL valid?</summary>
IsUrl = 0,
/// <summary>Is the URL opaque?</summary>
IsOpaque = 1,
/// <summary>Is the URL a URL that is not typically tracked in navigation history?</summary>
IsNoHistory = 2,
/// <summary>Is the URL a file URL?</summary>
IsFileUrl = 3,
/// <summary>Attempt to determine a valid scheme for the URL.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Appliable")]
IsAppliable = 4,
/// <summary>Does the URL string end with a directory?</summary>
IsDirectory = 5,
/// <summary>Does the URL have an appended query string?</summary>
IsHasQuery = 6
}
#endregion // UrlType
#endregion // Enum / Struct
#region Methods
#region GetFileAssociation
/// <summary>Gets the file or protocol that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related string from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileAssociation(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Executable);
}
#endregion // GetFileAssociation
#region GetFileContentType
/// <summary>Gets the content-type that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related content-type from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileContentType(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.ContentType);
}
#endregion // GetFileContentType
#region GetFileDefaultIcon
/// <summary>Gets the default icon that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related default icon from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileDefaultIcon(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.DefaultIcon);
}
#endregion // GetFileDefaultIcon
#region GetFileFriendlyAppName
/// <summary>Gets the friendly application name that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related friendly application name from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileFriendlyAppName(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.InitByExeName, AssociationString.FriendlyAppName);
}
#endregion // GetFileFriendlyAppName
#region GetFileFriendlyDocName
/// <summary>Gets the friendly document name that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related friendly document name from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileFriendlyDocName(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyDocName);
}
#endregion // GetFileFriendlyDocName
#region GetFileIcon
/// <summary>Gets an <see cref="IntPtr"/> handle to the Shell icon that represents the file.</summary>
/// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks>
/// <param name="filePath">
/// The path to the file system object which should not exceed maximum path length. Both absolute and
/// relative paths are valid.
/// </param>
/// <param name="iconAttributes">
/// Icon size <see cref="Shell32.FileAttributes.SmallIcon"/> or <see cref="Shell32.FileAttributes.LargeIcon"/>. Can also be combined
/// with <see cref="Shell32.FileAttributes.AddOverlays"/> and others.
/// </param>
/// <returns>An <see cref="IntPtr"/> handle to the Shell icon that represents the file, or IntPtr.Zero on failure.</returns>
[SecurityCritical]
public static IntPtr GetFileIcon(string filePath, FileAttributes iconAttributes)
{
if (Utils.IsNullOrWhiteSpace(filePath))
return IntPtr.Zero;
FileInfo fileInfo = GetFileInfoCore(filePath, System.IO.FileAttributes.Normal, FileAttributes.Icon | iconAttributes, true, true);
return fileInfo.IconHandle == IntPtr.Zero ? IntPtr.Zero : fileInfo.IconHandle;
}
#endregion // GetFileIcon
#region GetFileInfo
/// <summary>Retrieves information about an object in the file system, such as a file, folder, directory, or drive root.</summary>
/// <returns>A <see cref="Shell32.FileInfo"/> struct instance.</returns>
/// <remarks>
/// <para>You should call this function from a background thread.</para>
/// <para>Failure to do so could cause the UI to stop responding.</para>
/// <para>Unicode path are supported.</para>
/// </remarks>
/// <param name="filePath">The path to the file system object which should not exceed the maximum path length. Both absolute and relative paths are valid.</param>
/// <param name="attributes">A <see cref="System.IO.FileAttributes"/> attribute.</param>
/// <param name="fileAttributes">One ore more <see cref="FileAttributes"/> attributes.</param>
/// <param name="continueOnException">
/// <para><see langword="true"/> suppress any Exception that might be thrown a result from a failure,</para>
/// <para>such as ACLs protected directories or non-accessible reparse points.</para>
/// </param>
[SecurityCritical]
public static FileInfo GetFileInfo(string filePath, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool continueOnException)
{
return GetFileInfoCore(filePath, attributes, fileAttributes, true, continueOnException);
}
#endregion // GetFileInfo
#region GetShell32Info
/// <summary>Retrieves an instance of <see cref="Shell32Info"/> containing information about the specified file.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>A <see cref="Shell32Info"/> class instance.</returns>
[SecurityCritical]
public static Shell32Info GetShell32Info(string path)
{
return new Shell32Info(path);
}
/// <summary>Retrieves an instance of <see cref="Shell32Info"/> containing information about the specified file.</summary>
/// <param name="path">A path to the file.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
/// <returns>A <see cref="Shell32Info"/> class instance.</returns>
[SecurityCritical]
public static Shell32Info GetShell32Info(string path, PathFormat pathFormat)
{
return new Shell32Info(path, pathFormat);
}
#endregion // GetShell32Info
#region GetFileOpenWithAppName
/// <summary>Gets the "Open With" command that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related "Open With" command from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileOpenWithAppName(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyAppName);
}
#endregion // GetFileOpenWithAppName
#region GetFileVerbCommand
/// <summary>Gets the Shell command that is associated with <paramref name="path"/> from the registry.</summary>
/// <param name="path">A path to the file.</param>
/// <returns>The associated file- or protocol-related Shell command from the registry or <c>string.Empty</c> if no association can be found.</returns>
[SecurityCritical]
public static string GetFileVerbCommand(string path)
{
return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Command);
}
#endregion // GetFileVerbCommand
#region PathCreateFromUrl
/// <summary>Converts a file URL to a Microsoft MS-DOS path.</summary>
/// <param name="urlPath">The file URL.</param>
/// <returns>
/// <para>The Microsoft MS-DOS path. If no path can be created, <c>string.Empty</c> is returned.</para>
/// <para>If <paramref name="urlPath"/> is <see langword="null"/>, <see langword="null"/> will also be returned.</para>
/// </returns>
[SecurityCritical]
internal static string PathCreateFromUrl(string urlPath)
{
if (urlPath == null)
return null;
var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);
uint bufferSize = (uint) buffer.Capacity;
uint lastError = NativeMethods.PathCreateFromUrl(urlPath, buffer, ref bufferSize, 0);
// Don't throw exception, but return string.Empty;
return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty;
}
#endregion // PathCreateFromUrl
#region PathCreateFromUrlAlloc
/// <summary>Creates a path from a file URL.</summary>
/// <param name="urlPath">The URL.</param>
/// <returns>
/// <para>The file path. If no path can be created, <c>string.Empty</c> is returned.</para>
/// <para>If <paramref name="urlPath"/> is <see langword="null"/>, <see langword="null"/> will also be returned.</para>
/// </returns>
[SecurityCritical]
internal static string PathCreateFromUrlAlloc(string urlPath)
{
if (!NativeMethods.IsAtLeastWindowsVista)
throw new PlatformNotSupportedException(Resources.Requires_Windows_Vista_Or_Higher);
if (urlPath == null)
return null;
StringBuilder buffer;
uint lastError = NativeMethods.PathCreateFromUrlAlloc(urlPath, out buffer, 0);
// Don't throw exception, but return string.Empty;
return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty;
}
#endregion // PathCreateFromUrlAlloc
#region PathFileExists
/// <summary>Determines whether a path to a file system object such as a file or folder is valid.</summary>
/// <param name="path">The full path of maximum length the maximum path length to the object to verify.</param>
/// <returns><see langword="true"/> if the file exists; <see langword="false"/> otherwise</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")]
[SecurityCritical]
public static bool PathFileExists(string path)
{
if (Utils.IsNullOrWhiteSpace(path))
return false;
// PathFileExists()
// In the ANSI version of this function, the name is limited to 248 characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
return NativeMethods.PathFileExists(Path.GetFullPathCore(null, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck | GetFullPathOptions.ContinueOnNonExist));
}
#endregion // PathFileExists
#region UrlIs
/// <summary>Tests whether a URL is a specified type.</summary>
/// <param name="url">The URL.</param>
/// <param name="urlType"></param>
/// <returns>
/// For all but one of the URL types, UrlIs returns <see langword="true"/> if the URL is the specified type, or <see langword="false"/> otherwise.
/// If UrlIs is set to <see cref="UrlType.IsAppliable"/>, UrlIs will attempt to determine the URL scheme.
/// If the function is able to determine a scheme, it returns <see langword="true"/>, or <see langword="false"/> otherwise.
/// </returns>
[SecurityCritical]
internal static bool UrlIs(string url, UrlType urlType)
{
return NativeMethods.UrlIs(url, urlType);
}
#endregion // UrlIs
#region UrlCreateFromPath
/// <summary>Converts a Microsoft MS-DOS path to a canonicalized URL.</summary>
/// <param name="path">The full MS-DOS path of maximum length <see cref="NativeMethods.MaxPath"/>.</param>
/// <returns>
/// <para>The URL. If no URL can be created <c>string.Empty</c> is returned.</para>
/// <para>If <paramref name="path"/> is <see langword="null"/>, <see langword="null"/> will also be returned.</para>
/// </returns>
[SecurityCritical]
internal static string UrlCreateFromPath(string path)
{
if (path == null)
return null;
// UrlCreateFromPath does not support extended paths.
string pathRp = Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars);
var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);
var bufferSize = (uint) buffer.Capacity;
uint lastError = NativeMethods.UrlCreateFromPath(pathRp, buffer, ref bufferSize, 0);
// Don't throw exception, but return null;
string url = buffer.ToString();
if (Utils.IsNullOrWhiteSpace(url))
url = string.Empty;
return lastError == Win32Errors.S_OK ? url : string.Empty;
}
#endregion // UrlCreateFromPath
#region UrlIsFileUrl
/// <summary>Tests a URL to determine if it is a file URL.</summary>
/// <param name="url">The URL.</param>
/// <returns><see langword="true"/> if the URL is a file URL, or <see langword="false"/> otherwise.</returns>
[SecurityCritical]
internal static bool UrlIsFileUrl(string url)
{
return NativeMethods.UrlIs(url, UrlType.IsFileUrl);
}
#endregion // UrlIsFileUrl
#region UrlIsNoHistory
/// <summary>Returns whether a URL is a URL that browsers typically do not include in navigation history.</summary>
/// <param name="url">The URL.</param>
/// <returns><see langword="true"/> if the URL is a URL that is not included in navigation history, or <see langword="false"/> otherwise.</returns>
[SecurityCritical]
internal static bool UrlIsNoHistory(string url)
{
return NativeMethods.UrlIs(url, UrlType.IsNoHistory);
}
#endregion // UrlIsNoHistory
#region UrlIsOpaque
/// <summary>Returns whether a URL is opaque.</summary>
/// <param name="url">The URL.</param>
/// <returns><see langword="true"/> if the URL is opaque, or <see langword="false"/> otherwise.</returns>
[SecurityCritical]
internal static bool UrlIsOpaque(string url)
{
return NativeMethods.UrlIs(url, UrlType.IsOpaque);
}
#endregion // UrlIsOpaque
#region Internal Methods
#region GetFileAssociationCore
/// <summary>Searches for and retrieves a file or protocol association-related string from the registry.</summary>
/// <param name="path">A path to a file.</param>
/// <param name="attributes">One or more <see cref="AssociationAttributes"/> attributes. Only one "InitXXX" attribute can be used.</param>
/// <param name="associationType">A <see cref="AssociationString"/> attribute.</param>
/// <returns>The associated file- or protocol-related string from the registry or <c>string.Empty</c> if no association can be found.</returns>
/// <exception cref="ArgumentNullException"/>
[SecurityCritical]
private static string GetFileAssociationCore(string path, AssociationAttributes attributes, AssociationString associationType)
{
if (Utils.IsNullOrWhiteSpace(path))
throw new ArgumentNullException("path");
attributes = attributes | AssociationAttributes.NoTruncate | AssociationAttributes.RemapRunDll;
uint bufferSize = NativeMethods.MaxPath;
StringBuilder buffer;
uint retVal;
do
{
buffer = new StringBuilder((int)bufferSize);
// AssocQueryString()
// In the ANSI version of this function, the name is limited to 248 characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2014-02-05: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
// However, the function fails when using Unicode format.
retVal = NativeMethods.AssocQueryString(attributes, associationType, path, null, buffer, out bufferSize);
// No Exception is thrown, just return empty string on error.
//switch (retVal)
//{
// // 0x80070483: No application is associated with the specified file for this operation.
// case 2147943555:
// case Win32Errors.E_POINTER:
// case Win32Errors.S_OK:
// break;
// default:
// NativeError.ThrowException(retVal);
// break;
//}
} while (retVal == Win32Errors.E_POINTER);
return buffer.ToString();
}
#endregion // GetFileAssociationCore
#region GetFileInfoCore
/// <summary>Retrieve information about an object in the file system, such as a file, folder, directory, or drive root.</summary>
/// <returns>A <see cref="Shell32.FileInfo"/> struct instance.</returns>
/// <remarks>
/// <para>You should call this function from a background thread.</para>
/// <para>Failure to do so could cause the UI to stop responding.</para>
/// <para>Unicode path are not supported.</para>
/// </remarks>
/// <param name="path">The path to the file system object which should not exceed the maximum path length in length. Both absolute and relative paths are valid.</param>
/// <param name="attributes">A <see cref="System.IO.FileAttributes"/> attribute.</param>
/// <param name="fileAttributes">A <see cref="FileAttributes"/> attribute.</param>
/// <param name="checkInvalidPathChars">Checks that the path contains only valid path-characters.</param>
/// <param name="continueOnException">
/// <para><see langword="true"/> suppress any Exception that might be thrown a result from a failure,</para>
/// <para>such as ACLs protected directories or non-accessible reparse points.</para>
/// </param>
[SecurityCritical]
internal static FileInfo GetFileInfoCore(string path, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool checkInvalidPathChars, bool continueOnException)
{
// Prevent possible crash.
FileInfo fileInfo = new FileInfo
{
DisplayName = string.Empty,
TypeName = string.Empty,
IconIndex = 0
};
if (!Utils.IsNullOrWhiteSpace(path))
{
// ShGetFileInfo()
// In the ANSI version of this function, the name is limited to 248 characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
// However, the function fails when using Unicode format.
IntPtr shGetFileInfo = NativeMethods.ShGetFileInfo(Path.GetRegularPathCore(path, checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : 0), attributes, out fileInfo, (uint) Marshal.SizeOf(fileInfo), fileAttributes);
if (shGetFileInfo == IntPtr.Zero && !continueOnException)
NativeError.ThrowException(Marshal.GetLastWin32Error(), path);
}
return fileInfo;
}
#endregion // GetFileInfoCore
#endregion // Internal Methods
#endregion // Methods
}
#endregion // AlphaFS
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#if !JSONNET_XMLDISABLE
using System.Xml;
#endif
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies the state of the <see cref="JsonWriter"/>.
/// </summary>
public enum WriteState
{
/// <summary>
/// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state.
/// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state.
/// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary>
Error,
/// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// An object is being written.
/// </summary>
Object,
/// <summary>
/// A array is being written.
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
Property,
/// <summary>
/// A write method has not been called.
/// </summary>
Start
}
/// <summary>
/// Specifies formatting options for the <see cref="JsonTextWriter"/>.
/// </summary>
public enum Formatting
{
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented
}
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
private enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Bytes,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] stateArray = new[] {
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
};
private int _top;
private readonly List<JTokenType> _stack;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get { return _top; }
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw new JsonWriterException("Invalid state: " + _currentState);
}
}
}
/// <summary>
/// Indicates how the output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JTokenType>(8);
_stack.Add(JTokenType.None);
_currentState = State.Start;
_formatting = Formatting.None;
CloseOutput = true;
}
private void Push(JTokenType value)
{
_top++;
if (_stack.Count <= _top)
_stack.Add(value);
else
_stack[_top] = value;
}
private JTokenType Pop()
{
JTokenType value = Peek();
_top--;
return value;
}
private JTokenType Peek()
{
return _stack[_top];
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
AutoComplete(JsonToken.StartObject);
Push(JTokenType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public virtual void WriteEndObject()
{
AutoCompleteClose(JsonToken.EndObject);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
AutoComplete(JsonToken.StartArray);
Push(JTokenType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
AutoCompleteClose(JsonToken.EndArray);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
AutoComplete(JsonToken.StartConstructor);
Push(JTokenType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
AutoCompleteClose(JsonToken.EndConstructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
AutoComplete(JsonToken.PropertyName);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth);
}
internal void WriteToken(JsonReader reader, int initialDepth)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0)
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment(reader.Value.ToString());
break;
case JsonToken.Integer:
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Float:
WriteValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
WriteValue((DateTime)reader.Value);
break;
case JsonToken.Raw:
WriteRawValue((string)reader.Value);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
}
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.Integer)
throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType);
long ticks = (long)reader.Value;
DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType);
WriteValue(date);
}
private bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
private bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
WriteEndObject();
break;
case JTokenType.Array:
WriteEndArray();
break;
case JTokenType.Constructor:
WriteEndConstructor();
break;
default:
throw new JsonWriterException("Unexpected type when writing end: " + type);
}
}
private void AutoCompleteAll()
{
while (_top > 0)
{
WriteEnd();
}
}
private JTokenType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JTokenType.Object;
case JsonToken.EndArray:
return JTokenType.Array;
case JsonToken.EndConstructor:
return JTokenType.Constructor;
default:
throw new JsonWriterException("No type for token: " + token);
}
}
private JsonToken GetCloseTokenForType(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
default:
throw new JsonWriterException("No close token for type: " + type);
}
}
private void AutoCompleteClose(JsonToken tokenBeingClosed)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
for (int i = 0; i < _top; i++)
{
int currentLevel = _top - i;
if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed))
{
levelsToComplete = i + 1;
break;
}
}
if (levelsToComplete == 0)
throw new JsonWriterException("No token to close.");
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
WriteEnd(token);
}
JTokenType currentLevelType = Peek();
switch (currentLevelType)
{
case JTokenType.Object:
_currentState = State.Object;
break;
case JTokenType.Array:
_currentState = State.Array;
break;
case JTokenType.Constructor:
_currentState = State.Array;
break;
case JTokenType.None:
_currentState = State.Start;
break;
default:
throw new JsonWriterException("Unknown JsonType: " + currentLevelType);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
int token;
switch (tokenBeingWritten)
{
default:
token = (int)tokenBeingWritten;
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// a value is being written
token = 7;
break;
}
// gets new state based on the current state and what is being written
State newState = stateArray[token][(int)_currentState];
if (newState == State.Error)
throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()));
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
else if (_currentState == State.Property)
{
if (_formatting == Formatting.Indented)
WriteIndentSpace();
}
WriteState writeState = WriteState;
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) ||
writeState == WriteState.Array || writeState == WriteState.Constructor)
{
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
AutoComplete(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
AutoComplete(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
//
public virtual void WriteValue(uint value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
//
public virtual void WriteValue(ulong value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
AutoComplete(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
//
public virtual void WriteValue(ushort value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
//
public virtual void WriteValue(sbyte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
AutoComplete(JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
AutoComplete(JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
//
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
//
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
//
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
//
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
return;
}
else if (value is IConvertible)
{
IConvertible convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
WriteValue(convertible.ToString(CultureInfo.InvariantCulture));
return;
case TypeCode.Char:
WriteValue(convertible.ToChar(CultureInfo.InvariantCulture));
return;
case TypeCode.Boolean:
WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture));
return;
case TypeCode.SByte:
WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture));
return;
case TypeCode.Int16:
WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt16:
WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.Int32:
WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Byte:
WriteValue(convertible.ToByte(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt32:
WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Int64:
WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt64:
WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.Single:
WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture));
return;
case TypeCode.Double:
WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture));
return;
case TypeCode.DateTime:
WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture));
return;
case TypeCode.Decimal:
WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture));
return;
case TypeCode.DBNull:
WriteNull();
return;
}
}
else if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
return;
}
else if (value is byte[])
{
WriteValue((byte[])value);
return;
}
else if (value is Guid)
{
WriteValue((Guid)value);
return;
}
else if (value is Uri)
{
WriteValue((Uri)value);
return;
}
else if (value is TimeSpan)
{
WriteValue((TimeSpan)value);
return;
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
AutoComplete(JsonToken.Comment);
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw new JsonWriterException("Only white space characters should be used.");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (WriteState != WriteState.Closed)
Close();
}
}
}
#endif
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Parcel : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Parcel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public void writeInt(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeInt", "(I)V", ref global::android.os.Parcel._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public int readInt()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Parcel.staticClass, "readInt", "()I", ref global::android.os.Parcel._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public long readLong()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.os.Parcel.staticClass, "readLong", "()J", ref global::android.os.Parcel._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public byte readByte()
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::android.os.Parcel.staticClass, "readByte", "()B", ref global::android.os.Parcel._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
public void writeLong(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeLong", "(J)V", ref global::android.os.Parcel._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public void writeByte(byte arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeByte", "(B)V", ref global::android.os.Parcel._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public void writeFloat(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeFloat", "(F)V", ref global::android.os.Parcel._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public float readFloat()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.os.Parcel.staticClass, "readFloat", "()F", ref global::android.os.Parcel._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public double readDouble()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.os.Parcel.staticClass, "readDouble", "()D", ref global::android.os.Parcel._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public global::java.lang.String readString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.os.Parcel.staticClass, "readString", "()Ljava/lang/String;", ref global::android.os.Parcel._m9) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m10;
public int dataSize()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Parcel.staticClass, "dataSize", "()I", ref global::android.os.Parcel._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public void writeValue(java.lang.Object arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeValue", "(Ljava/lang/Object;)V", ref global::android.os.Parcel._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public void writeString(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeString", "(Ljava/lang/String;)V", ref global::android.os.Parcel._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public static global::android.os.Parcel obtain()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Parcel._m13.native == global::System.IntPtr.Zero)
global::android.os.Parcel._m13 = @__env.GetStaticMethodIDNoThrow(global::android.os.Parcel.staticClass, "obtain", "()Landroid/os/Parcel;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.os.Parcel>(@__env.CallStaticObjectMethod(android.os.Parcel.staticClass, global::android.os.Parcel._m13)) as android.os.Parcel;
}
private static global::MonoJavaBridge.MethodId _m14;
public void recycle()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "recycle", "()V", ref global::android.os.Parcel._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public bool hasFileDescriptors()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Parcel.staticClass, "hasFileDescriptors", "()Z", ref global::android.os.Parcel._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public int dataAvail()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Parcel.staticClass, "dataAvail", "()I", ref global::android.os.Parcel._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public int dataPosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Parcel.staticClass, "dataPosition", "()I", ref global::android.os.Parcel._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
public int dataCapacity()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Parcel.staticClass, "dataCapacity", "()I", ref global::android.os.Parcel._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
public void setDataSize(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "setDataSize", "(I)V", ref global::android.os.Parcel._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m20;
public void setDataPosition(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "setDataPosition", "(I)V", ref global::android.os.Parcel._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public void setDataCapacity(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "setDataCapacity", "(I)V", ref global::android.os.Parcel._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public byte[] marshall()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.os.Parcel.staticClass, "marshall", "()[B", ref global::android.os.Parcel._m22) as byte[];
}
private static global::MonoJavaBridge.MethodId _m23;
public void unmarshall(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "unmarshall", "([BII)V", ref global::android.os.Parcel._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m24;
public void appendFrom(android.os.Parcel arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "appendFrom", "(Landroid/os/Parcel;II)V", ref global::android.os.Parcel._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m25;
public void writeInterfaceToken(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeInterfaceToken", "(Ljava/lang/String;)V", ref global::android.os.Parcel._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public void enforceInterface(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "enforceInterface", "(Ljava/lang/String;)V", ref global::android.os.Parcel._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public void writeByteArray(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeByteArray", "([BII)V", ref global::android.os.Parcel._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m28;
public void writeByteArray(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeByteArray", "([B)V", ref global::android.os.Parcel._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public void writeDouble(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeDouble", "(D)V", ref global::android.os.Parcel._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public void writeStrongBinder(android.os.IBinder arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeStrongBinder", "(Landroid/os/IBinder;)V", ref global::android.os.Parcel._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public void writeStrongInterface(android.os.IInterface arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeStrongInterface", "(Landroid/os/IInterface;)V", ref global::android.os.Parcel._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void writeStrongInterface(global::android.os.IInterfaceDelegate arg0)
{
writeStrongInterface((global::android.os.IInterfaceDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m32;
public void writeFileDescriptor(java.io.FileDescriptor arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeFileDescriptor", "(Ljava/io/FileDescriptor;)V", ref global::android.os.Parcel._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public void writeMap(java.util.Map arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeMap", "(Ljava/util/Map;)V", ref global::android.os.Parcel._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public void writeBundle(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeBundle", "(Landroid/os/Bundle;)V", ref global::android.os.Parcel._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public void writeList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
public void writeArray(java.lang.Object[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeArray", "([Ljava/lang/Object;)V", ref global::android.os.Parcel._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m37;
public void writeSparseArray(android.util.SparseArray arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeSparseArray", "(Landroid/util/SparseArray;)V", ref global::android.os.Parcel._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m38;
public void writeSparseBooleanArray(android.util.SparseBooleanArray arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeSparseBooleanArray", "(Landroid/util/SparseBooleanArray;)V", ref global::android.os.Parcel._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m39;
public void writeBooleanArray(bool[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeBooleanArray", "([Z)V", ref global::android.os.Parcel._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m40;
public bool[] createBooleanArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<bool>(this, global::android.os.Parcel.staticClass, "createBooleanArray", "()[Z", ref global::android.os.Parcel._m40) as bool[];
}
private static global::MonoJavaBridge.MethodId _m41;
public void readBooleanArray(bool[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readBooleanArray", "([Z)V", ref global::android.os.Parcel._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m42;
public void writeCharArray(char[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeCharArray", "([C)V", ref global::android.os.Parcel._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m43;
public char[] createCharArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<char>(this, global::android.os.Parcel.staticClass, "createCharArray", "()[C", ref global::android.os.Parcel._m43) as char[];
}
private static global::MonoJavaBridge.MethodId _m44;
public void readCharArray(char[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readCharArray", "([C)V", ref global::android.os.Parcel._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m45;
public void writeIntArray(int[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeIntArray", "([I)V", ref global::android.os.Parcel._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m46;
public int[] createIntArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<int>(this, global::android.os.Parcel.staticClass, "createIntArray", "()[I", ref global::android.os.Parcel._m46) as int[];
}
private static global::MonoJavaBridge.MethodId _m47;
public void readIntArray(int[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readIntArray", "([I)V", ref global::android.os.Parcel._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m48;
public void writeLongArray(long[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeLongArray", "([J)V", ref global::android.os.Parcel._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m49;
public long[] createLongArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<long>(this, global::android.os.Parcel.staticClass, "createLongArray", "()[J", ref global::android.os.Parcel._m49) as long[];
}
private static global::MonoJavaBridge.MethodId _m50;
public void readLongArray(long[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readLongArray", "([J)V", ref global::android.os.Parcel._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m51;
public void writeFloatArray(float[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeFloatArray", "([F)V", ref global::android.os.Parcel._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m52;
public float[] createFloatArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<float>(this, global::android.os.Parcel.staticClass, "createFloatArray", "()[F", ref global::android.os.Parcel._m52) as float[];
}
private static global::MonoJavaBridge.MethodId _m53;
public void readFloatArray(float[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readFloatArray", "([F)V", ref global::android.os.Parcel._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m54;
public void writeDoubleArray(double[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeDoubleArray", "([D)V", ref global::android.os.Parcel._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m55;
public double[] createDoubleArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<double>(this, global::android.os.Parcel.staticClass, "createDoubleArray", "()[D", ref global::android.os.Parcel._m55) as double[];
}
private static global::MonoJavaBridge.MethodId _m56;
public void readDoubleArray(double[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readDoubleArray", "([D)V", ref global::android.os.Parcel._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m57;
public void writeStringArray(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeStringArray", "([Ljava/lang/String;)V", ref global::android.os.Parcel._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m58;
public global::java.lang.String[] createStringArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::android.os.Parcel.staticClass, "createStringArray", "()[Ljava/lang/String;", ref global::android.os.Parcel._m58) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m59;
public void readStringArray(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readStringArray", "([Ljava/lang/String;)V", ref global::android.os.Parcel._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m60;
public void writeBinderArray(android.os.IBinder[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeBinderArray", "([Landroid/os/IBinder;)V", ref global::android.os.Parcel._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m61;
public global::android.os.IBinder[] createBinderArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<android.os.IBinder>(this, global::android.os.Parcel.staticClass, "createBinderArray", "()[Landroid/os/IBinder;", ref global::android.os.Parcel._m61) as android.os.IBinder[];
}
private static global::MonoJavaBridge.MethodId _m62;
public void readBinderArray(android.os.IBinder[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readBinderArray", "([Landroid/os/IBinder;)V", ref global::android.os.Parcel._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m63;
public void writeTypedList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeTypedList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m64;
public void writeStringList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeStringList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m65;
public void writeBinderList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeBinderList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m66;
public void writeTypedArray(android.os.Parcelable[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeTypedArray", "([Landroid/os/Parcelable;I)V", ref global::android.os.Parcel._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m67;
public void writeParcelable(android.os.Parcelable arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeParcelable", "(Landroid/os/Parcelable;I)V", ref global::android.os.Parcel._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m68;
public void writeSerializable(java.io.Serializable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeSerializable", "(Ljava/io/Serializable;)V", ref global::android.os.Parcel._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m69;
public void writeException(java.lang.Exception arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeException", "(Ljava/lang/Exception;)V", ref global::android.os.Parcel._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m70;
public void writeNoException()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeNoException", "()V", ref global::android.os.Parcel._m70);
}
private static global::MonoJavaBridge.MethodId _m71;
public void readException()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readException", "()V", ref global::android.os.Parcel._m71);
}
private static global::MonoJavaBridge.MethodId _m72;
public void readException(int arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readException", "(ILjava/lang/String;)V", ref global::android.os.Parcel._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m73;
public global::android.os.IBinder readStrongBinder()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.IBinder>(this, global::android.os.Parcel.staticClass, "readStrongBinder", "()Landroid/os/IBinder;", ref global::android.os.Parcel._m73) as android.os.IBinder;
}
private static global::MonoJavaBridge.MethodId _m74;
public global::android.os.ParcelFileDescriptor readFileDescriptor()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readFileDescriptor", "()Landroid/os/ParcelFileDescriptor;", ref global::android.os.Parcel._m74) as android.os.ParcelFileDescriptor;
}
private static global::MonoJavaBridge.MethodId _m75;
public void readMap(java.util.Map arg0, java.lang.ClassLoader arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readMap", "(Ljava/util/Map;Ljava/lang/ClassLoader;)V", ref global::android.os.Parcel._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m76;
public void readList(java.util.List arg0, java.lang.ClassLoader arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readList", "(Ljava/util/List;Ljava/lang/ClassLoader;)V", ref global::android.os.Parcel._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m77;
public global::java.util.HashMap readHashMap(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readHashMap", "(Ljava/lang/ClassLoader;)Ljava/util/HashMap;", ref global::android.os.Parcel._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.HashMap;
}
private static global::MonoJavaBridge.MethodId _m78;
public global::android.os.Bundle readBundle()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.os.Parcel.staticClass, "readBundle", "()Landroid/os/Bundle;", ref global::android.os.Parcel._m78) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m79;
public global::android.os.Bundle readBundle(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.os.Parcel.staticClass, "readBundle", "(Ljava/lang/ClassLoader;)Landroid/os/Bundle;", ref global::android.os.Parcel._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m80;
public byte[] createByteArray()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.os.Parcel.staticClass, "createByteArray", "()[B", ref global::android.os.Parcel._m80) as byte[];
}
private static global::MonoJavaBridge.MethodId _m81;
public void readByteArray(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readByteArray", "([B)V", ref global::android.os.Parcel._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m82;
public global::java.util.ArrayList readArrayList(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readArrayList", "(Ljava/lang/ClassLoader;)Ljava/util/ArrayList;", ref global::android.os.Parcel._m82, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m83;
public global::java.lang.Object[] readArray(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::android.os.Parcel.staticClass, "readArray", "(Ljava/lang/ClassLoader;)[Ljava/lang/Object;", ref global::android.os.Parcel._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object[];
}
private static global::MonoJavaBridge.MethodId _m84;
public global::android.util.SparseArray readSparseArray(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readSparseArray", "(Ljava/lang/ClassLoader;)Landroid/util/SparseArray;", ref global::android.os.Parcel._m84, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.util.SparseArray;
}
private static global::MonoJavaBridge.MethodId _m85;
public global::android.util.SparseBooleanArray readSparseBooleanArray()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readSparseBooleanArray", "()Landroid/util/SparseBooleanArray;", ref global::android.os.Parcel._m85) as android.util.SparseBooleanArray;
}
private static global::MonoJavaBridge.MethodId _m86;
public global::java.util.ArrayList createTypedArrayList(android.os.Parcelable_Creator arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "createTypedArrayList", "(Landroid/os/Parcelable$Creator;)Ljava/util/ArrayList;", ref global::android.os.Parcel._m86, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m87;
public void readTypedList(java.util.List arg0, android.os.Parcelable_Creator arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readTypedList", "(Ljava/util/List;Landroid/os/Parcelable$Creator;)V", ref global::android.os.Parcel._m87, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m88;
public global::java.util.ArrayList createStringArrayList()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "createStringArrayList", "()Ljava/util/ArrayList;", ref global::android.os.Parcel._m88) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m89;
public global::java.util.ArrayList createBinderArrayList()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "createBinderArrayList", "()Ljava/util/ArrayList;", ref global::android.os.Parcel._m89) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m90;
public void readStringList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readStringList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m90, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m91;
public void readBinderList(java.util.List arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readBinderList", "(Ljava/util/List;)V", ref global::android.os.Parcel._m91, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m92;
public global::java.lang.Object[] createTypedArray(android.os.Parcelable_Creator arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::android.os.Parcel.staticClass, "createTypedArray", "(Landroid/os/Parcelable$Creator;)[Ljava/lang/Object;", ref global::android.os.Parcel._m92, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object[];
}
private static global::MonoJavaBridge.MethodId _m93;
public void readTypedArray(java.lang.Object[] arg0, android.os.Parcelable_Creator arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "readTypedArray", "([Ljava/lang/Object;Landroid/os/Parcelable$Creator;)V", ref global::android.os.Parcel._m93, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m94;
public void writeParcelableArray(android.os.Parcelable[] arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Parcel.staticClass, "writeParcelableArray", "([Landroid/os/Parcelable;I)V", ref global::android.os.Parcel._m94, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m95;
public global::java.lang.Object readValue(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Parcel.staticClass, "readValue", "(Ljava/lang/ClassLoader;)Ljava/lang/Object;", ref global::android.os.Parcel._m95, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m96;
public global::android.os.Parcelable readParcelable(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.Parcelable>(this, global::android.os.Parcel.staticClass, "readParcelable", "(Ljava/lang/ClassLoader;)Landroid/os/Parcelable;", ref global::android.os.Parcel._m96, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Parcelable;
}
private static global::MonoJavaBridge.MethodId _m97;
public global::android.os.Parcelable[] readParcelableArray(java.lang.ClassLoader arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<android.os.Parcelable>(this, global::android.os.Parcel.staticClass, "readParcelableArray", "(Ljava/lang/ClassLoader;)[Landroid/os/Parcelable;", ref global::android.os.Parcel._m97, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Parcelable[];
}
private static global::MonoJavaBridge.MethodId _m98;
public global::java.io.Serializable readSerializable()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.io.Serializable>(this, global::android.os.Parcel.staticClass, "readSerializable", "()Ljava/io/Serializable;", ref global::android.os.Parcel._m98) as java.io.Serializable;
}
internal static global::MonoJavaBridge.FieldId _STRING_CREATOR4010;
public static global::android.os.Parcelable_Creator STRING_CREATOR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.os.Parcel.staticClass, _STRING_CREATOR4010)) as android.os.Parcelable_Creator;
}
}
static Parcel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Parcel.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Parcel"));
global::android.os.Parcel._STRING_CREATOR4010 = @__env.GetStaticFieldIDNoThrow(global::android.os.Parcel.staticClass, "STRING_CREATOR", "Landroid/os/Parcelable$Creator;");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace T5Suite2
{
public partial class frmAutotuneSettings : DevExpress.XtraEditors.XtraForm
{
public frmAutotuneSettings()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void simpleButton2_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
public int CellStableTime_ms
{
get
{
return (int)spinEdit1.Value;
}
set
{
spinEdit1.Value = value;
}
}
public int IgnitionCellStableTime_ms
{
get
{
return (int)spinEdit11.Value;
}
set
{
spinEdit11.Value = value;
}
}
public int MinimumEngineSpeedForIgnitionTuning
{
get
{
return (int)spinEdit12.Value;
}
set
{
spinEdit12.Value = value;
}
}
public double MaximumIgnitionAdvancePerSession
{
get
{
return Convert.ToDouble(spinEdit10.Value);
}
set
{
spinEdit10.Value = Convert.ToDecimal(value);
}
}
public double IgnitionAdvancePerCycle
{
get
{
return Convert.ToDouble(spinEdit13.Value);
}
set
{
spinEdit13.Value = Convert.ToDecimal(value);
}
}
public double IgnitionRetardFirstKnock
{
get
{
return Convert.ToDouble(spinEdit14.Value);
}
set
{
spinEdit14.Value = Convert.ToDecimal(value);
}
}
public double IgnitionRetardFurtherKnocks
{
get
{
return Convert.ToDouble(spinEdit15.Value);
}
set
{
spinEdit15.Value = Convert.ToDecimal(value);
}
}
public double GlobalMaximumIgnitionAdvance
{
get
{
return Convert.ToDouble(spinEdit16.Value);
}
set
{
spinEdit16.Value = Convert.ToDecimal(value);
}
}
public int CorrectionPercentage
{
get
{
return (int)spinEdit3.Value;
}
set
{
spinEdit3.Value = value;
}
}
public int AreaCorrectionPercentage
{
get
{
return (int)spinEdit4.Value;
}
set
{
spinEdit4.Value = value;
}
}
public int AcceptableTargetErrorPercentage
{
get
{
return (int)spinEdit6.Value;
}
set
{
spinEdit6.Value = value;
}
}
public int MaximumAdjustmentPerCyclePercentage
{
get
{
return (int)spinEdit7.Value;
}
set
{
spinEdit7.Value = value;
}
}
public int EnrichmentFilter
{
get
{
return (int)spinEdit5.Value;
}
set
{
spinEdit5.Value = value;
}
}
public int FuelCutDecayTime_ms
{
get
{
return (int)spinEdit2.Value;
}
set
{
spinEdit2.Value = value;
}
}
public bool DiscardFuelcutMeasurements
{
get
{
return checkEdit1.Checked;
}
set
{
checkEdit1.Checked = value;
}
}
public bool DisableClosedLoopOnStartAutotune
{
get
{
return checkEdit4.Checked;
}
set
{
checkEdit4.Checked = value;
}
}
public bool PlayCellProcessedSound
{
get
{
return checkEdit5.Checked;
}
set
{
checkEdit5.Checked = value;
}
}
public bool CapIgnitionMap
{
get
{
return checkEdit8.Checked;
}
set
{
checkEdit8.Checked = value;
}
}
public bool ResetFuelTrims
{
get
{
return checkEdit7.Checked;
}
set
{
checkEdit7.Checked = value;
}
}
public bool AllowIdleAutoTune
{
get
{
return checkEdit6.Checked;
}
set
{
checkEdit6.Checked = value;
}
}
public bool DiscardClosedThrottleMeasurements
{
get
{
return checkEdit2.Checked;
}
set
{
checkEdit2.Checked = value;
}
}
public bool AutoUpdateFuelMap
{
get
{
return checkEdit3.Checked;
}
set
{
checkEdit3.Checked = value;
}
}
public int MinimumAFRMeasurements
{
get
{
return (int)spinEdit8.Value;
}
set
{
spinEdit8.Value = value;
}
}
public int MaximumAFRDeviance
{
get
{
return (int)spinEdit9.Value;
}
set
{
spinEdit9.Value = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SphinxDemo.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Diagnostics;
using System.Security.Cryptography;
namespace System.DirectoryServices.ActiveDirectory
{
internal enum TRUSTED_INFORMATION_CLASS
{
TrustedDomainNameInformation = 1,
TrustedControllersInformation,
TrustedPosixOffsetInformation,
TrustedPasswordInformation,
TrustedDomainInformationBasic,
TrustedDomainInformationEx,
TrustedDomainAuthInformation,
TrustedDomainFullInformation,
TrustedDomainAuthInformationInternal,
TrustedDomainFullInformationInternal,
TrustedDomainInformationEx2Internal,
TrustedDomainFullInformation2Internal
}
[Flags]
internal enum TRUST_ATTRIBUTE
{
TRUST_ATTRIBUTE_NON_TRANSITIVE = 0x00000001,
TRUST_ATTRIBUTE_UPLEVEL_ONLY = 0x00000002,
TRUST_ATTRIBUTE_QUARANTINED_DOMAIN = 0x00000004,
TRUST_ATTRIBUTE_FOREST_TRANSITIVE = 0x00000008,
TRUST_ATTRIBUTE_CROSS_ORGANIZATION = 0x00000010,
TRUST_ATTRIBUTE_WITHIN_FOREST = 0x00000020,
TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL = 0x00000040
}
internal class TrustHelper
{
private const int STATUS_OBJECT_NAME_NOT_FOUND = 2;
internal const int ERROR_NOT_FOUND = 1168;
internal const int NETLOGON_QUERY_LEVEL = 2;
internal const int NETLOGON_CONTROL_REDISCOVER = 5;
private const int NETLOGON_CONTROL_TC_VERIFY = 10;
private const int NETLOGON_VERIFY_STATUS_RETURNED = 0x80;
private const int PASSWORD_LENGTH = 15;
private const int TRUST_AUTH_TYPE_CLEAR = 2;
private const int policyDnsDomainInformation = 12;
private const int TRUSTED_SET_POSIX = 0x00000010;
private const int TRUSTED_SET_AUTH = 0x00000020;
internal const int TRUST_TYPE_DOWNLEVEL = 0x00000001;
internal const int TRUST_TYPE_UPLEVEL = 0x00000002;
internal const int TRUST_TYPE_MIT = 0x00000003;
private const int ERROR_ALREADY_EXISTS = 183;
private const int ERROR_INVALID_LEVEL = 124;
private static readonly char[] s_punctuations = "!@#$%^&*()_-+=[{]};:>|./?".ToCharArray();
private TrustHelper() { }
internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool isForest)
{
PolicySafeHandle handle = null;
IntPtr buffer = (IntPtr)0;
LSA_UNICODE_STRING trustedDomainName = null;
bool impersonated = false;
IntPtr target = (IntPtr)0;
string serverName = null;
// get policy server name
serverName = Utils.GetPolicyServerName(context, isForest, false, sourceName);
impersonated = Utils.Impersonate(context);
try
{
try
{
// get the policy handle first
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
Debug.Assert(buffer != (IntPtr)0);
TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
Marshal.PtrToStructure(buffer, domainInfo);
// validate this is the trust that the user refers to
ValidateTrustAttribute(domainInfo, isForest, sourceName, targetName);
// get the attribute of the trust
// selective authentication info
if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION)
{
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION) == 0)
return false;
else
return true;
}
// sid filtering behavior for forest trust
else if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL)
{
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL) == 0)
return true;
else
return false;
}
// sid filtering behavior for domain trust
else if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN)
{
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN) == 0)
return false;
else
return true;
}
else
{
// should not happen
throw new ArgumentException(nameof(attribute));
}
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
}
}
catch { throw; }
}
internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool status, bool isForest)
{
PolicySafeHandle handle = null;
IntPtr buffer = (IntPtr)0;
IntPtr newInfo = (IntPtr)0;
LSA_UNICODE_STRING trustedDomainName = null;
bool impersonated = false;
IntPtr target = (IntPtr)0;
string serverName = null;
serverName = Utils.GetPolicyServerName(context, isForest, false, sourceName);
impersonated = Utils.Impersonate(context);
try
{
try
{
// get the policy handle first
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// get the trusted domain information
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
Debug.Assert(buffer != (IntPtr)0);
// get the managed structre representation
TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
Marshal.PtrToStructure(buffer, domainInfo);
// validate this is the trust that the user refers to
ValidateTrustAttribute(domainInfo, isForest, sourceName, targetName);
// change the attribute value properly
// selective authentication
if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION)
{
if (status)
{
// turns on selective authentication
domainInfo.TrustAttributes |= TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION;
}
else
{
// turns off selective authentication
domainInfo.TrustAttributes &= ~(TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION);
}
}
// user wants to change sid filtering behavior for forest trust
else if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL)
{
if (status)
{
// user wants sid filtering behavior
domainInfo.TrustAttributes &= ~(TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL);
}
else
{
// users wants to turn off sid filtering behavior
domainInfo.TrustAttributes |= TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL;
}
}
// user wants to change sid filtering behavior for external trust
else if (attribute == TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN)
{
if (status)
{
// user wants sid filtering behavior
domainInfo.TrustAttributes |= TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN;
}
else
{
// user wants to turn off sid filtering behavior
domainInfo.TrustAttributes &= ~(TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN);
}
}
else
{
throw new ArgumentException(nameof(attribute));
}
// reconstruct the unmanaged structure to set it back
newInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TRUSTED_DOMAIN_INFORMATION_EX)));
Marshal.StructureToPtr(domainInfo, newInfo, false);
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo);
if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
}
return;
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
if (newInfo != (IntPtr)0)
Marshal.FreeHGlobal(newInfo);
}
}
catch { throw; }
}
internal static void DeleteTrust(DirectoryContext sourceContext, string sourceName, string targetName, bool isForest)
{
PolicySafeHandle policyHandle = null;
LSA_UNICODE_STRING trustedDomainName = null;
int win32Error = 0;
bool impersonated = false;
IntPtr target = (IntPtr)0;
string serverName = null;
IntPtr buffer = (IntPtr)0;
serverName = Utils.GetPolicyServerName(sourceContext, isForest, false, sourceName);
impersonated = Utils.Impersonate(sourceContext);
try
{
try
{
// get the policy handle
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// get trust information
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
if (result != 0)
{
win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
Debug.Assert(buffer != (IntPtr)0);
try
{
TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
Marshal.PtrToStructure(buffer, domainInfo);
// validate this is the trust that the user refers to
ValidateTrustAttribute(domainInfo, isForest, sourceName, targetName);
// delete the trust
result = UnsafeNativeMethods.LsaDeleteTrustedDomain(policyHandle, domainInfo.Sid);
if (result != 0)
{
win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
}
finally
{
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
}
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
}
}
catch { throw; }
}
internal static void VerifyTrust(DirectoryContext context, string sourceName, string targetName, bool isForest, TrustDirection direction, bool forceSecureChannelReset, string preferredTargetServer)
{
PolicySafeHandle policyHandle = null;
LSA_UNICODE_STRING trustedDomainName = null;
int win32Error = 0;
IntPtr data = (IntPtr)0;
IntPtr ptr = (IntPtr)0;
IntPtr buffer1 = (IntPtr)0;
IntPtr buffer2 = (IntPtr)0;
bool impersonated = true;
IntPtr target = (IntPtr)0;
string policyServerName = null;
policyServerName = Utils.GetPolicyServerName(context, isForest, false, sourceName);
impersonated = Utils.Impersonate(context);
try
{
try
{
// get the policy handle
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(policyServerName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// validate the trust existence
ValidateTrust(policyHandle, trustedDomainName, sourceName, targetName, isForest, (int)direction, policyServerName); // need to verify direction
if (preferredTargetServer == null)
data = Marshal.StringToHGlobalUni(targetName);
else
// this is the case that we need to specifically go to a particular server. This is the way to tell netlogon to do that.
data = Marshal.StringToHGlobalUni(targetName + "\\" + preferredTargetServer);
ptr = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(ptr, data);
if (!forceSecureChannelReset)
{
win32Error = UnsafeNativeMethods.I_NetLogonControl2(policyServerName, NETLOGON_CONTROL_TC_VERIFY, NETLOGON_QUERY_LEVEL, ptr, out buffer1);
if (win32Error == 0)
{
NETLOGON_INFO_2 info = new NETLOGON_INFO_2();
Marshal.PtrToStructure(buffer1, info);
if ((info.netlog2_flags & NETLOGON_VERIFY_STATUS_RETURNED) != 0)
{
int result = info.netlog2_pdc_connection_status;
if (result == 0)
{
// verification succeeded
return;
}
else
{
// don't really know which server is down, the source or the target
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
}
else
{
int result = info.netlog2_tc_connection_status;
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
}
else
{
if (win32Error == ERROR_INVALID_LEVEL)
{
// it is pre-win2k SP3 dc that does not support NETLOGON_CONTROL_TC_VERIFY
throw new NotSupportedException(SR.TrustVerificationNotSupport);
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error);
}
}
}
else
{
// then try secure channel reset
win32Error = UnsafeNativeMethods.I_NetLogonControl2(policyServerName, NETLOGON_CONTROL_REDISCOVER, NETLOGON_QUERY_LEVEL, ptr, out buffer2);
if (win32Error != 0)
// don't really know which server is down, the source or the target
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error);
}
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (ptr != (IntPtr)0)
Marshal.FreeHGlobal(ptr);
if (data != (IntPtr)0)
Marshal.FreeHGlobal(data);
if (buffer1 != (IntPtr)0)
UnsafeNativeMethods.NetApiBufferFree(buffer1);
if (buffer2 != (IntPtr)0)
UnsafeNativeMethods.NetApiBufferFree(buffer2);
}
}
catch { throw; }
}
internal static void CreateTrust(DirectoryContext sourceContext, string sourceName, DirectoryContext targetContext, string targetName, bool isForest, TrustDirection direction, string password)
{
LSA_AUTH_INFORMATION AuthData = null;
TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = null;
TRUSTED_DOMAIN_INFORMATION_EX tdi = null;
IntPtr fileTime = (IntPtr)0;
IntPtr unmanagedPassword = (IntPtr)0;
IntPtr info = (IntPtr)0;
IntPtr domainHandle = (IntPtr)0;
PolicySafeHandle policyHandle = null;
IntPtr unmanagedAuthData = (IntPtr)0;
bool impersonated = false;
string serverName = null;
// get the domain info first
info = GetTrustedDomainInfo(targetContext, targetName, isForest);
try
{
try
{
POLICY_DNS_DOMAIN_INFO domainInfo = new POLICY_DNS_DOMAIN_INFO();
Marshal.PtrToStructure(info, domainInfo);
AuthData = new LSA_AUTH_INFORMATION();
fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime)));
UnsafeNativeMethods.GetSystemTimeAsFileTime(fileTime);
// set the time
FileTime tmp = new FileTime();
Marshal.PtrToStructure(fileTime, tmp);
AuthData.LastUpdateTime = new LARGE_INTEGER();
AuthData.LastUpdateTime.lowPart = tmp.lower;
AuthData.LastUpdateTime.highPart = tmp.higher;
AuthData.AuthType = TRUST_AUTH_TYPE_CLEAR;
unmanagedPassword = Marshal.StringToHGlobalUni(password);
AuthData.AuthInfo = unmanagedPassword;
AuthData.AuthInfoLength = password.Length * 2; // sizeof(WCHAR)
unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
if ((direction & TrustDirection.Inbound) != 0)
{
AuthInfoEx.IncomingAuthInfos = 1;
AuthInfoEx.IncomingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.IncomingPreviousAuthenticationInformation = (IntPtr)0;
}
if ((direction & TrustDirection.Outbound) != 0)
{
AuthInfoEx.OutgoingAuthInfos = 1;
AuthInfoEx.OutgoingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0;
}
tdi = new TRUSTED_DOMAIN_INFORMATION_EX();
tdi.FlatName = domainInfo.Name;
tdi.Name = domainInfo.DnsDomainName;
tdi.Sid = domainInfo.Sid;
tdi.TrustType = TRUST_TYPE_UPLEVEL;
tdi.TrustDirection = (int)direction;
if (isForest)
{
tdi.TrustAttributes = TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE;
}
else
{
tdi.TrustAttributes = TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_QUARANTINED_DOMAIN;
}
// get server name
serverName = Utils.GetPolicyServerName(sourceContext, isForest, false, sourceName);
// do impersonation and get policy handle
impersonated = Utils.Impersonate(sourceContext);
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
int result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle);
if (result != 0)
{
result = UnsafeNativeMethods.LsaNtStatusToWinError(result);
if (result == ERROR_ALREADY_EXISTS)
{
if (isForest)
throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingForestTrust, sourceName, targetName));
else
throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingDomainTrust, sourceName, targetName));
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName);
}
}
finally
{
if (impersonated)
Utils.Revert();
if (fileTime != (IntPtr)0)
Marshal.FreeHGlobal(fileTime);
if (domainHandle != (IntPtr)0)
UnsafeNativeMethods.LsaClose(domainHandle);
if (info != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(info);
if (unmanagedPassword != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedPassword);
if (unmanagedAuthData != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedAuthData);
}
}
catch { throw; }
}
internal static string UpdateTrust(DirectoryContext context, string sourceName, string targetName, string password, bool isForest)
{
PolicySafeHandle handle = null;
IntPtr buffer = (IntPtr)0;
LSA_UNICODE_STRING trustedDomainName = null;
IntPtr newBuffer = (IntPtr)0;
bool impersonated = false;
LSA_AUTH_INFORMATION AuthData = null;
IntPtr fileTime = (IntPtr)0;
IntPtr unmanagedPassword = (IntPtr)0;
IntPtr unmanagedAuthData = (IntPtr)0;
TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = null;
TrustDirection direction;
IntPtr target = (IntPtr)0;
string serverName = null;
serverName = Utils.GetPolicyServerName(context, isForest, false, sourceName);
impersonated = Utils.Impersonate(context);
try
{
try
{
// get the policy handle first
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// get the trusted domain information
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
// get the managed structre representation
TRUSTED_DOMAIN_FULL_INFORMATION domainInfo = new TRUSTED_DOMAIN_FULL_INFORMATION();
Marshal.PtrToStructure(buffer, domainInfo);
// validate the trust attribute first
ValidateTrustAttribute(domainInfo.Information, isForest, sourceName, targetName);
// get trust direction
direction = (TrustDirection)domainInfo.Information.TrustDirection;
// change the attribute value properly
AuthData = new LSA_AUTH_INFORMATION();
fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime)));
UnsafeNativeMethods.GetSystemTimeAsFileTime(fileTime);
// set the time
FileTime tmp = new FileTime();
Marshal.PtrToStructure(fileTime, tmp);
AuthData.LastUpdateTime = new LARGE_INTEGER();
AuthData.LastUpdateTime.lowPart = tmp.lower;
AuthData.LastUpdateTime.highPart = tmp.higher;
AuthData.AuthType = TRUST_AUTH_TYPE_CLEAR;
unmanagedPassword = Marshal.StringToHGlobalUni(password);
AuthData.AuthInfo = unmanagedPassword;
AuthData.AuthInfoLength = password.Length * 2;
unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
if ((direction & TrustDirection.Inbound) != 0)
{
AuthInfoEx.IncomingAuthInfos = 1;
AuthInfoEx.IncomingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.IncomingPreviousAuthenticationInformation = (IntPtr)0;
}
if ((direction & TrustDirection.Outbound) != 0)
{
AuthInfoEx.OutgoingAuthInfos = 1;
AuthInfoEx.OutgoingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0;
}
// reconstruct the unmanaged structure to set it back
domainInfo.AuthInformation = AuthInfoEx;
newBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TRUSTED_DOMAIN_FULL_INFORMATION)));
Marshal.StructureToPtr(domainInfo, newBuffer, false);
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
}
return serverName;
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
if (newBuffer != (IntPtr)0)
Marshal.FreeHGlobal(newBuffer);
if (fileTime != (IntPtr)0)
Marshal.FreeHGlobal(fileTime);
if (unmanagedPassword != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedPassword);
if (unmanagedAuthData != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedAuthData);
}
}
catch { throw; }
}
internal static void UpdateTrustDirection(DirectoryContext context, string sourceName, string targetName, string password, bool isForest, TrustDirection newTrustDirection)
{
PolicySafeHandle handle = null;
IntPtr buffer = (IntPtr)0;
LSA_UNICODE_STRING trustedDomainName = null;
IntPtr newBuffer = (IntPtr)0;
bool impersonated = false;
LSA_AUTH_INFORMATION AuthData = null;
IntPtr fileTime = (IntPtr)0;
IntPtr unmanagedPassword = (IntPtr)0;
IntPtr unmanagedAuthData = (IntPtr)0;
TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = null;
IntPtr target = (IntPtr)0;
string serverName = null;
serverName = Utils.GetPolicyServerName(context, isForest, false, sourceName);
impersonated = Utils.Impersonate(context);
try
{
try
{
// get the policy handle first
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(targetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// get the trusted domain information
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
// get the managed structre representation
TRUSTED_DOMAIN_FULL_INFORMATION domainInfo = new TRUSTED_DOMAIN_FULL_INFORMATION();
Marshal.PtrToStructure(buffer, domainInfo);
// validate the trust attribute first
ValidateTrustAttribute(domainInfo.Information, isForest, sourceName, targetName);
// change the attribute value properly
AuthData = new LSA_AUTH_INFORMATION();
fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime)));
UnsafeNativeMethods.GetSystemTimeAsFileTime(fileTime);
// set the time
FileTime tmp = new FileTime();
Marshal.PtrToStructure(fileTime, tmp);
AuthData.LastUpdateTime = new LARGE_INTEGER();
AuthData.LastUpdateTime.lowPart = tmp.lower;
AuthData.LastUpdateTime.highPart = tmp.higher;
AuthData.AuthType = TRUST_AUTH_TYPE_CLEAR;
unmanagedPassword = Marshal.StringToHGlobalUni(password);
AuthData.AuthInfo = unmanagedPassword;
AuthData.AuthInfoLength = password.Length * 2;
unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
if ((newTrustDirection & TrustDirection.Inbound) != 0)
{
AuthInfoEx.IncomingAuthInfos = 1;
AuthInfoEx.IncomingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.IncomingPreviousAuthenticationInformation = (IntPtr)0;
}
else
{
AuthInfoEx.IncomingAuthInfos = 0;
AuthInfoEx.IncomingAuthenticationInformation = (IntPtr)0;
AuthInfoEx.IncomingPreviousAuthenticationInformation = (IntPtr)0;
}
if ((newTrustDirection & TrustDirection.Outbound) != 0)
{
AuthInfoEx.OutgoingAuthInfos = 1;
AuthInfoEx.OutgoingAuthenticationInformation = unmanagedAuthData;
AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0;
}
else
{
AuthInfoEx.OutgoingAuthInfos = 0;
AuthInfoEx.OutgoingAuthenticationInformation = (IntPtr)0;
AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0;
}
// reconstruct the unmanaged structure to set it back
domainInfo.AuthInformation = AuthInfoEx;
// reset the trust direction
domainInfo.Information.TrustDirection = (int)newTrustDirection;
newBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TRUSTED_DOMAIN_FULL_INFORMATION)));
Marshal.StructureToPtr(domainInfo, newBuffer, false);
result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
}
return;
}
finally
{
if (impersonated)
Utils.Revert();
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
if (newBuffer != (IntPtr)0)
Marshal.FreeHGlobal(newBuffer);
if (fileTime != (IntPtr)0)
Marshal.FreeHGlobal(fileTime);
if (unmanagedPassword != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedPassword);
if (unmanagedAuthData != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedAuthData);
}
}
catch { throw; }
}
private static void ValidateTrust(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomainName, string sourceName, string targetName, bool isForest, int direction, string serverName)
{
IntPtr buffer = (IntPtr)0;
// get trust information
int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
// 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
Debug.Assert(buffer != (IntPtr)0);
try
{
TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
Marshal.PtrToStructure(buffer, domainInfo);
// validate this is the trust that the user refers to
ValidateTrustAttribute(domainInfo, isForest, sourceName, targetName);
// validate trust direction if applicable
if (direction != 0)
{
if ((direction & domainInfo.TrustDirection) == 0)
{
if (isForest)
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, sourceName, targetName, (TrustDirection)direction), typeof(ForestTrustRelationshipInformation), null);
else
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, sourceName, targetName, (TrustDirection)direction), typeof(TrustRelationshipInformation), null);
}
}
}
finally
{
if (buffer != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(buffer);
}
}
private static void ValidateTrustAttribute(TRUSTED_DOMAIN_INFORMATION_EX domainInfo, bool isForest, string sourceName, string targetName)
{
if (isForest)
{
// it should be a forest trust, make sure that TRUST_ATTRIBUTE_FOREST_TRANSITIVE bit is set
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) == 0)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
}
}
else
{
// it should not be a forest trust, make sure that TRUST_ATTRIBUTE_FOREST_TRANSITIVE bit is not set
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) != 0)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongForestTrust, sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
// we don't deal with NT4 trust also
if (domainInfo.TrustType == TRUST_TYPE_DOWNLEVEL)
throw new InvalidOperationException(SR.NT4NotSupported);
// we don't perform any operation on kerberos trust also
if (domainInfo.TrustType == TRUST_TYPE_MIT)
throw new InvalidOperationException(SR.KerberosNotSupported);
}
}
internal static string CreateTrustPassword()
{
string password = string.Empty;
byte[] buf = new byte[PASSWORD_LENGTH];
char[] cBuf = new char[PASSWORD_LENGTH];
using (RandomNumberGenerator RNG = RandomNumberGenerator.Create())
{
RNG.GetBytes(buf);
for (int iter = 0; iter < PASSWORD_LENGTH; iter++)
{
int i = (int)(buf[iter] % 87);
if (i < 10)
cBuf[iter] = (char)('0' + i);
else if (i < 36)
cBuf[iter] = (char)('A' + i - 10);
else if (i < 62)
cBuf[iter] = (char)('a' + i - 36);
else
cBuf[iter] = s_punctuations[i - 62];
}
}
password = new string(cBuf);
return password;
}
private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, string targetName, bool isForest)
{
PolicySafeHandle policyHandle = null;
IntPtr buffer = (IntPtr)0;
bool impersonated = false;
string serverName = null;
try
{
try
{
serverName = Utils.GetPolicyServerName(targetContext, isForest, false, targetName);
impersonated = Utils.Impersonate(targetContext);
try
{
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
}
catch (ActiveDirectoryOperationException)
{
if (impersonated)
{
Utils.Revert();
impersonated = false;
}
// try anonymous
Utils.ImpersonateAnonymous();
impersonated = true;
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
}
catch (UnauthorizedAccessException)
{
if (impersonated)
{
Utils.Revert();
impersonated = false;
}
// try anonymous
Utils.ImpersonateAnonymous();
impersonated = true;
policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
}
int result = UnsafeNativeMethods.LsaQueryInformationPolicy(policyHandle, policyDnsDomainInformation, out buffer);
if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
}
return buffer;
}
finally
{
if (impersonated)
Utils.Revert();
}
}
catch { throw; }
}
}
}
| |
// 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 MultiplySubtractNegatedScalarDouble()
{
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.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();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble testClass)
{
var result = Fma.MultiplySubtractNegatedScalar(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtractNegatedScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegatedScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtractNegatedScalar(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2)),
Sse2.LoadVector128((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegatedScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble();
var result = Fma.MultiplySubtractNegatedScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtractNegatedScalar(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegatedScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegatedScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2)),
Sse2.LoadVector128((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractNegatedScalar)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using OpenKh.Engine.Renders;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Xe.Drawing;
using static OpenKh.Tools.Common.Wpf.DependencyPropertyUtils;
namespace OpenKh.Tools.Common.Wpf.Controls
{
public class DrawPanel : FrameworkElement
{
private static void CopyMemory(IntPtr dest, IntPtr src, int count)
{
memcpy(dest, src, new UIntPtr(Convert.ToUInt32(count)));
}
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
private static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);
public static readonly DependencyProperty DrawingProperty =
GetDependencyProperty<DrawPanel, ISpriteDrawing>(nameof(Drawing),(o, x) => o.SetDrawing(x));
public static readonly DependencyProperty DrawCreateCommandProperty =
GetDependencyProperty<DrawPanel, ICommand>(nameof(DrawCreate), (o, x) => o.drawCreateCommand = x);
public static readonly DependencyProperty DrawDestroyCommandProperty =
GetDependencyProperty<DrawPanel, ICommand>(nameof(DrawDestroy), (o, x) => o.drawDestroyCommand = x);
public static readonly DependencyProperty DrawBeginCommandProperty =
GetDependencyProperty<DrawPanel, ICommand>(nameof(DrawBegin), (o, x) => o.drawBeginCommand = x);
public static readonly DependencyProperty DrawEndCommandProperty =
GetDependencyProperty<DrawPanel, ICommand>(nameof(DrawEnd), (o, x) => o.drawEndCommand = x);
public static readonly DependencyProperty FramesPerSecondProperty =
GetDependencyProperty<DrawPanel, double>(nameof(FramesPerSecond), 30.0f, (o, x) => o.SetFramesPerSecond(x), x => x >= 0.0f);
private ISpriteDrawing drawing;
private ICommand drawCreateCommand;
private ICommand drawDestroyCommand;
private ICommand drawBeginCommand;
private ICommand drawEndCommand;
private VisualCollection _children;
private DrawingVisual _visual;
private WriteableBitmap _writeableBitmap;
private System.Timers.Timer _timer = new System.Timers.Timer();
private System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
private System.Diagnostics.Stopwatch _stopwatchDeltaTime = new System.Diagnostics.Stopwatch();
public ISpriteDrawing Drawing
{
get => (ISpriteDrawing)GetValue(DrawingProperty);
set => SetValue(DrawingProperty, value);
}
/// <summary>
/// Called when an IDrawing has been set.
/// </summary>
public ICommand DrawCreate
{
get => (ICommand)GetValue(DrawCreateCommandProperty);
set => SetValue(DrawCreateCommandProperty, value);
}
/// <summary>
/// Called before disposing an IDrawing.
/// </summary>
public ICommand DrawDestroy
{
get => (ICommand)GetValue(DrawDestroyCommandProperty);
set => SetValue(DrawDestroyCommandProperty, value);
}
/// <summary>
/// Called when the frame needs to be rendered.
/// </summary>
public ICommand DrawBegin
{
get => (ICommand)GetValue(DrawBeginCommandProperty);
set => SetValue(DrawBeginCommandProperty, value);
}
/// <summary>
/// Called once the frame has been rendered.
/// </summary>
public ICommand DrawEnd
{
get => (ICommand)GetValue(DrawEndCommandProperty);
set => SetValue(DrawEndCommandProperty, value);
}
/// <summary>
/// Get or set how frames per second needs to be drawn.
/// A value of 0 stops the execution.
/// Values below 0 are not valid.
/// </summary>
public double FramesPerSecond
{
get => (double)GetValue(FramesPerSecondProperty);
set => SetValue(FramesPerSecondProperty, value);
}
public double LastDrawTime { get; private set; }
public double LastDrawAndPresentTime { get; private set; }
public double DeltaTime { get; private set; }
public DrawPanel()
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
_visual = new DrawingVisual();
_children = new VisualCollection(this)
{
_visual
};
_timer.Elapsed += (sender, args) =>
{
if (drawing == null)
return;
Application.Current?.Dispatcher.Invoke(new Action(() =>
{
DoRender();
}));
};
SetFramesPerSecond(FramesPerSecond);
}
else
{
_children = new VisualCollection(this);
}
}
protected override void OnRender(DrawingContext dc)
{
Present(dc, _writeableBitmap);
}
/// <summary>
/// Rendering on demand.
/// </summary>
public void DoRender()
{
DeltaTime = _stopwatchDeltaTime.Elapsed.TotalMilliseconds / 1000.0;
_stopwatchDeltaTime.Restart();
_stopwatch.Restart();
if (Drawing == null)
return;
OnDrawBegin();
LastDrawTime = _stopwatch.Elapsed.TotalMilliseconds;
Present();
LastDrawAndPresentTime = _stopwatch.Elapsed.TotalMilliseconds;
OnDrawEnd();
}
public async Task DoRenderAsync() => await DoRenderTask();
public Task DoRenderTask() =>
Task.Run(() =>
{
DoRender();
});
// Provide a required override for the VisualChildrenCount property.
protected override int VisualChildrenCount => _children.Count;
// Provide a required override for the GetVisualChild method.
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= _children.Count)
throw new ArgumentOutOfRangeException();
return _children[index];
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
var size = sizeInfo.NewSize;
ResizeRenderingEngine((int)size.Width, (int)size.Height);
base.OnRenderSizeChanged(sizeInfo);
}
}
protected virtual void OnDrawCreate() => drawCreateCommand.Invoke(drawing);
protected virtual void OnDrawDestroy() => drawDestroyCommand.Invoke(drawing);
protected virtual void OnDrawBegin() => drawBeginCommand.Invoke(drawing);
protected virtual void OnDrawEnd() => drawEndCommand.Invoke(drawing);
private void SetDrawing(ISpriteDrawing drawing)
{
if (drawing == null) // HACK
return;
if (this.drawing == drawing)
return;
if (this.drawing != null)
{
OnDrawDestroy();
this.drawing.Dispose();
}
this.drawing = drawing;
ResizeRenderingEngine((int)Math.Round(Math.Max(1, ActualWidth)), (int)Math.Round(Math.Max(1, ActualHeight)));
OnDrawCreate();
}
private void SetFramesPerSecond(double framesPerSec)
{
if (framesPerSec < 0)
throw new ArgumentException($"{nameof(FramesPerSecond)} value is set to {framesPerSec}, but it cannot be below than 0.");
if (framesPerSec > 0)
{
_timer.Enabled = true;
_timer.Interval = 1000.0 / framesPerSec;
}
else
{
_timer.Enabled = false;
}
}
private void Present()
{
Present(drawing?.DestinationTexture);
}
private void Present(ISpriteTexture surface)
{
if (surface != null && surface.Width > 0 && surface.Height > 0)
{
BlitSutface(surface);
}
InvalidateVisual(); // call Present() from OnRender
}
private void BlitSutface(ISpriteTexture surface)
{
using (var map = surface.Map())
{
if (_writeableBitmap == null ||
surface.Width != _writeableBitmap.Width ||
surface.Height != _writeableBitmap.Height ||
map.Stride / 4 != _writeableBitmap.Width)
{
_writeableBitmap = new WriteableBitmap(map.Stride / 4, surface.Height, 96.0, 96.0, PixelFormats.Bgra32, null);
}
_writeableBitmap.Lock();
CopyMemory(_writeableBitmap.BackBuffer, map.Data, map.Length);
_writeableBitmap.AddDirtyRect(new Int32Rect()
{
X = 0,
Y = 0,
Width = surface.Width,
Height = surface.Height
});
_writeableBitmap.Unlock();
}
}
private void Present(DrawingContext dc, ImageSource image)
{
if (image == null)
return;
dc.DrawImage(image, new Rect()
{
X = 0,
Y = 0,
Width = image.Width,
Height = image.Height
});
}
private void ResizeRenderingEngine(int width, int height)
{
if (drawing == null)
return;
width = Math.Min(Math.Max(1, width), 65536);
height = Math.Min(Math.Max(1, height), 65536);
drawing.DestinationTexture?.Dispose();
drawing.DestinationTexture = drawing.CreateSpriteTexture(width, height);
//drawing.SetViewport(0, width, 0, height);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.OperationalInsights
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// WorkspacesOperations operations.
/// </summary>
public partial interface IWorkspacesOperations
{
/// <summary>
/// Disables an intelligence pack for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='intelligencePackName'>
/// The name of the intelligence pack to be disabled.
/// </param>
/// <param name='customHeaders'>
/// The 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.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DisableIntelligencePackWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string intelligencePackName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Enables an intelligence pack for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='intelligencePackName'>
/// The name of the intelligence pack to be enabled.
/// </param>
/// <param name='customHeaders'>
/// The 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.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> EnableIntelligencePackWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string intelligencePackName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the intelligence packs possible and whether they are
/// enabled or disabled for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<IntelligencePack>>> ListIntelligencePacksWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the shared keys for a workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedKeys>> GetSharedKeysWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a list of usage metrics for a workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// The name of the workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<UsageMetric>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a list of management groups connected to a workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// The name of the workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<ManagementGroup>>> ListManagementGroupsWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets workspaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<Workspace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the workspaces in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<Workspace>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create or update a workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the workspace.
/// </param>
/// <param name='workspaceName'>
/// The name of the workspace.
/// </param>
/// <param name='parameters'>
/// The parameters required to create or update a workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Workspace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, Workspace parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a workspace instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the workspace.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets a workspace instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the workspace.
/// </param>
/// <param name='workspaceName'>
/// Name of the Log Analytics Workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Workspace>> GetWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get a list of workspaces which the current user has administrator
/// privileges and are not associated with an Azure Subscription. The
/// subscriptionId parameter in the Url is ignored.
/// </summary>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<LinkTarget>>> ListLinkTargetsWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the schema for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SearchGetSchemaResponse>> GetSchemaWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Submit a search for a given workspace. The response will contain an
/// id to track the search. User can use the id to poll the search
/// status and get the full search result later if the search takes
/// long time to finish.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='parameters'>
/// The parameters required to execute a search query.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SearchResultsResponse>> GetSearchResultsWithHttpMessagesAsync(string resourceGroupName, string workspaceName, SearchParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets updated search results for a given search query.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='id'>
/// The id of the search that will have results updated. You can get
/// the id from the response of the GetResults call.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SearchResultsResponse>> UpdateSearchResultsWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string id, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create or update a workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name of the workspace.
/// </param>
/// <param name='workspaceName'>
/// The name of the workspace.
/// </param>
/// <param name='parameters'>
/// The parameters required to create or update a workspace.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Workspace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, Workspace parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Submit a search for a given workspace. The response will contain an
/// id to track the search. User can use the id to poll the search
/// status and get the full search result later if the search takes
/// long time to finish.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='parameters'>
/// The parameters required to execute a search query.
/// </param>
/// <param name='customHeaders'>
/// The 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SearchResultsResponse>> BeginGetSearchResultsWithHttpMessagesAsync(string resourceGroupName, string workspaceName, SearchParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation.Internal.PropertyEditing
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Activities.Presentation;
using System.Activities.Presentation.Model;
using View = System.Activities.Presentation.View;
using System.Activities.Presentation.PropertyEditing;
using System.Runtime;
using System.Activities.Presentation.Internal.PropertyEditing.Automation;
using System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.ValueEditors;
using System.Activities.Presentation.Internal.PropertyEditing.Model;
using ModelUtilities = System.Activities.Presentation.Internal.PropertyEditing.Model.ModelUtilities;
using System.Activities.Presentation.Internal.PropertyEditing.Resources;
using System.Activities.Presentation.Internal.PropertyEditing.Selection;
using System.Activities.Presentation.Internal.PropertyEditing.State;
using System.Text;
using Microsoft.Activities.Presentation;
// <summary>
// The main control that acts as the PropertyInspector
// </summary>
[SuppressMessage(FxCop.Category.Naming, "CA1724:TypeNamesShouldNotMatchNamespaces",
Justification = "Code imported from Cider; keeping changes to a minimum as it impacts xaml files as well")]
partial class PropertyInspector :
INotifyPropertyChanged
{
private static readonly Size DesiredIconSize = new Size(40, 40);
private View.Selection _displayedSelection;
private View.Selection _lastNotifiedSelection;
private ModelItem _lastParent;
private bool _ignoreSelectionNameChanges;
private List<ModelEditingScope> _pendingTransactions = new List<ModelEditingScope>();
private PropertyValueEditorCommandHandler _defaultCommandHandler;
private IStateContainer _sessionStateContainer;
private SelectionPath _lastSelectionPath;
private bool _objectSelectionInitialized;
private bool _disposed;
private bool _isReadOnly;
private string propertyPathToSelect;
private ContextItemManager designerContextItemManager;
private DesignerPerfEventProvider designerPerfEventProvider;
// Map between currently displayed category editors and the names of the categories they belong to
private Dictionary<Type, string> _activeCategoryEditors = new Dictionary<Type, string>();
// <summary>
// Basic ctor
// </summary>
// FxCop complains this.DataContext, which is somewhat bogus
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PropertyInspector()
{
this.DataContext = this;
HookIntoCommands();
this.InitializeComponent();
//Handle the commit and cancel keys within the property inspector
ValueEditorUtils.SetHandlesCommitKeys(this, true);
_propertyToolBar.CurrentViewManagerChanged += new EventHandler(OnCurrentViewManagerChanged);
}
// <summary>
// Event fired when the IsInAlphaView changes as a result of some
// user or internal interaction. When IsInAlphaView is set by the
// external host, this event will not and should not be fired.
// </summary>
public event EventHandler RootViewModified;
public event PropertyChangedEventHandler PropertyChanged;
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "No need for a Setter")]
public ContextItemManager DesignerContextItemManager
{
set
{
this.designerContextItemManager = value;
this.designerContextItemManager.Subscribe<View.Selection>(this.OnSelectionChanged);
}
}
// <summary>
// Gets a value indicating whether the selected object Name should be read-only
// </summary>
public bool IsInfoBarNameReadOnly
{
get
{
return _displayedSelection == null || _displayedSelection.SelectionCount != 1;
}
}
// <summary>
// Gets the selection name to display
// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Propagating the error might cause VS to crash")]
[SuppressMessage("Reliability", "Reliability108", Justification = "Propagating the error might cause VS to crash")]
public string SelectionName
{
get
{
if (_displayedSelection == null || _displayedSelection.SelectionCount == 0)
{
return null;
}
if (_displayedSelection.SelectionCount == 1)
{
return _displayedSelection.PrimarySelection.Name;
}
return System.Activities.Presentation.Internal.Properties.Resources.PropertyEditing_MultipleObjectsSelected;
}
set
{
if (_disposed)
{
return;
}
if (CanSetSelectionName(_displayedSelection))
{
ModelItem selection = _displayedSelection.PrimarySelection;
Fx.Assert(selection != null, "PrimarySelection should not be null");
try
{
_ignoreSelectionNameChanges = true;
using (ModelEditingScope change = selection.BeginEdit(System.Activities.Presentation.Internal.Properties.Resources.PropertyEditing_NameChangeUndoText))
{
if (string.IsNullOrEmpty(value))
{
// Null with cause ClearValue to be called in the base implementation on the NameProperty
selection.Name = null;
}
else
{
selection.Name = value;
}
if (change != null)
change.Complete();
}
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
ErrorReporting.ShowErrorMessage(e.Message);
}
finally
{
_ignoreSelectionNameChanges = false;
}
OnPropertyChanged("SelectionName");
}
else
{
Debug.Fail("Shouldn't be able to set a selection name if no or more than one object is selected.");
}
}
}
// <summary>
// Gets the icon for the selection
// </summary>
public object SelectionIcon
{
get
{
if (_displayedSelection == null || _displayedSelection.SelectionCount == 0)
{
return null;
}
if (_displayedSelection.SelectionCount == 1 || AreHomogenous(_displayedSelection.SelectedObjects))
{
if (_displayedSelection.SelectionCount == 1)
{
Visual selectedVisual = _displayedSelection.PrimarySelection.View as Visual;
// We dont want to show tooltips for elements that derive from "Window" class.
// But we do want to show it for DesignTimeWindow, hence we check the View, so that modelItem returns the correct value
// for designtimewindow.
if (selectedVisual != null && !typeof(Window).IsAssignableFrom(_displayedSelection.PrimarySelection.View.GetType()))
{
// Show a small preview of the selected single object
VisualBrush controlBrush = new VisualBrush(selectedVisual);
controlBrush.Stretch = Stretch.Uniform;
Rectangle rect = new Rectangle();
rect.Width = DesiredIconSize.Width;
rect.Height = DesiredIconSize.Height;
rect.DataContext = string.Empty;
// If the control's parent is RTLed, then the VisualBrush "mirrors" the text.
// so apply "mirror" transform to "negate" the mirroring.
FrameworkElement curElement = selectedVisual as FrameworkElement;
FrameworkElement parentElement = curElement.Parent as FrameworkElement;
if (parentElement != null && parentElement.FlowDirection == FlowDirection.RightToLeft)
{
ScaleTransform mirrorTransform = new ScaleTransform(-1, 1);
mirrorTransform.CenterX = rect.Width / 2;
mirrorTransform.CenterY = rect.Height / 2;
controlBrush.Transform = mirrorTransform;
}
rect.Fill = controlBrush;
return rect;
}
else
{
// The selected object is not a visual, so show a non-designable object icon
return GetEmbeddedImage("NonDesignableSelection.png");
}
}
// Show mutliple-selection of the same type icon
return GetEmbeddedImage("MultiSelectionSameType.png");
}
// Show multiple-selection of different types icon
return GetEmbeddedImage("MultiSelectionDifferentType.png");
}
}
// <summary>
// Gets the Type name for the current selection
// </summary>
public string SelectionTypeName
{
get
{
if (_displayedSelection == null || _displayedSelection.SelectionCount == 0)
{
return null;
}
if (_displayedSelection.SelectionCount == 1 || AreHomogenous(_displayedSelection.SelectedObjects))
{
return GetStringRepresentation(_displayedSelection.PrimarySelection.ItemType);
}
return System.Activities.Presentation.Internal.Properties.Resources.PropertyEditing_MultipleTypesSelected;
}
}
static string GetStringRepresentation(Type type)
{
return TypeNameHelper.GetDisplayName(type, true);
}
// Property View
// <summary>
// Gets the state that should be persisted while the host is
// running, but discarded when the host shuts down.
// </summary>
public object SessionState
{
get
{
// Don't instantiate the SessionStateContainer until
// CategoryList has been instantiated. Otherwise, we would
// get an invalid container.
if (_categoryList == null)
{
return null;
}
return SessionStateContainer.RetrieveState();
}
set
{
// Don't instantiate the SessionStateContainer until
// CategoryList has been instantiated. Otherwise, we would
// get an invalid container.
if (_categoryList == null || value == null)
{
return;
}
SessionStateContainer.RestoreState(value);
_objectSelectionInitialized = false;
}
}
public bool IsReadOnly
{
get { return this._isReadOnly; }
internal set
{
this._isReadOnly = value;
this._categoryList.Opacity = this._isReadOnly ? 0.8 : 1.0;
this._categoryList.ToolTip = this._isReadOnly ? this.FindResource("editingDisabledHint") : null;
this.OnPropertyChanged("IsReadOnly");
}
}
// <summary>
// Gets or sets a flag indicating whether the root PropertyInspector
// control is in alpha-view. We isolate this state from any other
// to make VS integration easier.
// </summary>
public bool IsInAlphaView
{
get { return _propertyToolBar.IsAlphaViewSelected; }
set { _propertyToolBar.IsAlphaViewSelected = value; }
}
private void SelectPropertyByPathOnIdle()
{
SelectionPath selectionPath =
new SelectionPath(PropertySelectionPathInterpreter.PropertyPathTypeId, propertyPathToSelect);
bool pendingGeneration;
bool result = this._categoryList.SetSelectionPath(selectionPath, out pendingGeneration);
if (!result && pendingGeneration)
{
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new MethodInvoker(SelectPropertyByPathOnIdle));
}
}
internal void SelectPropertyByPath(string path)
{
this.propertyPathToSelect = path;
// must do it in application idle time, otherwise the propertygrid is not popugrated yet.
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new MethodInvoker(SelectPropertyByPathOnIdle));
}
internal TextBlock SelectionTypeLabel
{ get { return _typeLabel; } }
//internal TextBlock SelectionNameLabel
//{ get { return _nameLabel; } }
//internal StringEditor SelectionNameEditor
//{ get { return _nameEditor; } }
internal PropertyToolBar PropertyToolBar
{ get { return _propertyToolBar; } }
internal TextBlock NoSearchResultsLabel
{ get { return _noSearchResultsLabel; } }
internal TextBlock UninitializedLabel
{ get { return _uninitializedLabel; } }
internal CategoryList CategoryList
{ get { return _categoryList; } }
internal EditingContext EditingContext { get; set; }
private DesignerPerfEventProvider DesignerPerfEventProvider
{
get
{
if (this.designerPerfEventProvider == null && this.EditingContext != null)
{
this.designerPerfEventProvider = this.EditingContext.Services.GetService<DesignerPerfEventProvider>();
}
return this.designerPerfEventProvider;
}
}
private SelectionPath LastSelectionPath
{
get { return _lastSelectionPath; }
set { _lastSelectionPath = value; }
}
private IStateContainer SessionStateContainer
{
get
{
if (_categoryList == null)
{
return null;
}
if (_sessionStateContainer == null)
{
_sessionStateContainer = new AggregateStateContainer(
PropertyStateContainer.Instance,
_categoryList,
new SelectionPathStateContainer(this),
PropertyActiveEditModeStateContainer.Instance,
PropertyViewManagerStateContainer.Instance);
}
return _sessionStateContainer;
}
}
// IPropertyInspectorState
internal void Dispose()
{
_disposed = true;
DisassociateAllProperties();
UpdateSelectionPropertyChangedEventHooks(_displayedSelection, null);
_displayedSelection = null;
_defaultCommandHandler.Dispose();
_defaultCommandHandler = null;
}
private void HookIntoCommands()
{
// Use a helper classes to handle all the standard PI commands
_defaultCommandHandler = new PropertyValueEditorCommandHandler(this);
}
// <summary>
// Marks all shown properties as disassociated which disables all modifications
// done to them through the PI model objects.
// </summary>
private void DisassociateAllProperties()
{
if (_categoryList != null && _categoryList.IsLoaded)
{
foreach (ModelCategoryEntry category in _categoryList)
{
category.MarkAllPropertiesDisassociated();
}
}
}
// Properties
private void OnCurrentViewManagerChanged(object sender, EventArgs e)
{
this.RefreshPropertyList(false);
// Isolate the current view of the root PropertyInspector into
// its own separate flag and event to appease the VS ----s
//
if (this.RootViewModified != null)
{
RootViewModified(null, EventArgs.Empty);
}
}
private void RefreshPropertyList(bool attachedOnly)
{
UpdateCategories(_lastNotifiedSelection, attachedOnly);
UpdateCategoryEditors(_lastNotifiedSelection);
//
// The first time SelectionChanges, there is nothing selected, so don't store the
// current property selected. It would just overwrite the selection path that we
// received from SelectionPathStateContainer, which is not what we want.
//
if (_objectSelectionInitialized)
{
LastSelectionPath = _categoryList.SelectionPath;
}
_objectSelectionInitialized = true;
//
// Call UpdateSelectedProperty() _after_ the UI renders. We need to set PropertySelection.IsSelected
// property on a templated visual objects (CategoryContainer, PropertyContainer) and those may not exist yet.
//
Dispatcher.BeginInvoke(DispatcherPriority.Render, new UpdateSelectedPropertyInvoker(UpdateSelectedProperty), _lastNotifiedSelection);
}
// Selection Logic
// SelectionPathStateContainer
// <summary>
// Called externally whenever selection changes
// </summary>
// <param name="selection">New selection</param>
public void OnSelectionChanged(View.Selection selection)
{
_lastNotifiedSelection = selection;
RefreshSelection();
}
// <summary>
// Called when visibility of the PropertyBrowserPane changes and the
// PropertyInspector may be showing a stale selection. This method is identical
// to OnSelectionChanged() but with no new selection instance introduced.
// </summary>
public void RefreshSelection()
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, new MethodInvoker(OnSelectionChangedIdle));
}
// Updates PI when the application becomes Idle (perf optimization)
private void OnSelectionChangedIdle()
{
if (DesignerPerfEventProvider != null)
{
DesignerPerfEventProvider.PropertyInspectorUpdatePropertyListStart();
}
if (AreSelectionsEquivalent(_lastNotifiedSelection, _displayedSelection))
{
return;
}
if (!VisualTreeUtils.IsVisible(this))
{
return;
}
// Change the SelectedControlFlowDirectionRTL resource property
// This will allow the 3rd party editors to look at this property
// and change to RTL for controls that support RTL.
// We set the resource to the primary selections RTL property.
FlowDirection commmonFD = this.FlowDirection;
if (_lastNotifiedSelection != null && _lastNotifiedSelection.PrimarySelection != null)
{
FrameworkElement selectedElement = _lastNotifiedSelection.PrimarySelection.View as FrameworkElement;
if (selectedElement != null)
{
commmonFD = selectedElement.FlowDirection;
}
// In case of mulitislection,
// if the FlowDirection is different then always set it to LTR.
// else set it to common FD.
if (_lastNotifiedSelection.SelectionCount > 1)
{
foreach (ModelItem item in _lastNotifiedSelection.SelectedObjects)
{
FrameworkElement curElm = item.View as FrameworkElement;
if (curElm != null && curElm.FlowDirection != commmonFD)
{
//reset to LTR (since the FD's are different within multiselect)
commmonFD = FlowDirection.LeftToRight;
break;
}
}
}
}
PropertyInspectorResources.GetResources()["SelectedControlFlowDirectionRTL"] = commmonFD;
RefreshPropertyList(false);
UpdateSelectionPropertyChangedEventHooks(_displayedSelection, _lastNotifiedSelection);
_displayedSelection = _lastNotifiedSelection;
_lastParent = GetCommonParent(_lastNotifiedSelection);
// Handle dangling transactions
_defaultCommandHandler.CommitOpenTransactions();
OnPropertyChanged("IsInfoBarNameReadOnly");
OnPropertyChanged("SelectionName");
OnPropertyChanged("SelectionIcon");
OnPropertyChanged("SelectionTypeName");
}
// Removes / adds a PropertyChanged listener from / to the previous / current selection
private void UpdateSelectionPropertyChangedEventHooks(View.Selection previousSelection, View.Selection currentSelection)
{
if (previousSelection != null && previousSelection.PrimarySelection != null)
{
previousSelection.PrimarySelection.PropertyChanged -= OnSelectedItemPropertyChanged;
}
if (currentSelection != null && currentSelection.PrimarySelection != null)
{
currentSelection.PrimarySelection.PropertyChanged += OnSelectedItemPropertyChanged;
}
}
private void OnSelectedItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_ignoreSelectionNameChanges)
{
return;
}
// PS 40699 - Name is not a special property for WF
//if ("Name".Equals(e.PropertyName))
//{
// OnSelectedItemNameChanged();
//}
if ("Parent".Equals(e.PropertyName))
{
OnParentChanged();
}
}
// Called when the name changes
private void OnSelectedItemNameChanged()
{
OnPropertyChanged("SelectionName");
}
// Called when the parent of the current selection changes
private void OnParentChanged()
{
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new MethodInvoker(OnParentChangedIdle));
}
private void OnParentChangedIdle()
{
if (_displayedSelection == null || _displayedSelection.SelectionCount < 1)
{
return;
}
ModelItem newParent = GetCommonParent(_displayedSelection);
if (_lastParent != newParent)
{
RefreshPropertyList(true);
_lastParent = newParent;
}
}
// Looks for common parent ModelItem among all the items in the selection
private static ModelItem GetCommonParent(View.Selection selection)
{
if (selection == null || selection.SelectionCount < 1)
{
return null;
}
ModelItem parent = null;
foreach (ModelItem item in selection.SelectedObjects)
{
if (parent == null)
{
parent = item.Parent;
}
else if (parent != item.Parent)
{
return null;
}
}
return parent;
}
// The user can only specify the name for the selected objects iff exactly one
// object is selected.
private static bool CanSetSelectionName(View.Selection selection)
{
return selection != null && selection.SelectionCount == 1;
}
private static bool AreSelectionsEquivalent(View.Selection a, View.Selection b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
if (a.SelectionCount != b.SelectionCount)
{
return false;
}
// POSSIBLE OPTIMIZATION: be smarter about same selection in a different order
IEnumerator<ModelItem> ea = a.SelectedObjects.GetEnumerator();
IEnumerator<ModelItem> eb = b.SelectedObjects.GetEnumerator();
while (ea.MoveNext() && eb.MoveNext())
{
if (!object.Equals(ea.Current, eb.Current))
{
return false;
}
}
return true;
}
// This is the work-horse that refreshes the list of properties and categories within a PropertyInspector
// window, including refreshing of CategoryEditors, based on the specified selection
private void UpdateCategories(View.Selection selection, bool attachedOnly)
{
// Optimization stolen from Sparkle:
// re-rendering the categories is the number one perf issue. Clearing
// the databound collection results in massive Avalon code execution, and
// then re-adding everything causes another huge shuffle. What is more,
// even when changing the selection between different objects, most properties
// do not change. Therefore we are going to take the new list of properties
// and we are going to merge them into the existing stuff, using an
// approach I call Mark, Match, and Cull.
//
// First we mark all the properties in the current collection. Those which
// are still marked at the end will be culled out
foreach (ModelCategoryEntry category in _categoryList)
{
if (attachedOnly)
{
category.MarkAttachedPropertiesDisassociated();
}
else
{
category.MarkAllPropertiesDisassociated();
}
}
// Second we try to match each property in the list of properties for the newly selected objects
// against something that we already have. If we have a match, then we reset the existing
// ModelPropertyEntry and clear the mark
//
foreach (IEnumerable<ModelProperty> propertySet in
ModelPropertyMerger.GetMergedProperties(
selection == null ? null : selection.SelectedObjects,
selection == null ? 0 : selection.SelectionCount))
{
string propertyName = GetPropertyName(propertySet);
// Specifically filter out the Name property
// PS 40699 - Name is not a special property for WF
//if ("Name".Equals(propertyName))
//{
// continue;
//}
if (attachedOnly && propertyName.IndexOf('.') < 0)
{
continue;
}
ModelPropertyEntry wrappedProperty = _propertyToolBar.CurrentViewManager.AddProperty(propertySet, propertyName, _categoryList);
// Make sure no valid properties get culled out
wrappedProperty.Disassociated = false;
}
// Third, we walk the properties and categories, and we cull out all of the
// marked properties. Empty categories are removed.
//
for (int i = _categoryList.Count - 1; i >= 0; i--)
{
ModelCategoryEntry category = (ModelCategoryEntry)_categoryList[i];
category.CullDisassociatedProperties();
if (category.IsEmpty)
{
_categoryList.RemoveAt(i);
}
}
_categoryList.RefreshFilter();
}
// Helper method that adjusts the visible set of CategoryEditors based on the specified selection
private void UpdateCategoryEditors(View.Selection selection)
{
// Figure out which category editors to show
Dictionary<Type, object> newCategoryEditorTypes = _propertyToolBar.CurrentViewManager.GetCategoryEditors(
FindCommonType(selection == null ? null : selection.SelectedObjects),
_categoryList);
// Figure out which CategoryEditors are no longer needed and remove them
List<Type> editorTypesToRemove = null;
foreach (KeyValuePair<Type, string> item in _activeCategoryEditors)
{
if (!newCategoryEditorTypes.ContainsKey(item.Key) || !IsCategoryShown(item.Key))
{
// New selection does not include this existing category editor
// or the category that contains this editor
// so remove the editor.
if (editorTypesToRemove == null)
{
editorTypesToRemove = new List<Type>();
}
editorTypesToRemove.Add(item.Key);
}
else
{
// This category editor already exists, so don't re-add it
newCategoryEditorTypes.Remove(item.Key);
}
}
if (editorTypesToRemove != null)
{
foreach (Type editorTypeToRemove in editorTypesToRemove)
{
ModelCategoryEntry affectedCategory = _categoryList.FindCategory(_activeCategoryEditors[editorTypeToRemove]) as ModelCategoryEntry;
if (affectedCategory != null)
{
affectedCategory.RemoveCategoryEditor(editorTypeToRemove);
}
_activeCategoryEditors.Remove(editorTypeToRemove);
}
}
// Figure out which CategoryEditors are now required and add them
foreach (Type editorTypeToAdd in newCategoryEditorTypes.Keys)
{
CategoryEditor editor = (CategoryEditor)ExtensibilityAccessor.SafeCreateInstance(editorTypeToAdd);
if (editor == null)
{
continue;
}
ModelCategoryEntry affectedCategory = _categoryList.FindCategory(editor.TargetCategory) as ModelCategoryEntry;
if (affectedCategory == null)
{
continue;
}
affectedCategory.AddCategoryEditor(editor);
_activeCategoryEditors[editorTypeToAdd] = editor.TargetCategory;
}
}
// Check if the category is shown for the current category editor type
private bool IsCategoryShown(Type categoryEditorType)
{
bool ret = true;
CategoryEditor editorToRemove = (CategoryEditor)ExtensibilityAccessor.SafeCreateInstance(categoryEditorType);
if (editorToRemove != null)
{
ModelCategoryEntry affectedCategory = _categoryList.FindCategory(editorToRemove.TargetCategory) as ModelCategoryEntry;
if (affectedCategory == null)
{
ret = false;
}
}
else
{
ret = false;
}
return ret;
}
// Tries to figure out what property to select and selects is
private void UpdateSelectedProperty(View.Selection selection)
{
// If we are not loaded, skip any and all selection magic
if (!this.IsLoaded)
{
return;
}
if (selection != null)
{
// See what the view would like us to select if we run out of things
// we can think of selecting
//
SelectionPath fallbackSelection = null;
if (_propertyToolBar.CurrentViewManager != null)
{
fallbackSelection = _propertyToolBar.CurrentViewManager.GetDefaultSelectionPath(_categoryList);
}
// Select the first thing we request that exists, using the following
// precedence order:
//
// * LastSelectionPath
// * DefaultProperty
// * Whatever the view wants to show (first category, first property, ...)
//
_categoryList.UpdateSelectedProperty(
this.LastSelectionPath,
ModelPropertyMerger.GetMergedDefaultProperty(selection.SelectedObjects),
fallbackSelection);
}
if (DesignerPerfEventProvider != null)
{
DesignerPerfEventProvider.PropertyInspectorUpdatePropertyListEnd();
}
}
private static Type FindCommonType(IEnumerable<ModelItem> modelItems)
{
Type commonType = null;
if (modelItems != null)
{
foreach (ModelItem selectedItem in modelItems)
{
if (commonType == null)
{
commonType = selectedItem.ItemType;
}
else
{
commonType = ModelUtilities.GetCommonAncestor(commonType, selectedItem.ItemType);
}
}
}
return commonType;
}
private static bool AreHomogenous(IEnumerable<ModelItem> items)
{
Fx.Assert(items != null, "items parameter is null");
Type type = null;
foreach (ModelItem item in items)
{
if (type == null)
{
type = item.ItemType;
}
else if (type != item.ItemType)
{
return false;
}
}
return true;
}
// Static Helpers
private static string GetPropertyName(IEnumerable<ModelProperty> propertySet)
{
if (propertySet == null)
{
return null;
}
foreach (ModelProperty property in propertySet)
{
return property.Name;
}
return null;
}
private static Image GetEmbeddedImage(string imageName)
{
Image image = new Image();
image.Source = new BitmapImage(new Uri(
string.Concat(
"/System.Activities.Presentation;component/System/Activities/Presentation/Base/Core/Internal/PropertyEditing/Resources/",
imageName),
UriKind.RelativeOrAbsolute));
return image;
}
// AutomationPeer Stuff
protected override AutomationPeer OnCreateAutomationPeer()
{
return new PropertyInspectorAutomationPeer(this);
}
// Cross-domain State Storage
// <summary>
// Clears the FilterString
// </summary>
public void ClearFilterString()
{
_categoryList.FilterString = null;
}
// INotifyPropertyChanged Members
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private delegate void MethodInvoker();
private delegate void UpdateSelectedPropertyInvoker(View.Selection selection);
// Container for property-selection state represented by SelectionPath.
// Since we receive a stored SelectionPath on the reload of this control,
// at which point the visuals themselves have not been rendered yet, we
// store the supplied SelectionPath instance and use it to select the
// correct property only after the UI has been rendered.
//
private class SelectionPathStateContainer : IStateContainer
{
private PropertyInspector _parent;
public SelectionPathStateContainer(PropertyInspector parent)
{
if (parent == null)
{
throw FxTrace.Exception.ArgumentNull("parent");
}
_parent = parent;
}
//
// Pulls the SelectionPath from the CategoryList, but only if it was Sticky,
// meaning we should preserve it
//
public object RetrieveState()
{
if (_parent.CategoryList != null)
{
SelectionPath path = _parent._objectSelectionInitialized ? _parent.CategoryList.SelectionPath : _parent.LastSelectionPath;
return path == null ? null : path.State;
}
return null;
}
//
// Pulls the SelectionPath from the CategoryList, but only if it was Sticky,
// meaning we should preserve it
//
public void RestoreState(object state)
{
if (state != null)
{
SelectionPath restoredPath = SelectionPath.FromState(state);
_parent.LastSelectionPath = restoredPath;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
using SteamTrade.TradeWebAPI;
namespace SteamTrade
{
/// <summary>
/// Class which represents a trade.
/// Note that the logic that Steam uses can be seen from their web-client source-code: http://steamcommunity-a.akamaihd.net/public/javascript/economy_trade.js
/// </summary>
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
public enum TradeStatusType
{
OnGoing = 0,
CompletedSuccessfully = 1,
UnknownStatus = 2,
TradeCancelled = 3,
SessionExpired = 4,
TradeFailed = 5
}
public string GetTradeStatusErrorString(TradeStatusType tradeStatusType)
{
switch(tradeStatusType)
{
case TradeStatusType.OnGoing:
return "is still going on";
case TradeStatusType.CompletedSuccessfully:
return "completed successfully";
case TradeStatusType.UnknownStatus:
return "CLOSED FOR UNKNOWN REASONS - WHAT CAUSES THIS STATUS!?";
case TradeStatusType.TradeCancelled:
return "was cancelled " + (tradeCancelledByBot ? "by bot" : "by other user");
case TradeStatusType.SessionExpired:
return String.Format("expired because {0} timed out", (otherUserTimingOut ? "other user" : "bot"));
case TradeStatusType.TradeFailed:
return "failed unexpectedly";
default:
return "STATUS IS UNKNOWN - THIS SHOULD NEVER HAPPEN!";
}
}
#endregion
private const int WEB_REQUEST_MAX_RETRIES = 3;
private const int WEB_REQUEST_TIME_BETWEEN_RETRIES_MS = 600;
// list to store all trade events already processed
private readonly List<TradeEvent> eventList;
// current bot's sid
private readonly SteamID mySteamId;
private readonly Dictionary<int, TradeUserAssets> myOfferedItemsLocalCopy;
private readonly TradeSession session;
private readonly Task<Inventory> myInventoryTask;
private readonly Task<Inventory> otherInventoryTask;
private List<TradeUserAssets> myOfferedItems;
private List<TradeUserAssets> otherOfferedItems;
private bool otherUserTimingOut;
private bool tradeCancelledByBot;
private int numUnknownStatusUpdates;
internal Trade(SteamID me, SteamID other, string sessionId, string token, Task<Inventory> myInventoryTask, Task<Inventory> otherInventoryTask)
{
TradeStarted = false;
OtherIsReady = false;
MeIsReady = false;
mySteamId = me;
OtherSID = other;
session = new TradeSession(sessionId, token, other);
this.eventList = new List<TradeEvent>();
myOfferedItemsLocalCopy = new Dictionary<int, TradeUserAssets>();
otherOfferedItems = new List<TradeUserAssets>();
myOfferedItems = new List<TradeUserAssets>();
this.otherInventoryTask = otherInventoryTask;
this.myInventoryTask = myInventoryTask;
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets the private inventory of the other user.
/// </summary>
public ForeignInventory OtherPrivateInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public IEnumerable<TradeUserAssets> OtherOfferedItems
{
get { return otherOfferedItems; }
}
/// <summary>
/// Gets the items the bot has offered, by itemid.
/// </summary>
/// <value>
/// The bot offered items.
/// </value>
public IEnumerable<TradeUserAssets> MyOfferedItems
{
get { return myOfferedItems; }
}
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady { get; private set; }
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
/// <summary>
/// Gets a value indicating whether the trade completed normally. This
/// is independent of other flags.
/// </summary>
public bool HasTradeCompletedOk { get; private set; }
/// <summary>
/// Gets a value indicating if the remote trading partner accepted the trade.
/// </summary>
public bool OtherUserAccepted { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler();
public delegate void CompleteHandler();
public delegate void ErrorHandler(string errorMessage);
public delegate void StatusErrorHandler(TradeStatusType statusType);
public delegate void TimeoutHandler();
public delegate void SuccessfulInit();
public delegate void UserAddItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem);
public delegate void MessageHandler(string msg);
public delegate void UserSetReadyStateHandler(bool ready);
public delegate void UserAcceptHandler();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// Called when the trade completes successfully.
/// </summary>
public event CompleteHandler OnSuccess;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// Specifically for trade_status errors.
/// </summary>
public event StatusErrorHandler OnStatusError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade()
{
tradeCancelledByBot = true;
return RetryWebRequest(session.CancelTradeWebCmd);
}
/// <summary>
/// Adds a specified TF2 item by its itemid.
/// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload
/// </summary>
/// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns>
public bool AddItem(ulong itemid)
{
if(MyInventory.GetItem(itemid) == null)
{
return false;
}
else
{
return AddItem(new TradeUserAssets(440, 2, itemid));
}
}
public bool AddItem(ulong itemid, int appid, long contextid)
{
return AddItem(new TradeUserAssets(appid, contextid, itemid));
}
public bool AddItem(TradeUserAssets item)
{
var slot = NextTradeSlot();
bool success = RetryWebRequest(() => session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid));
if(success)
myOfferedItemsLocalCopy[slot] = item;
return success;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex(int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
return AddItem(item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex(int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint added = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable)
{
bool success = AddItem(item.Id);
if(success)
added++;
if(numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
public bool RemoveItem(TradeUserAssets item)
{
return RemoveItem(item.assetid, item.appid, item.contextid);
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem(ulong itemid, int appid = 440, long contextid = 2)
{
int? slot = GetItemSlot(itemid);
if(!slot.HasValue)
return false;
bool success = RetryWebRequest(() => session.RemoveItemWebCmd(itemid, slot.Value, appid, contextid));
if(success)
myOfferedItemsLocalCopy.Remove(slot.Value);
return success;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex(int defindex)
{
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values)
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null && item.Defindex == defindex)
{
return RemoveItem(item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex(int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex);
uint removed = 0;
foreach(Inventory.Item item in items)
{
if(item != null && myOfferedItemsLocalCopy.Values.Any(o => o.assetid == item.Id))
{
bool success = RemoveItem(item.Id);
if(success)
removed++;
if(numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Removes all offered items from the trade.
/// </summary>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItems()
{
uint numRemoved = 0;
foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values.ToList())
{
Inventory.Item item = MyInventory.GetItem(asset.assetid);
if(item != null)
{
bool wasRemoved = RemoveItem(item.Id);
if(wasRemoved)
numRemoved++;
}
}
return numRemoved;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage(string msg)
{
return RetryWebRequest(() => session.SendMessageWebCmd(msg));
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady(bool ready)
{
//If the bot calls SetReady(false) and the call fails, we still want meIsReady to be
//set to false. Otherwise, if the call to SetReady() was a result of a callback
//from Trade.Poll() inside of the OnTradeAccept() handler, the OnTradeAccept()
//handler might think the bot is ready, when really it's not!
if(!ready)
MeIsReady = false;
ValidateLocalTradeItems();
return RetryWebRequest(() => session.SetReadyWebCmd(ready));
}
/// <summary>
/// Accepts the trade from the user. Returns whether the acceptance went through or not
/// </summary>
public bool AcceptTrade()
{
if(!MeIsReady)
return false;
ValidateLocalTradeItems();
return RetryWebRequest(session.AcceptTradeWebCmd);
}
/// <summary>
/// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least
/// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts)
/// </summary>
/// <returns>The result of the function if it succeeded, or default(T) (null/false/0) otherwise</returns>
private T RetryWebRequest<T>(Func<T> webEvent)
{
for(int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++)
{
//Don't make any more requests if the trade has ended!
if(HasTradeCompletedOk || OtherUserCancelled)
return default(T);
try
{
T result = webEvent();
// if the web request returned some error.
if(!EqualityComparer<T>.Default.Equals(result, default(T)))
return result;
}
catch(Exception ex)
{
// TODO: log to SteamBot.Log but... see issue #394
// realistically we should not throw anymore
Console.WriteLine(ex);
}
if(i != WEB_REQUEST_MAX_RETRIES)
{
//This will cause the bot to stop responding while we wait between web requests. ...Is this really what we want?
Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS);
}
}
return default(T);
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll()
{
if (!TradeStarted)
{
TradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if (OnAfterInit != null)
OnAfterInit();
}
TradeStatus status = RetryWebRequest(session.GetStatus);
if (status == null)
return false;
TradeStatusType tradeStatusType = (TradeStatusType) status.trade_status;
switch (tradeStatusType)
{
// Nothing happened. i.e. trade hasn't closed yet.
case TradeStatusType.OnGoing:
return HandleTradeOngoing(status);
// Successful trade
case TradeStatusType.CompletedSuccessfully:
HasTradeCompletedOk = true;
return false;
//On a status of 2, the Steam web code attempts the request two more times
//This is our attempt to do the same. I (BlueRaja) personally don't think this will work, but we shall see...
case TradeStatusType.UnknownStatus:
numUnknownStatusUpdates++;
if(numUnknownStatusUpdates < 3)
{
return false;
}
break;
}
FireOnStatusErrorEvent(tradeStatusType);
OtherUserCancelled = true;
return false;
}
private bool HandleTradeOngoing(TradeStatus status)
{
if (status.newversion)
{
HandleTradeVersionChange(status);
return true;
}
else if (status.version > session.Version)
{
// oh crap! we missed a version update abort so we don't get
// scammed. if we could get what steam thinks what's in the
// trade then this wouldn't be an issue. but we can only get
// that when we see newversion == true
throw new TradeException("The trade version does not match. Aborting.");
}
// Update Local Variables
if (status.them != null)
{
OtherIsReady = status.them.ready == 1;
MeIsReady = status.me.ready == 1;
OtherUserAccepted = status.them.confirmed == 1;
//Similar to the logic Steam uses to determine whether or not to show the "waiting" spinner in the trade window
otherUserTimingOut = (status.them.connection_pending || status.them.sec_since_touch >= 5);
}
bool otherUserDidSomething = false;
var events = status.GetAllEvents();
foreach(var tradeEvent in events.OrderBy(o => o.timestamp))
{
if (eventList.Contains(tradeEvent))
continue;
//add event to processed list, as we are taking care of this event now
eventList.Add(tradeEvent);
bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString();
// dont process if this is something the bot did
if (isBot)
continue;
otherUserDidSomething = true;
switch ((TradeEventType)tradeEvent.action)
{
case TradeEventType.ItemAdded:
TradeUserAssets newAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid);
if(!otherOfferedItems.Contains(newAsset))
{
otherOfferedItems.Add(newAsset);
FireOnUserAddItem(newAsset);
}
break;
case TradeEventType.ItemRemoved:
TradeUserAssets oldAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid);
if(otherOfferedItems.Contains(oldAsset))
{
otherOfferedItems.Remove(oldAsset);
FireOnUserRemoveItem(oldAsset);
}
break;
case TradeEventType.UserSetReady:
OnUserSetReady(true);
break;
case TradeEventType.UserSetUnReady:
OnUserSetReady(false);
break;
case TradeEventType.UserAccept:
OnUserAccept();
break;
case TradeEventType.UserChat:
OnMessage(tradeEvent.text);
break;
default:
throw new TradeException("Unknown event type: " + tradeEvent.action);
}
}
if (status.logpos != 0)
{
session.LogPos = status.logpos;
}
return otherUserDidSomething;
}
private void HandleTradeVersionChange(TradeStatus status)
{
//Figure out which items have been added/removed
IEnumerable<TradeUserAssets> otherOfferedItemsUpdated = status.them.GetAssets();
IEnumerable<TradeUserAssets> addedItems = otherOfferedItemsUpdated.Except(otherOfferedItems).ToList();
IEnumerable<TradeUserAssets> removedItems = otherOfferedItems.Except(otherOfferedItemsUpdated).ToList();
//Copy over the new items and update the version number
otherOfferedItems = status.them.GetAssets().ToList();
myOfferedItems = status.me.GetAssets().ToList();
session.Version = status.version;
//Fire the OnUserRemoveItem events
foreach (TradeUserAssets asset in removedItems)
{
FireOnUserRemoveItem(asset);
}
//Fire the OnUserAddItem events
foreach (TradeUserAssets asset in addedItems)
{
FireOnUserAddItem(asset);
}
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
private void FireOnUserAddItem(TradeUserAssets asset)
{
if(MeIsReady)
{
SetReady(false);
}
if(OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, item);
}
else
{
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
//Console.WriteLine("User added a non TF2 item to the trade.");
OnUserAddItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
Console.WriteLine("User added an unknown item to the trade.");
}
OnUserAddItem(schemaItem, null);
// todo: figure out what to send in with Inventory item.....
}
}
private Schema.Item GetItemFromPrivateBp(TradeUserAssets asset)
{
if(OtherPrivateInventory == null)
{
// get the foreign inventory
var f = session.GetForiegnInventory(OtherSID, asset.contextid, asset.appid);
OtherPrivateInventory = new ForeignInventory(f);
}
ushort defindex = OtherPrivateInventory.GetDefIndex(asset.assetid);
Schema.Item schemaItem = CurrentSchema.GetItem(defindex);
return schemaItem;
}
/// <summary>
/// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine.
/// Passes in null items if something went wrong.
/// </summary>
/// <returns></returns>
private void FireOnUserRemoveItem(TradeUserAssets asset)
{
if(MeIsReady)
{
SetReady(false);
}
if(OtherInventory != null)
{
Inventory.Item item = OtherInventory.GetItem(asset.assetid);
if(item != null)
{
Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, item);
}
else
{
// TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema
item = new Inventory.Item
{
Id = asset.assetid,
AppId = asset.appid,
ContextId = asset.contextid
};
OnUserRemoveItem(null, item);
}
}
else
{
var schemaItem = GetItemFromPrivateBp(asset);
if(schemaItem == null)
{
// TODO: Add log (counldn't find item in CurrentSchema)
}
OnUserRemoveItem(schemaItem, null);
}
}
internal void FireOnSuccessEvent()
{
var onSuccessEvent = OnSuccess;
if(onSuccessEvent != null)
onSuccessEvent();
}
internal void FireOnCloseEvent()
{
var onCloseEvent = OnClose;
if(onCloseEvent != null)
onCloseEvent();
}
internal void FireOnErrorEvent(string message)
{
var onErrorEvent = OnError;
if(onErrorEvent != null)
onErrorEvent(message);
}
internal void FireOnStatusErrorEvent(TradeStatusType statusType)
{
var onStatusErrorEvent = OnStatusError;
if (onStatusErrorEvent != null)
onStatusErrorEvent(statusType);
}
private int NextTradeSlot()
{
int slot = 0;
while(myOfferedItemsLocalCopy.ContainsKey(slot))
{
slot++;
}
return slot;
}
private int? GetItemSlot(ulong itemid)
{
foreach(int slot in myOfferedItemsLocalCopy.Keys)
{
if(myOfferedItemsLocalCopy[slot].assetid == itemid)
{
return slot;
}
}
return null;
}
private void ValidateLocalTradeItems()
{
if (!myOfferedItemsLocalCopy.Values.OrderBy(o => o).SequenceEqual(MyOfferedItems.OrderBy(o => o)))
{
throw new TradeException("Error validating local copy of offered items in the trade");
}
}
}
}
| |
// 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.Collections.Generic;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using XunitPlatformID = Xunit.PlatformID;
namespace System.IO.Tests
{
public class FileStream_CopyToAsync : FileSystemTest
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void InvalidArgs_Throws(bool useAsync)
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x100, useAsync))
{
Assert.Throws<ArgumentNullException>("destination", () => { fs.CopyToAsync(null); });
Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { fs.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => { fs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
fs.Dispose();
Assert.Throws<ObjectDisposedException>(() => { fs.CopyToAsync(new MemoryStream()); });
}
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x100, useAsync))
{
fs.SafeFileHandle.Dispose();
Assert.Throws<ObjectDisposedException>(() => { fs.CopyToAsync(new MemoryStream()); });
}
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
{
Assert.Throws<NotSupportedException>(() => { fs.CopyToAsync(new MemoryStream()); });
}
using (FileStream src = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x100, useAsync))
using (FileStream dst = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x100, useAsync))
{
dst.Dispose();
Assert.Throws<ObjectDisposedException>(() => { src.CopyToAsync(dst); });
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task AlreadyCanceled_ReturnsCanceledTask(bool useAsync)
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x100, useAsync))
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => fs.CopyToAsync(fs, 0x1000, new CancellationToken(canceled: true)));
}
}
[Theory] // inner loop, just a few cases
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public Task File_AllDataCopied_InnerLoop(bool useAsync, bool preWrite)
{
return File_AllDataCopied(
_ => new MemoryStream(), useAsync, preRead: false, preWrite: preWrite, exposeHandle: false, cancelable: true,
bufferSize: 4096, writeSize: 1024, numWrites: 10);
}
[Theory] // outer loop, many combinations
[OuterLoop]
[MemberData(nameof(File_AllDataCopied_MemberData))]
public async Task File_AllDataCopied(
Func<string, Stream> createDestinationStream,
bool useAsync, bool preRead, bool preWrite, bool exposeHandle, bool cancelable,
int bufferSize, int writeSize, int numWrites)
{
// Create the expected data
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
// Write it out into the source file
string srcPath = GetTestFilePath();
File.WriteAllBytes(srcPath, expectedData);
string dstPath = GetTestFilePath();
using (FileStream src = new FileStream(srcPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
using (Stream dst = createDestinationStream(dstPath))
{
// If configured to expose the handle, do so. This influences the stream's need to ensure the position is in sync.
if (exposeHandle)
{
var ignored = src.SafeFileHandle;
}
// If configured to "preWrite", do a write before we start reading.
if (preWrite)
{
src.Write(new byte[] { 42 }, 0, 1);
dst.Write(new byte[] { 42 }, 0, 1);
expectedData[0] = 42;
}
// If configured to "preRead", read one byte from the source prior to the CopyToAsync.
// This helps test what happens when there's already data in the buffer, when the position
// isn't starting at zero, etc.
if (preRead)
{
int initialByte = src.ReadByte();
if (initialByte >= 0)
{
dst.WriteByte((byte)initialByte);
}
}
// Do the copy
await src.CopyToAsync(dst, writeSize, cancelable ? new CancellationTokenSource().Token : CancellationToken.None);
dst.Flush();
// Make sure we're at the end of the source file
Assert.Equal(src.Length, src.Position);
// Verify the copied data
dst.Position = 0;
var result = new MemoryStream();
dst.CopyTo(result);
byte[] actualData = result.ToArray();
Assert.Equal(expectedData.Length, actualData.Length);
Assert.Equal<byte>(expectedData, actualData);
}
}
public static IEnumerable<object[]> File_AllDataCopied_MemberData()
{
bool[] bools = new[] { true, false };
foreach (bool useAsync in bools) // sync or async mode
{
foreach (bool preRead in bools) // whether to do a read before the CopyToAsync
{
foreach (bool cancelable in bools) // whether to use a cancelable token
{
for (int streamType = 0; streamType < 2; streamType++) // kind of stream to use
{
Func<string, Stream> createDestinationStream;
switch (streamType)
{
case 0: createDestinationStream = _ => new MemoryStream(); break;
default: createDestinationStream = s => File.Create(s); break;
}
// Various exposeHandle (whether the SafeFileHandle was publically accessed),
// preWrite, bufferSize, writeSize, and numWrites combinations
yield return new object[] { createDestinationStream, useAsync, preRead, false, false, cancelable, 0x1000, 0x100, 100 };
yield return new object[] { createDestinationStream, useAsync, preRead, false, false, cancelable, 0x1, 0x1, 1000 };
yield return new object[] { createDestinationStream, useAsync, preRead, false, true, cancelable, 0x2, 0x100, 100 };
yield return new object[] { createDestinationStream, useAsync, preRead, false, false, cancelable, 0x4000, 0x10, 100 };
yield return new object[] { createDestinationStream, useAsync, preRead, false, true, cancelable, 0x1000, 99999, 10 };
}
}
}
}
}
[Theory]
[InlineData(10, 1024)]
public async Task AnonymousPipeViaFileStream_AllDataCopied(int writeSize, int numWrites)
{
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
var results = new MemoryStream();
using (var server = new AnonymousPipeServerStream(PipeDirection.Out))
{
Task serverTask = Task.Run(async () =>
{
for (int i = 0; i < numWrites; i++)
{
await server.WriteAsync(expectedData, i * writeSize, writeSize);
}
});
using (var client = new FileStream(new SafeFileHandle(server.ClientSafePipeHandle.DangerousGetHandle(), false), FileAccess.Read, bufferSize: 3))
{
Task copyTask = client.CopyToAsync(results, writeSize);
await await Task.WhenAny(serverTask, copyTask);
server.Dispose();
await copyTask;
}
}
byte[] actualData = results.ToArray();
Assert.Equal(expectedData.Length, actualData.Length);
Assert.Equal<byte>(expectedData, actualData);
}
[PlatformSpecific(XunitPlatformID.Windows)] // Uses P/Invokes to create async pipe handle
[Theory]
[InlineData(false, 10, 1024)]
[InlineData(true, 10, 1024)]
public async Task NamedPipeViaFileStream_AllDataCopied(bool useAsync, int writeSize, int numWrites)
{
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
var results = new MemoryStream();
var pipeOptions = useAsync ? PipeOptions.Asynchronous : PipeOptions.None;
string name = Guid.NewGuid().ToString("N");
using (var server = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, pipeOptions))
{
Task serverTask = Task.Run(async () =>
{
await server.WaitForConnectionAsync();
for (int i = 0; i < numWrites; i++)
{
await server.WriteAsync(expectedData, i * writeSize, writeSize);
}
server.Dispose();
});
Assert.True(WaitNamedPipeW(@"\\.\pipe\" + name, -1));
using (SafeFileHandle clientHandle = CreateFileW(@"\\.\pipe\" + name, GENERIC_READ, FileShare.None, IntPtr.Zero, FileMode.Open, (int)pipeOptions, IntPtr.Zero))
using (var client = new FileStream(clientHandle, FileAccess.Read, bufferSize: 3, isAsync: useAsync))
{
Task copyTask = client.CopyToAsync(results, (int)totalLength);
await await Task.WhenAny(serverTask, copyTask);
await copyTask;
}
}
byte[] actualData = results.ToArray();
Assert.Equal(expectedData.Length, actualData.Length);
Assert.Equal<byte>(expectedData, actualData);
}
[PlatformSpecific(XunitPlatformID.Windows)] // Uses P/Invokes to create async pipe handle
[Theory]
public async Task NamedPipeViaFileStream_CancellationRequested_OperationCanceled()
{
string name = Guid.NewGuid().ToString("N");
using (var server = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
Task serverTask = server.WaitForConnectionAsync();
Assert.True(WaitNamedPipeW(@"\\.\pipe\" + name, -1));
using (SafeFileHandle clientHandle = CreateFileW(@"\\.\pipe\" + name, GENERIC_READ, FileShare.None, IntPtr.Zero, FileMode.Open, (int)PipeOptions.Asynchronous, IntPtr.Zero))
using (var client = new FileStream(clientHandle, FileAccess.Read, bufferSize: 3, isAsync: true))
{
await serverTask;
var cts = new CancellationTokenSource();
Task clientTask = client.CopyToAsync(new MemoryStream(), 0x1000, cts.Token);
Assert.False(clientTask.IsCompleted);
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => clientTask);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task DerivedFileStream_ReadAsyncInvoked(bool useAsync)
{
var expectedData = new byte[100];
new Random(42).NextBytes(expectedData);
string srcPath = GetTestFilePath();
File.WriteAllBytes(srcPath, expectedData);
bool readAsyncInvoked = false;
using (var fs = new FileStreamThatOverridesReadAsync(srcPath, useAsync, () => readAsyncInvoked = true))
{
await fs.CopyToAsync(new MemoryStream());
Assert.True(readAsyncInvoked);
}
}
private class FileStreamThatOverridesReadAsync : FileStream
{
private readonly Action _readAsyncInvoked;
internal FileStreamThatOverridesReadAsync(string path, bool useAsync, Action readAsyncInvoked) :
base(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync)
{
_readAsyncInvoked = readAsyncInvoked;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
_readAsyncInvoked();
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
}
#region Windows P/Invokes
// We need to P/Invoke to test the named pipe async behavior with FileStream
// because NamedPipeClientStream internally binds the created handle,
// and that then prevents FileStream's constructor from working with the handle
// when trying to set isAsync to true.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitNamedPipeW(string name, int timeout);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern SafeFileHandle CreateFileW(
string lpFileName, int dwDesiredAccess, FileShare dwShareMode,
IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
internal const int GENERIC_READ = unchecked((int)0x80000000);
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/checkout/checkout_candidate_viability.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.Booking.Checkout {
/// <summary>Holder for reflection information generated from booking/checkout/checkout_candidate_viability.proto</summary>
public static partial class CheckoutCandidateViabilityReflection {
#region Descriptor
/// <summary>File descriptor for booking/checkout/checkout_candidate_viability.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CheckoutCandidateViabilityReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNib29raW5nL2NoZWNrb3V0L2NoZWNrb3V0X2NhbmRpZGF0ZV92aWFiaWxp",
"dHkucHJvdG8SHGhvbG1zLnR5cGVzLmJvb2tpbmcuY2hlY2tvdXQaPGJvb2tp",
"bmcvY2hlY2tvdXQvZGVwYXJ0dXJlX2RhdGVfY2hlY2tvdXRfYWNjZXB0aWJp",
"bGl0eS5wcm90bxouYm9va2luZy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9uX2lu",
"ZGljYXRvci5wcm90bxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3VudC5wcm90",
"bxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8i9wIKGkNoZWNrb3V0",
"Q2FuZGlkYXRlVmlhYmlsaXR5EkkKC3Jlc2VydmF0aW9uGAEgASgLMjQuaG9s",
"bXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNh",
"dG9yEkMKF2VmZmVjdGl2ZV9jaGVja291dF9kYXRlGAIgASgLMiIuaG9sbXMu",
"dHlwZXMucHJpbWl0aXZlLlBiTG9jYWxEYXRlElwKEmRhdGVfYWNjZXB0aWJp",
"bGl0eRgDIAEoDjJALmhvbG1zLnR5cGVzLmJvb2tpbmcuY2hlY2tvdXQuRGVw",
"YXJ0dXJlRGF0ZUNoZWNrb3V0QWNjZXB0aWJpbGl0eRI8Cg1mb2xpb19iYWxh",
"bmNlGAQgASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1v",
"dW50Ei0KJWZvbGlvX2JhbGFuY2VfYWNjZXB0aWJsZV9mb3JfY2hlY2tvdXQY",
"BSABKAhCH6oCHEhPTE1TLlR5cGVzLkJvb2tpbmcuQ2hlY2tvdXRiBnByb3Rv",
"Mw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Checkout.DepartureDateCheckoutAcceptibilityReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Checkout.CheckoutCandidateViability), global::HOLMS.Types.Booking.Checkout.CheckoutCandidateViability.Parser, new[]{ "Reservation", "EffectiveCheckoutDate", "DateAcceptibility", "FolioBalance", "FolioBalanceAcceptibleForCheckout" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CheckoutCandidateViability : pb::IMessage<CheckoutCandidateViability> {
private static readonly pb::MessageParser<CheckoutCandidateViability> _parser = new pb::MessageParser<CheckoutCandidateViability>(() => new CheckoutCandidateViability());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CheckoutCandidateViability> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Checkout.CheckoutCandidateViabilityReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckoutCandidateViability() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckoutCandidateViability(CheckoutCandidateViability other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
EffectiveCheckoutDate = other.effectiveCheckoutDate_ != null ? other.EffectiveCheckoutDate.Clone() : null;
dateAcceptibility_ = other.dateAcceptibility_;
FolioBalance = other.folioBalance_ != null ? other.FolioBalance.Clone() : null;
folioBalanceAcceptibleForCheckout_ = other.folioBalanceAcceptibleForCheckout_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckoutCandidateViability Clone() {
return new CheckoutCandidateViability(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "effective_checkout_date" field.</summary>
public const int EffectiveCheckoutDateFieldNumber = 2;
private global::HOLMS.Types.Primitive.PbLocalDate effectiveCheckoutDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate EffectiveCheckoutDate {
get { return effectiveCheckoutDate_; }
set {
effectiveCheckoutDate_ = value;
}
}
/// <summary>Field number for the "date_acceptibility" field.</summary>
public const int DateAcceptibilityFieldNumber = 3;
private global::HOLMS.Types.Booking.Checkout.DepartureDateCheckoutAcceptibility dateAcceptibility_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Checkout.DepartureDateCheckoutAcceptibility DateAcceptibility {
get { return dateAcceptibility_; }
set {
dateAcceptibility_ = value;
}
}
/// <summary>Field number for the "folio_balance" field.</summary>
public const int FolioBalanceFieldNumber = 4;
private global::HOLMS.Types.Primitive.MonetaryAmount folioBalance_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount FolioBalance {
get { return folioBalance_; }
set {
folioBalance_ = value;
}
}
/// <summary>Field number for the "folio_balance_acceptible_for_checkout" field.</summary>
public const int FolioBalanceAcceptibleForCheckoutFieldNumber = 5;
private bool folioBalanceAcceptibleForCheckout_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool FolioBalanceAcceptibleForCheckout {
get { return folioBalanceAcceptibleForCheckout_; }
set {
folioBalanceAcceptibleForCheckout_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CheckoutCandidateViability);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CheckoutCandidateViability other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if (!object.Equals(EffectiveCheckoutDate, other.EffectiveCheckoutDate)) return false;
if (DateAcceptibility != other.DateAcceptibility) return false;
if (!object.Equals(FolioBalance, other.FolioBalance)) return false;
if (FolioBalanceAcceptibleForCheckout != other.FolioBalanceAcceptibleForCheckout) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (effectiveCheckoutDate_ != null) hash ^= EffectiveCheckoutDate.GetHashCode();
if (DateAcceptibility != 0) hash ^= DateAcceptibility.GetHashCode();
if (folioBalance_ != null) hash ^= FolioBalance.GetHashCode();
if (FolioBalanceAcceptibleForCheckout != false) hash ^= FolioBalanceAcceptibleForCheckout.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 (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
if (effectiveCheckoutDate_ != null) {
output.WriteRawTag(18);
output.WriteMessage(EffectiveCheckoutDate);
}
if (DateAcceptibility != 0) {
output.WriteRawTag(24);
output.WriteEnum((int) DateAcceptibility);
}
if (folioBalance_ != null) {
output.WriteRawTag(34);
output.WriteMessage(FolioBalance);
}
if (FolioBalanceAcceptibleForCheckout != false) {
output.WriteRawTag(40);
output.WriteBool(FolioBalanceAcceptibleForCheckout);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (effectiveCheckoutDate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EffectiveCheckoutDate);
}
if (DateAcceptibility != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DateAcceptibility);
}
if (folioBalance_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FolioBalance);
}
if (FolioBalanceAcceptibleForCheckout != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CheckoutCandidateViability other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.effectiveCheckoutDate_ != null) {
if (effectiveCheckoutDate_ == null) {
effectiveCheckoutDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
EffectiveCheckoutDate.MergeFrom(other.EffectiveCheckoutDate);
}
if (other.DateAcceptibility != 0) {
DateAcceptibility = other.DateAcceptibility;
}
if (other.folioBalance_ != null) {
if (folioBalance_ == null) {
folioBalance_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
FolioBalance.MergeFrom(other.FolioBalance);
}
if (other.FolioBalanceAcceptibleForCheckout != false) {
FolioBalanceAcceptibleForCheckout = other.FolioBalanceAcceptibleForCheckout;
}
}
[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 (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
if (effectiveCheckoutDate_ == null) {
effectiveCheckoutDate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(effectiveCheckoutDate_);
break;
}
case 24: {
dateAcceptibility_ = (global::HOLMS.Types.Booking.Checkout.DepartureDateCheckoutAcceptibility) input.ReadEnum();
break;
}
case 34: {
if (folioBalance_ == null) {
folioBalance_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(folioBalance_);
break;
}
case 40: {
FolioBalanceAcceptibleForCheckout = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
namespace Simple.Data.IntegrationTest.Query
{
using Mocking.Ado;
using NUnit.Framework;
[TestFixture]
public class WithTest : DatabaseIntegrationContext
{
protected override void SetSchema(MockSchemaProvider schemaProvider)
{
// ReSharper disable CoVariantArrayConversion
schemaProvider.SetTables(new[] { "dbo", "Employee", "BASE TABLE" },
new[] { "dbo", "Department", "BASE TABLE" },
new[] { "dbo", "Activity", "BASE TABLE" },
new[] { "dbo", "Customer", "BASE TABLE" },
new[] { "dbo", "Order", "BASE TABLE" },
new[] { "dbo", "Item", "BASE TABLE" },
new[] { "dbo", "Note", "BASE TABLE" },
new[] { "dbo", "Activity_Join", "BASE TABLE" },
new[] { "dbo", "Location", "BASE_TABLE" });
schemaProvider.SetColumns(new[] { "dbo", "Employee", "Id" },
new[] { "dbo", "Employee", "Name" },
new[] { "dbo", "Employee", "ManagerId" },
new[] { "dbo", "Employee", "DepartmentId" },
new[] { "dbo", "Department", "Id" },
new[] { "dbo", "Department", "Name" },
new[] { "dbo", "Customer", "Id" },
new[] { "dbo", "Customer", "Name" },
new[] { "dbo", "Order", "Id" },
new[] { "dbo", "Order", "CustomerId" },
new[] { "dbo", "Order", "Description" },
new[] { "dbo", "Item", "Id" },
new[] { "dbo", "Item", "OrderId" },
new[] { "dbo", "Item", "Description" },
new[] { "dbo", "Note", "Id" },
new[] { "dbo", "Note", "CustomerId" },
new[] { "dbo", "Note", "Text" },
new[] { "dbo", "Activity", "ID" },
new[] { "dbo", "Activity", "Description" },
new[] { "dbo", "Activity_Join", "ID_Activity" },
new[] { "dbo", "Activity_Join", "ID_Location" },
new[] { "dbo", "Location", "ID" },
new[] { "dbo", "Location", "Address" }
);
schemaProvider.SetPrimaryKeys(new object[] {"dbo", "Employee", "Id", 0},
new object[] {"dbo", "Department", "Id", 0},
new object[] {"dbo", "Customer", "Id", 0},
new object[] {"dbo", "Order", "Id", 0},
new object[] {"dbo", "Item", "Id", 0},
new object[] {"dbo", "Note", "Id", 0}
);
schemaProvider.SetForeignKeys(
new object[] { "FK_Employee_Department", "dbo", "Employee", "DepartmentId", "dbo", "Department", "Id", 0 },
new object[] { "FK_Activity_Join_Activity", "dbo", "Activity_Join", "ID_Activity", "dbo", "Activity", "ID", 0 },
new object[] { "FK_Activity_Join_Location", "dbo", "Activity_Join", "ID_Location", "dbo", "Location", "ID", 0 },
new object[] { "FK_Order_Customer", "dbo", "Order", "CustomerId", "dbo", "Customer", "Id", 0 },
new object[] { "FK_Item_Order", "dbo", "Item", "OrderId", "dbo", "Order", "Id", 0 },
new object[] { "FK_Note_Customer", "dbo", "Note", "CustomerId", "dbo", "Customer", "Id", 0 }
);
// ReSharper restore CoVariantArrayConversion
}
[Test]
public void SingleWithClauseUsingMagicMethodShouldUseWith1Join()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name],"+
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid],"+
"[dbo].[department].[id] as [__with1__department__id],[dbo].[department].[name] as [__with1__department__name]"+
" from [dbo].[employee] left join [dbo].[department] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])";
var q = _db.Employees.All().WithDepartment();
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithClauseUsingMagicMethodShouldUseWithNJoin()
{
const string expectedSql = "select " +
"[dbo].[department].[id],[dbo].[department].[name],"+
"[dbo].[employee].[id] as [__withn__employees__id],[dbo].[employee].[name] as [__withn__employees__name],"+
"[dbo].[employee].[managerid] as [__withn__employees__managerid],[dbo].[employee].[departmentid] as [__withn__employees__departmentid]"+
" from [dbo].[department] left join [dbo].[employee] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])";
var q = _db.Departments.All().WithEmployees();
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithClauseUsingReferenceShouldUseJoin()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[dbo].[department].[id] as [__with1__department__id],[dbo].[department].[name] as [__with1__department__name]" +
" from [dbo].[employee] left join [dbo].[department] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])";
var q = _db.Employees.All().With(_db.Employees.Department);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithOneClauseUsingReferenceShouldUseJoinAndForceOne()
{
const string expectedSql = "select " +
"[dbo].[department].[id],[dbo].[department].[name]," +
"[dbo].[employee].[id] as [__with1__employee__id],[dbo].[employee].[name] as [__with1__employee__name]," +
"[dbo].[employee].[managerid] as [__with1__employee__managerid],[dbo].[employee].[departmentid] as [__with1__employee__departmentid]" +
" from [dbo].[department] left join [dbo].[employee] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])";
var q = _db.Departments.All().WithOne(_db.Departments.Employee);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithClauseUsingReferenceWithAliasShouldApplyAliasToSql()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[foo].[id] as [__with1__foo__id],[foo].[name] as [__with1__foo__name]" +
" from [dbo].[employee] left join [dbo].[department] [foo] on ([foo].[id] = [dbo].[employee].[departmentid])";
var q = _db.Employees.All().With(_db.Employees.Department.As("Foo"));
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithClauseUsingTwoStepReference()
{
const string expectedSql = "select "+
"[dbo].[activity].[id],"+
"[dbo].[activity].[description],"+
"[dbo].[location].[id] as [__withn__location__id]," +
"[dbo].[location].[address] as [__withn__location__address]" +
" from [dbo].[activity] "+
"left join [dbo].[activity_join] on ([dbo].[activity].[id] = [dbo].[activity_join].[id_activity]) "+
"left join [dbo].[location] on ([dbo].[location].[id] = [dbo].[activity_join].[id_location])";
var q = _db.Activity.All().With(_db.Activity.ActivityJoin.Location);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithClauseUsingExplicitJoinShouldApplyAliasToSql()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[manager].[id] as [__withn__manager__id],[manager].[name] as [__withn__manager__name]," +
"[manager].[managerid] as [__withn__manager__managerid],[manager].[departmentid] as [__withn__manager__departmentid]" +
" from [dbo].[employee] left join [dbo].[employee] [manager] on ([manager].[id] = [dbo].[employee].[managerid])";
dynamic manager;
var q = _db.Employees.All()
.OuterJoin(_db.Employees.As("Manager"), out manager).On(Id: _db.Employees.ManagerId)
.With(manager);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void SingleWithOneClauseUsingExplicitJoinShouldApplyAliasToSql()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[manager].[id] as [__with1__manager__id],[manager].[name] as [__with1__manager__name]," +
"[manager].[managerid] as [__with1__manager__managerid],[manager].[departmentid] as [__with1__manager__departmentid]" +
" from [dbo].[employee] left join [dbo].[employee] [manager] on ([manager].[id] = [dbo].[employee].[managerid])";
dynamic manager;
var q = _db.Employees.All()
.OuterJoin(_db.Employees.As("Manager"), out manager).On(Id: _db.Employees.ManagerId)
.WithOne(manager);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void MultipleWithClauseJustDoesEverythingYouWouldHope()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[manager].[id] as [__withn__manager__id],[manager].[name] as [__withn__manager__name]," +
"[manager].[managerid] as [__withn__manager__managerid],[manager].[departmentid] as [__withn__manager__departmentid]," +
"[dbo].[department].[id] as [__with1__department__id],[dbo].[department].[name] as [__with1__department__name]" +
" from [dbo].[employee] left join [dbo].[employee] [manager] on ([manager].[id] = [dbo].[employee].[managerid])" +
" left join [dbo].[department] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])";
dynamic manager;
var q = _db.Employees.All()
.OuterJoin(_db.Employees.As("Manager"), out manager).On(Id: _db.Employees.ManagerId)
.With(manager)
.WithDepartment();
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
/// <summary>
/// Test for multiple child tables...
/// </summary>
[Test]
public void CustomerWithOrdersAndNotes()
{
const string expectedSql = "select [dbo].[customer].[id],[dbo].[customer].[name]," +
"[dbo].[order].[id] as [__withn__orders__id],[dbo].[order].[customerid] as [__withn__orders__customerid],[dbo].[order].[description] as [__withn__orders__description]," +
"[dbo].[note].[id] as [__withn__notes__id],[dbo].[note].[customerid] as [__withn__notes__customerid],[dbo].[note].[text] as [__withn__notes__text]" +
" from [dbo].[customer]" +
" left join [dbo].[order] on ([dbo].[customer].[id] = [dbo].[order].[customerid])" +
" left join [dbo].[note] on ([dbo].[customer].[id] = [dbo].[note].[customerid])";
var q = _db.Customers.All().WithOrders().WithNotes();
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
[Test]
public void CustomerWithOrdersWithItems()
{
const string expectedSql = "select [dbo].[Customer].[Id],[dbo].[Customer].[Name]," +
"[dbo].[Order].[Id] AS [__withn__Orders__Id],[dbo].[Order].[CustomerId] AS [__withn__Orders__CustomerId]," +
"[dbo].[Order].[Description] AS [__withn__Orders__Description],[dbo].[Item].[Id] AS [__withn__Items__Id]," +
"[dbo].[Item].[OrderId] AS [__withn__Items__OrderId],[dbo].[Item].[Description] AS [__withn__Items__Description]" +
" from [dbo].[Customer] LEFT JOIN [dbo].[Order] ON ([dbo].[Customer].[Id] = [dbo].[Order].[CustomerId])" +
" LEFT JOIN [dbo].[Item] ON ([dbo].[Order].[Id] = [dbo].[Item].[OrderId])";
var q = _db.Customers.All().With(_db.Customers.Orders).With(_db.Customers.Orders.Items);
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
/// <summary>
/// Test for issue #157
/// </summary>
[Test]
public void CriteriaReferencesShouldNotBeDuplicatedInSql()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[dbo].[department].[id] as [__with1__department__id],[dbo].[department].[name] as [__with1__department__name]" +
" from [dbo].[employee] join [dbo].[department] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])" +
" where [dbo].[department].[name] = @p1";
var q = _db.Employees.FindAll(_db.Employees.Department.Name == "Dev").WithDepartment();
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
/// <summary>
/// Test for issue #184
/// </summary>
[Test]
public void CriteriaReferencesShouldUseWithAliasOutValue()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[foo].[id] as [__with1__foo__id],[foo].[name] as [__with1__foo__name]" +
" from [dbo].[employee] join [dbo].[department] [foo] on ([foo].[id] = [dbo].[employee].[departmentid])" +
" where ([dbo].[employee].[name] like @p1" +
" and [foo].[name] = @p2)";
dynamic foo;
var q = _db.Employees.Query()
.Where(_db.Employees.Name.Like("A%"))
.WithOne(_db.Employees.Department.As("Foo"), out foo)
.Where(foo.Name == "Admin");
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
/// <summary>
/// Test for issue #184
/// </summary>
[Test]
public void CriteriaReferencesShouldUseSeparateJoinFromWithAlias()
{
const string expectedSql = "select [dbo].[employee].[id],[dbo].[employee].[name]," +
"[dbo].[employee].[managerid],[dbo].[employee].[departmentid]," +
"[foo].[id] as [__with1__foo__id],[foo].[name] as [__with1__foo__name]" +
" from [dbo].[employee]" +
" join [dbo].[department] on ([dbo].[department].[id] = [dbo].[employee].[departmentid])" +
" left join [dbo].[department] [foo] on ([foo].[id] = [dbo].[employee].[departmentid])" +
" where ([dbo].[employee].[name] like @p1" +
" and [dbo].[department].[name] = @p2)";
var q = _db.Employees.Query()
.Where(_db.Employees.Name.Like("A%"))
.WithOne(_db.Employees.Department.As("Foo"))
.Where(_db.Employees.Department.Name == "Admin");
EatException(() => q.ToList());
GeneratedSqlIs(expectedSql);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
private readonly HashSet<DocumentKey> _filesInProjects = new HashSet<DocumentKey>();
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, "MiscellaneousFiles")
{
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
internal void OnFileIncludedInProject(IVisualStudioHostDocument document)
{
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.FilePath, out docCookie))
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, document.FilePath);
}
_filesInProjects.Add(document.Key);
}
internal void OnFileRemovedFromProject(IVisualStudioHostDocument document)
{
// Remove the document key from the filesInProjects map first because adding documents
// to the misc files workspace requires that they not appear in this map.
_filesInProjects.Remove(document.Key);
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.Key.Moniker, out docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, document.Key.Moniker);
}
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, moniker);
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(uint docCookie, string moniker)
{
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation != null &&
!_filesInProjects.Any(d => StringComparer.OrdinalIgnoreCase.Equals(d.Moniker, moniker)) &&
!_docCookiesToHostProject.ContainsKey(docCookie))
{
// See if we should push to this to the metadata-to-source workspace instead.
if (_runningDocumentTable.IsDocumentInitialized(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
}
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(hostProject, (uint)VSConstants.VSITEMID.Nil, moniker, parseOptions.Kind, t => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProject(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
}
private bool TryRemoveDocumentFromMiscellaneousWorkspace(uint docCookie, string moniker)
{
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return true;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
return true;
}
return false;
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IEnumerable<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values;
}
void IVisualStudioHostProjectContainer.NotifyNonDocumentOpenedForProject(IVisualStudioHostProject project)
{
// Since the MiscellaneousFilesWorkspace doesn't do anything lazily, this is a no-op
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; }
public string ScriptExtension { get; }
public ParseOptions ParseOptions { get; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace ProtoCore
{
public class BuildHaltException : Exception
{
public string errorMsg { get; private set; }
public BuildHaltException()
{
errorMsg = "Stopping Build\n";
}
public BuildHaltException(string message)
{
errorMsg = message + '\n';
}
}
namespace BuildData
{
public enum WarningID
{
kDefault,
kAccessViolation,
kCallingConstructorInConstructor,
kCallingConstructorOnInstance,
kCallingNonStaticMethodOnClass,
kFunctionAbnormalExit,
kFunctionAlreadyDefined,
kFunctionNotFound,
kIdUnboundIdentifier,
kInvalidArguments,
kInvalidStaticCyclicDependency,
kInvalidRangeExpression,
kInvalidThis,
kMismatchReturnType,
kMissingReturnStatement,
kParsing,
kTypeUndefined,
kPropertyNotFound,
kFileNotFound,
kAlreadyImported,
kWarnMax
}
public struct WarningMessage
{
public const string kAssingToThis = "'this' is readonly and cannot be assigned to.";
public const string kCallingNonStaticProperty = "'{0}.{1}' is not a static property.";
public const string kCallingNonStaticMethod = "'{0}.{1}()' is not a static method.";
public const string kMethodHasInvalidArguments = "'{0}()' has some invalid arguments.";
public const string kInvalidStaticCyclicDependency = "Cyclic dependency detected at '{0}' and '{1}'.";
public const string KCallingConstructorOnInstance = "Cannot call constructor '{0}()' on instance.";
public const string kPropertyIsInaccessible = "Property '{0}' is inaccessible.";
public const string kMethodIsInaccessible = "Method '{0}()' is inaccessible.";
public const string kCallingConstructorInConstructor = "Cannot call constructor '{0}()' in itself.";
public const string kPropertyNotFound = "Property '{0}' not found";
public const string kMethodNotFound = "Method '{0}()' not found";
public const string kUnboundIdentifierMsg = "Variable '{0}' hasn't been defined yet.";
public const string kFunctionNotReturnAtAllCodePaths = "Method '{0}()' doesn't return at all code paths.";
public const string kRangeExpressionWithStepSizeZero = "The step size of range expression should not be 0.";
public const string kRangeExpressionWithInvalidStepSize = "The step size of range expression is invalid.";
public const string kRangeExpressionWithNonIntegerStepNumber = "The step number of range expression should be integer.";
public const string kRangeExpressionWithNegativeStepNumber = "The step number of range expression should be greater than 0.";
public const string kTypeUndefined = "Type '{0}' is not defined.";
public const string kMethodAlreadyDefined = "Method '{0}()' is already defined.";
public const string kReturnTypeUndefined = "Return type '{0}' of method '{1}()' is not defined.";
public const string kExceptionTypeUndefined = "Exception type '{0}' is not defined.";
public const string kArgumentTypeUndefined = "Type '{0}' of argument '{1}' is not defined.";
public const string kInvalidBreakForFunction = "Statement break causes function to abnormally return null.";
public const string kInvalidContinueForFunction = "Statement continue cause function to abnormally return null.";
public const string kUsingThisInStaticFunction = "'this' cannot be used in static method.";
public const string kInvalidThis = "'this' can only be used in member methods.";
public const string kUsingNonStaticMemberInStaticContext = "'{0}' is not a static property, so cannot be assigned to static properties or used in static methods.";
public const string kFileNotFound = "File : '{0}' not found";
public const string kAlreadyImported = "File : '{0}' is already imported";
}
public struct ErrorEntry
{
public string FileName;
public string Message;
public int Line;
public int Col;
}
public struct WarningEntry
{
public WarningID id;
public string msg;
public int line;
public int col;
public string FileName;
}
}
public class OutputMessage
{
public enum MessageType { Info, Warning, Error }
// A constructor for message only for print-out purpose
public OutputMessage(string message)
{
Type = MessageType.Info;
Message = message;
FilePath = string.Empty;
Line = -1;
Column = -1;
}
// A constructor for generic message.
public OutputMessage(MessageType type, string message)
{
Type = type;
Message = message;
FilePath = string.Empty;
Line = -1;
Column = -1;
}
// A constructor for source location related messages.
public OutputMessage(MessageType type, string message,
string filePath, int line, int column)
{
Type = type;
Message = message;
FilePath = filePath;
Line = line;
Column = column;
}
public MessageType Type { get; private set; }
public string FilePath { get; private set; }
public int Line { get; private set; }
public int Column { get; private set; }
public string Message { get; private set; }
public bool Continue { get; set; }
}
public interface IOutputStream
{
void Write(OutputMessage message);
List<OutputMessage> GetMessages();
}
public class FileOutputStream : IOutputStream
{
StreamWriter FileStream { get; set; }
public FileOutputStream(StreamWriter sw)
{
FileStream = sw;
}
public void Write(ProtoCore.OutputMessage message)
{
if (null == message)
return;
if (string.IsNullOrEmpty(message.FilePath))
{
// Type: Message
string formatWithoutFile = "{0}: {1}";
FileStream.WriteLine(string.Format(formatWithoutFile,
message.Type.ToString(), message.Message));
}
else
{
// Type: Message (File - Line, Column)
string formatWithFile = "{0}: {1} ({2} - line: {3}, col: {4})";
FileStream.WriteLine(string.Format(formatWithFile,
message.Type.ToString(), message.Message,
message.FilePath, message.Line, message.Column));
}
if (message.Type == ProtoCore.OutputMessage.MessageType.Warning)
message.Continue = true;
}
public List<ProtoCore.OutputMessage> GetMessages()
{
return null;
}
}
public class TextOutputStream : IOutputStream
{
public StringWriter TextStream { get; private set; }
public Dictionary<int, List<string>> Map { get; private set; }
public TextOutputStream(StringWriter sw, Dictionary<int, List<string>> map)
{
TextStream = sw;
Map = map;
}
public TextOutputStream(Dictionary<int, List<string>> map)
{
TextStream = new StringWriter();
Map = map;
}
public void Write(ProtoCore.OutputMessage message)
{
if (null == message)
return;
if (string.IsNullOrEmpty(message.FilePath))
{
// Type: Message
string formatWithoutFile = "{0}: {1}";
TextStream.WriteLine(string.Format(formatWithoutFile,
message.Type.ToString(), message.Message));
}
else
{
// Type: Message (File - Line, Column)
string formatWithFile = "{0}: {1} ({2} - line: {3}, col: {4})";
TextStream.WriteLine(string.Format(formatWithFile,
message.Type.ToString(), message.Message,
message.FilePath, message.Line, message.Column));
}
if (message.Type == ProtoCore.OutputMessage.MessageType.Warning)
message.Continue = true;
}
public List<ProtoCore.OutputMessage> GetMessages()
{
return null;
}
}
public class ConsoleOutputStream : IOutputStream
{
public ConsoleOutputStream()
{
}
public void Write(ProtoCore.OutputMessage message)
{
if (null == message)
return;
if (string.IsNullOrEmpty(message.FilePath))
{
// Type: Message
string formatWithoutFile = "{0}: {1}";
System.Console.WriteLine(string.Format(formatWithoutFile,
message.Type.ToString(), message.Message));
}
else
{
// Type: Message (File - Line, Column)
string formatWithFile = "{0}: {1} ({2} - line: {3}, col: {4})";
System.Console.WriteLine(string.Format(formatWithFile,
message.Type.ToString(), message.Message,
message.FilePath, message.Line, message.Column));
}
if (message.Type == ProtoCore.OutputMessage.MessageType.Warning)
message.Continue = true;
}
public List<ProtoCore.OutputMessage> GetMessages()
{
return null;
}
}
public class WebOutputStream : IOutputStream
{
public ProtoCore.Core core;
public ProtoLanguage.CompileStateTracker compileState;
public string filename;
public WebOutputStream(ProtoCore.Core core)
{
this.core = core;
this.filename = this.core.CurrentDSFileName;
}
public WebOutputStream(ProtoLanguage.CompileStateTracker state)
{
this.compileState = state;
this.filename = state.CurrentDSFileName;
}
public string GetCurrentFileName()
{
return this.filename;
}
public void Write(ProtoCore.OutputMessage message)
{
if (null == message)
return;
if (string.IsNullOrEmpty(message.FilePath))
{
// Type: Message
string formatWithoutFile = "{0}: {1}";
//System.IO.StreamWriter logFile = new System.IO.StreamWriter("c:\\test.txt");
if (null != compileState.ExecutionLog)
{
compileState.ExecutionLog.WriteLine(string.Format(formatWithoutFile,
message.Type.ToString(), message.Message));
}
//logFile.Close();
// System.Console.WriteLine(string.Format(formatWithoutFile,
// message.Type.ToString(), message.Message));
}
else
{
// Type: Message (File - Line, Column)
if (null != compileState.ExecutionLog)
{
string formatWithFile = "{0}: {1} ({2} - line: {3}, col: {4})";
compileState.ExecutionLog.WriteLine(string.Format(formatWithFile,
message.Type.ToString(), message.Message,
message.FilePath, message.Line, message.Column));
}
//System.Console.WriteLine(string.Format(formatWithFile,
// message.Type.ToString(), message.Message,
// message.FilePath, message.Line, message.Column));
}
if (message.Type == ProtoCore.OutputMessage.MessageType.Warning)
message.Continue = true;
}
public void Close()
{
if (null != compileState.ExecutionLog)
compileState.ExecutionLog.Close();
}
public List<ProtoCore.OutputMessage> GetMessages()
{
return null;
}
}
public class BuildStatus
{
//private Core core;
private ProtoLanguage.CompileStateTracker compileState;
private System.IO.TextWriter consoleOut = System.Console.Out;
private readonly bool LogWarnings = true;
private readonly bool logErrors = true;
private readonly bool displayBuildResult = true;
private readonly bool warningAsError;
private readonly bool errorAsWarning = false;
private readonly List<BuildData.WarningEntry> warnings;
public List<BuildData.WarningEntry> Warnings
{
get
{
return warnings;
}
}
public IOutputStream MessageHandler { get; set; }
public WebOutputStream WebMsgHandler { get; set; }
private readonly List<BuildData.ErrorEntry> errors;
public List<BuildData.ErrorEntry> Errors
{
get
{
return errors;
}
}
public int ErrorCount
{
get { return Errors.Count; }
}
public int WarningCount
{
get { return Warnings.Count; }
}
public BuildStatus(ProtoLanguage.CompileStateTracker compilestate, bool warningAsError, System.IO.TextWriter writer = null, bool errorAsWarning = false)
{
this.compileState = compilestate;
warnings = new List<BuildData.WarningEntry>();
errors = new List<BuildData.ErrorEntry>();
this.warningAsError = warningAsError;
this.errorAsWarning = errorAsWarning;
if (writer != null)
{
consoleOut = System.Console.Out;
System.Console.SetOut(writer);
}
// Create a default console output stream, and this can
// be overwritten in IDE by assigning it a different value.
this.MessageHandler = new ConsoleOutputStream();
if (compilestate.Options.WebRunner)
{
this.WebMsgHandler = new WebOutputStream(compilestate);
}
}
public BuildStatus(ProtoLanguage.CompileStateTracker compilestate, bool LogWarnings, bool logErrors, bool displayBuildResult, System.IO.TextWriter writer = null)
{
this.compileState = compilestate;
this.LogWarnings = LogWarnings;
this.logErrors = logErrors;
this.displayBuildResult = displayBuildResult;
//this.errorCount = 0;
//this.warningCount = 0;
warnings = new List<BuildData.WarningEntry>();
errors = new List<BuildData.ErrorEntry>();
if (writer != null)
{
consoleOut = System.Console.Out;
System.Console.SetOut(writer);
}
// Create a default console output stream, and this can
// be overwritten in IDE by assigning it a different value.
this.MessageHandler = new ConsoleOutputStream();
}
public void SetStream(System.IO.TextWriter writer)
{
// flush the stream first
System.Console.Out.Flush();
if (writer != null)
{
consoleOut = System.Console.Out;
System.Console.SetOut(writer);
}
else
{
System.Console.SetOut(consoleOut);
}
}
public void LogSyntaxError(string msg, string fileName = null, int line = -1, int col = -1)
{
// Error: " + msg + "\n";
/*if (fileName == null)
{
fileName = "N.A.";
}*/
if (logErrors)
{
var message = string.Format("{0}({1},{2}) Error:{3}", fileName, line, col, msg);
System.Console.WriteLine(message);
}
BuildData.ErrorEntry errorEntry = new BuildData.ErrorEntry
{
FileName = fileName,
Message = msg,
Line = line,
Col = col
};
if (compileState.Options.IsDeltaExecution)
{
compileState.LogErrorInGlobalMap(ProtoLanguage.CompileStateTracker.ErrorType.Error, msg, fileName, line, col);
}
errors.Add(errorEntry);
OutputMessage outputmessage = new OutputMessage(OutputMessage.MessageType.Error, msg.Trim(), fileName, line, col);
if (MessageHandler != null)
{
MessageHandler.Write(outputmessage);
if (WebMsgHandler != null)
{
OutputMessage webOutputMsg = new OutputMessage(OutputMessage.MessageType.Error, msg.Trim(), "", line, col);
WebMsgHandler.Write(webOutputMsg);
}
if (!outputmessage.Continue)
throw new BuildHaltException(msg);
}
}
public void LogSemanticError(string msg, string fileName = null, int line = -1, int col = -1, AssociativeGraph.GraphNode graphNode = null)
{
if (logErrors)
{
System.Console.WriteLine("{0}({1},{2}) Error:{3}", fileName, line, col, msg);
}
if (compileState.Options.IsDeltaExecution)
{
compileState.LogErrorInGlobalMap(ProtoLanguage.CompileStateTracker.ErrorType.Error, msg, fileName, line, col);
}
BuildData.ErrorEntry errorEntry = new BuildData.ErrorEntry
{
FileName = fileName,
Message = msg,
Line = line,
Col = col
};
errors.Add(errorEntry);
OutputMessage outputmessage = new OutputMessage(OutputMessage.MessageType.Error, msg.Trim(), fileName, line, col);
if (MessageHandler != null)
{
MessageHandler.Write(outputmessage);
if (WebMsgHandler != null)
{
OutputMessage webOutputMsg = new OutputMessage(OutputMessage.MessageType.Error, msg.Trim(), "", line, col);
WebMsgHandler.Write(webOutputMsg);
}
if (!outputmessage.Continue)
throw new BuildHaltException(msg);
}
throw new BuildHaltException(msg);
}
public void LogWarning(BuildData.WarningID warnId, string msg, string fileName = null, int line = -1, int col = -1)
{
//"> Warning: " + msg + "\n"
/*if (fileName == null)
{
fileName = "N.A.";
}*/
if (LogWarnings)
{
System.Console.WriteLine("{0}({1},{2}) Warning:{3}", fileName, line, col, msg);
}
BuildData.WarningEntry warningEntry = new BuildData.WarningEntry { id = warnId, msg = msg, line = line, col = col, FileName = fileName };
warnings.Add(warningEntry);
if (compileState.Options.IsDeltaExecution)
{
compileState.LogErrorInGlobalMap(ProtoLanguage.CompileStateTracker.ErrorType.Warning, msg, fileName, line, col, warnId);
}
OutputMessage outputmessage = new OutputMessage(OutputMessage.MessageType.Warning, msg.Trim(), fileName, line, col);
if (MessageHandler != null)
{
MessageHandler.Write(outputmessage);
if (WebMsgHandler != null)
{
OutputMessage webOutputMsg = new OutputMessage(OutputMessage.MessageType.Warning, msg.Trim(), "", line, col);
WebMsgHandler.Write(webOutputMsg);
}
if (!outputmessage.Continue)
throw new BuildHaltException(msg);
}
}
public bool ContainsWarning(BuildData.WarningID warnId)
{
foreach (BuildData.WarningEntry warn in warnings)
{
if (warnId == warn.id)
return true;
}
return false;
}
public void ReportBuildResult()
{
string buildResult = string.Format("========== Build: {0} error(s), {1} warning(s) ==========\n", errors.Count, warnings.Count);
if (displayBuildResult)
{
System.Console.WriteLine(buildResult);
}
if (MessageHandler != null)
{
OutputMessage outputMsg = new OutputMessage(OutputMessage.MessageType.Info, buildResult.Trim());
MessageHandler.Write(outputMsg);
if (WebMsgHandler != null)
{
WebMsgHandler.Write(outputMsg);
}
}
}
public bool GetBuildResult(out int errcount, out int warncount)
{
// TODO Jun: Integrate with the autogen parser
// The autogen parser whould pass its error and warning results to this class
//int errorCount = errors.Count;
//int warningCount = warnings.Count;
errcount = ErrorCount;
warncount = WarningCount;
return (warningAsError) ? (0 == errcount && 0 == warncount) : (0 == errcount);
}
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.AdManager.v202105;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Reflection;
namespace Google.Api.Ads.AdManager.Util.v202105
{
/// <summary>
/// A utility class for handling PQL objects.
/// </summary>
public class PqlUtilities
{
/// <summary>
/// Gets the underlying value of the Value object. For SetValues, returns
/// a List of underlying values.
/// </summary>
/// <value>The Value object to get the value from.</value>
/// <returns>The underlying value, or List of underlying values from a SetValue.</returns>
public static object GetValue(Value value)
{
if (value is SetValue)
{
PropertyInfo propInfo = value.GetType().GetProperty("values");
if (propInfo != null)
{
Value[] setValues = propInfo.GetValue(value, null) as Value[];
List<object> extractedValues = new List<object>();
foreach (Value setValue in setValues)
{
validateSetValueForSet(GetValue(setValue), extractedValues);
extractedValues.Add(GetValue(setValue));
}
return extractedValues;
}
}
else
{
PropertyInfo propInfo = value.GetType().GetProperty("value");
if (propInfo != null)
{
return propInfo.GetValue(value, null);
}
}
return null;
}
private static void validateSetValueForSet(object entry, IList<object> set)
{
if (entry is IList<object> || entry is SetValue)
{
throw new ArgumentException("Unsupported Value type [nested sets]");
}
if (set.Count > 0)
{
IEnumerator<Object> enumerator = set.GetEnumerator();
enumerator.MoveNext();
Object existingEntry = enumerator.Current;
if (!existingEntry.GetType().IsAssignableFrom(entry.GetType()))
{
throw new ArgumentException(String.Format(
"Unsupported Value type [SetValue with " + "mixed types {0} and {1}]",
existingEntry.GetType(), entry.GetType()));
}
}
}
/// <summary>
/// Gets the result set as list of string arrays.
/// </summary>
/// <param name="resultSet">The result set to convert to a string array list.</param>
/// <returns>A list of string arrays representing the result set.</returns>
public static List<String[]> ResultSetToStringArrayList(ResultSet resultSet)
{
List<string[]> stringArrayList = new List<string[]>();
stringArrayList.Add(GetColumnLabels(resultSet));
if (resultSet.rows != null)
{
foreach (Row row in resultSet.rows)
{
stringArrayList.Add(GetRowStringValues(row));
}
}
return stringArrayList;
}
/// <summary>
/// Gets the result set as a table represenation in the form of:
///
/// <pre>
/// +-------+-------+-------+
/// |column1|column2|column3|
/// +-------+-------+-------+
/// |value1 |value2 |value3 |
/// +-------+-------+-------+
/// |value1 |value2 |value3 |
/// +-------+-------+-------+
/// </pre>
/// </summary>
/// <param name="resultSet">The result set to display as a string</param>
/// <returns>The string represenation of result set as a table.</returns>
public static String ResultSetToString(ResultSet resultSet)
{
StringBuilder resultSetStringBuilder = new StringBuilder();
List<String[]> resultSetStringArrayList = ResultSetToStringArrayList(resultSet);
List<int> maxColumnSizes = GetMaxColumnSizes(resultSetStringArrayList);
string rowTemplate = CreateRowTemplate(maxColumnSizes);
string rowSeparator = CreateRowSeperator(maxColumnSizes);
resultSetStringBuilder.Append(rowSeparator);
for (int i = 0; i < resultSetStringArrayList.Count; i++)
{
resultSetStringBuilder
.AppendFormat(rowTemplate, (object[]) resultSetStringArrayList[i])
.Append(rowSeparator);
}
return resultSetStringBuilder.ToString();
}
/// <summary>
/// Creates the row template given the maximum size for each column.
/// </summary>
/// <param name="maxColumnSizes">The maximum size for each column</param>
/// <returns>The row template to format row data into.</returns>
private static string CreateRowTemplate(List<int> maxColumnSizes)
{
List<String> columnFormatSpecifiers = new List<string>();
int i = 0;
foreach (int maxColumnSize in maxColumnSizes)
{
columnFormatSpecifiers.Add(string.Format("{{{0},{1}}}", i, maxColumnSize));
i++;
}
return new StringBuilder("| ")
.Append(string.Join(" | ", columnFormatSpecifiers.ToArray())).Append(" |\n")
.ToString();
}
/// <summary>
/// Creates the row seperator given the maximum size for each column.
/// </summary>
/// <param name="maxColumnSizes">The maximum size for each column.</param>
/// <returns>The row seperator.</returns>
private static String CreateRowSeperator(List<int> maxColumnSizes)
{
StringBuilder rowSeperator = new StringBuilder("+");
foreach (int maxColumnSize in maxColumnSizes)
{
for (int i = 0; i < maxColumnSize + 2; i++)
{
rowSeperator.Append("-");
}
rowSeperator.Append("+");
}
return rowSeperator.Append("\n").ToString();
}
/// <summary>
/// Gets a list of the maximum size for each column.
/// </summary>
/// <param name="resultSet">The result set to process.</param>
/// <returns>A list of the maximum size for each column.</returns>
private static List<int> GetMaxColumnSizes(List<string[]> resultSet)
{
List<int> maxColumnSizes = new List<int>();
for (int i = 0; i < resultSet[i].Length; i++)
{
int maxColumnSize = -1;
for (int j = 0; j < resultSet.Count; j++)
{
if (resultSet[j][i].Length > maxColumnSize)
{
maxColumnSize = resultSet[j][i].Length;
}
}
maxColumnSizes.Add(maxColumnSize);
}
return maxColumnSizes;
}
/// <summary>
/// Gets the column labels for the result set.
/// </summary>
/// <param name="resultSet">The result set to get the column labels for.
/// </param>
/// <returns>The string array of column labels.</returns>
public static String[] GetColumnLabels(ResultSet resultSet)
{
List<string> columnLabels = new List<string>();
foreach (ColumnType column in resultSet.columnTypes)
{
columnLabels.Add(column.labelName);
}
return columnLabels.ToArray();
}
/// <summary>
/// Gets the row values for a row of the result set in the form of an object
/// array.
/// </summary>
/// <param name="row">The row to get the values for.</param>
/// <returns>The object array of the row values.</returns>
public static object[] GetRowValues(Row row)
{
List<object> rowValues = new List<object>();
foreach (Value value in row.values)
{
rowValues.Add(GetValue(value));
}
return rowValues.ToArray();
}
/// <summary>
/// Gets the row values for a row of the result set in a the form of a string
/// array. <code>null</code> values are interperted as empty strings.
/// </summary>
/// <param name="row">The row to get the values for.</param>
/// <returns>The string array of the row values.</returns>
public static String[] GetRowStringValues(Row row)
{
object[] rowValues = GetRowValues(row);
List<string> rowStringValues = new List<string>();
foreach (object obj in rowValues)
{
rowStringValues.Add(GetTextValue(obj));
}
return rowStringValues.ToArray();
}
/// <summary>
/// Gets the text value of an unwrapped Value object.
/// </summary>
/// <param name="value">The unwrapped Value.</param>
/// <returns>A formatted text representation of the value.</returns>
/// <remarks>DateValue is formatted in yyyy-mm-dd format. DateTimeValue is
/// formatted in yyyy-mm-dd HH:mm:ss Z format.</remarks>
private static string GetTextValue(Object value)
{
if (value == null)
{
return "";
}
if (value is Google.Api.Ads.AdManager.v202105.Date)
{
Google.Api.Ads.AdManager.v202105.Date date =
(Google.Api.Ads.AdManager.v202105.Date) value;
return string.Format("{0:0000}-{1:00}-{2:00}", date.year, date.month, date.day);
}
else if (value is Google.Api.Ads.AdManager.v202105.DateTime)
{
Google.Api.Ads.AdManager.v202105.DateTime dateTime =
(Google.Api.Ads.AdManager.v202105.DateTime) value;
return string.Format("{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00} {6}",
dateTime.date.year, dateTime.date.month, dateTime.date.day, dateTime.hour,
dateTime.minute, dateTime.second, dateTime.timeZoneId);
}
else if (value is List<object>)
{
List<string> textValues = (value as List<object>)
.ConvertAll(new Converter<object, string>(GetTextValue))
.ConvertAll(new Converter<string, string>(EscapeCsv));
return String.Join<string>(",", textValues);
}
else
{
// NumberValue, BooleanValue, TextValue
return value.ToString();
}
}
private static string EscapeCsv(string value)
{
value = value.Replace("\"", "\"\"");
if (value.Contains(",") || value.Contains("\""))
{
value = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", value);
}
return value;
}
}
}
| |
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 StacksOfWax.SimpleApi.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.IO;
using System.Net;
using System.Collections.Generic;
namespace JinxNeuralNetwork
{
public class Utils {
//a few util functions used
/// <summary>
/// Compile NeuralNetwork into image-processing GLSL shader, only supports rectifier activation function and all layer sizes must be divisble by 3. Shader expects input in float3 array 'is'.
/// </summary>
/// <param name="nn"></param>
/// <returns></returns>
public static string AsShader(NeuralNetwork neuralNet)
{
int KERNEL_AREA = neuralNet.inputLayer.numberOfNeurons/3;
//save neural network as glsl shader
string shaderSrc = "";
for (int h = 0; h < neuralNet.hiddenLayers.Length+1; h++)
{
NeuralNetworkLayer layer;
NeuralNetworkLayerConnection connect;
int isize;
string ov,iv;
if (h == 0)
{
iv = "is";
isize = KERNEL_AREA;
}
else
{
iv = "hs" + (h - 1);
isize = neuralNet.hiddenLayers[h - 1].numberOfNeurons / 3;
}
if (h >= neuralNet.hiddenLayers.Length)
{
ov = "os";
layer = neuralNet.outputLayer;
connect = neuralNet.outputConnection;
}
else
{
ov = "hs"+h;
layer = neuralNet.hiddenLayers[h];
connect = neuralNet.hiddenConnections[h];
}
int osize = layer.numberOfNeurons/3;
shaderSrc += "vec3 "+ ov + "[" + osize + "];"+Environment.NewLine;
int weightIndex = 0,
k = osize;
while (k-- > 0)
{
shaderSrc += ov + "[" + k + "] = clamp(vec3(";
int c = 3;
while (c-- > 0)
{
shaderSrc += layer.biases[(k * 3 + 2) - c].ToString(".0######") + "+";
int w = isize;
while (w-- > 0)
{
shaderSrc += "dot(" + iv + "[" + w + "],vec3(" +
connect.weights[weightIndex+2].ToString(".0######") + "," +
connect.weights[weightIndex + 1].ToString(".0######") + "," +
connect.weights[weightIndex].ToString(".0######") + "))";
if (w != 0) shaderSrc += "+";
weightIndex += 3;
}
if (c != 0) shaderSrc += ",";
else shaderSrc += "),0.,1.);" + Environment.NewLine;
}
if (k == 0) shaderSrc += Environment.NewLine;
}
}
return shaderSrc;
}
/// <summary>
/// Compile forward+backward propagating NeuralNetwork into image-processing GLSL shader, only supports rectifier activation function and all layer sizes must be divisble by 3. Shader expects input in float3 array 'is' and target output as 'ts'.
/// </summary>
/// <param name="neuralNet"></param>
/// <returns></returns>
public static string GenerationAsShader(NeuralNetwork neuralNet)
{
int KERNEL_AREA = neuralNet.inputLayer.numberOfNeurons / 3;
//save neural network as glsl shader
string shaderSrc = "//forward propagation"+Environment.NewLine;
for (int h = 0; h < neuralNet.hiddenLayers.Length+1; h++)
{
NeuralNetworkLayer layer;
NeuralNetworkLayerConnection connect;
int isize;
string ov, iv;
if (h == 0)
{
iv = "is";
isize = KERNEL_AREA;
}
else
{
iv = "hs" + (h - 1);
isize = neuralNet.hiddenLayers[h - 1].numberOfNeurons / 3;
}
if (h >= neuralNet.hiddenLayers.Length)
{
ov = "os";
layer = neuralNet.outputLayer;
connect = neuralNet.outputConnection;
}
else
{
ov = "hs" + h;
layer = neuralNet.hiddenLayers[h];
connect = neuralNet.hiddenConnections[h];
}
int osize = layer.numberOfNeurons / 3;
shaderSrc += "vec3 " + ov + "[" + osize + "];" + Environment.NewLine;
int weightIndex = 0,
k = osize;
while (k-- > 0)
{
shaderSrc += ov + "[" + k + "] = clamp(vec3(";
int c = 3;
while (c-- > 0)
{
shaderSrc += layer.biases[(k * 3 + 2) - c].ToString(".0######") + "+";
int w = isize;
while (w-- > 0)
{
shaderSrc += "dot(" + iv + "[" + w + "],vec3(" +
connect.weights[weightIndex + 2].ToString(".0######") + "," +
connect.weights[weightIndex + 1].ToString(".0######") + "," +
connect.weights[weightIndex].ToString(".0######") + "))";
if (w != 0) shaderSrc += "+";
weightIndex += 3;
}
if (c != 0) shaderSrc += ",";
else shaderSrc += "),0.,1.);" + Environment.NewLine;
}
if (k == 0) shaderSrc += Environment.NewLine;
}
}
int nout = neuralNet.outputLayer.numberOfNeurons / 3;
shaderSrc += Environment.NewLine + "//target output difference/deriv" + Environment.NewLine +
"vec3 td[" + nout + "];" + Environment.NewLine;
for (int i = 0; i < nout; i++)
{
shaderSrc += "td[" + i + "] = os[" + i + "]-ts[" + i + "];" + Environment.NewLine;
}
shaderSrc += "//back propagation" + Environment.NewLine;
for (int h = neuralNet.hiddenLayers.Length; h > -1; h--)
{
NeuralNetworkLayer layer;
NeuralNetworkLayerConnection connect;
int isize,osize;
string ov, iv, dv;
if (h == 0)
{
iv = "is";
osize = KERNEL_AREA;
}
else
{
iv = "hs" + (h - 1);
osize = neuralNet.hiddenLayers[h - 1].numberOfNeurons / 3;
}
if (h >= neuralNet.hiddenLayers.Length)
{
dv = "td";
layer = neuralNet.outputLayer;
connect = neuralNet.outputConnection;
}
else
{
dv = "ds" + (h + 1);
layer = neuralNet.hiddenLayers[h];
connect = neuralNet.hiddenConnections[h];
}
ov = "ds"+h;
isize = layer.numberOfNeurons / 3;
shaderSrc += "vec3 " + ov + "[" + osize + "];" + Environment.NewLine;
int weightIndex = 0,
k = osize;
while (k-- > 0)
{
shaderSrc += ov + "[" + k + "] = (vec3(1.0,1.0,1.0)-"+iv+"["+k+"])*vec3(";
int c = 3;
while (c-- > 0)
{
int w = isize;
while (w-- > 0)
{
shaderSrc += "dot(" + dv + "[" + w + "],vec3(" +
connect.weights[weightIndex + 2].ToString(".0######") + "," +
connect.weights[weightIndex + 1].ToString(".0######") + "," +
connect.weights[weightIndex].ToString(".0######") + "))";
if (w != 0) shaderSrc += "+";
weightIndex += 3;
}
if (c != 0) shaderSrc += ",";
else shaderSrc += ");" + Environment.NewLine;
}
if (k == 0) shaderSrc += Environment.NewLine;
}
}
return shaderSrc;
}
/// <summary>
/// Compile NeuralNetwork into 1-4D shader function.
/// </summary>
/// <param name="nn"></param>
/// <returns></returns>
public static string AsShader(NeuralNetwork nn, string fname, bool glsl)
{
int channels = nn.outputLayer.numberOfNeurons;
if (channels < 1 || channels > 4) return null;//invalid, max 4 output
string chn = "";
switch (channels) {
case 1:
chn = "float";
break;
case 2:
chn = "vec2";
break;
case 3:
chn = "vec3";
break;
case 4:
chn = "vec4";
break;
}
int ichannels = nn.inputLayer.numberOfNeurons;
if (ichannels < 1 || ichannels > 4) return null;//invalid, max 4 input
string ichn = "";
switch (ichannels)
{
case 1:
ichn = "float";
break;
case 2:
ichn = "vec2";
break;
case 3:
ichn = "vec3";
break;
case 4:
ichn = "vec4";
break;
}
string[] inNames = new string[] {"uv.x","uv.y","uv.z","uv.w"};
string glslCode = chn+" "+fname+"("+ichn+" uv) {";
int lastNumNeurons = ichannels,
baseId = 0, lastId = 0, weightIndex;
int[] stateIds = new int[nn.hiddenLayers.Length>0?nn.hiddenLayers.Length-1:0];
for (int i = 0; i < nn.hiddenLayers.Length; i++) {
string activeFunc = GetActivationFunctionGLSLName(nn.hiddenLayers[i].activationFunction);
if (i != 0) {
if (i < nn.hiddenLayers.Length-1) stateIds[i] = baseId;
lastId = baseId - lastNumNeurons;
} else {
if (i < stateIds.Length) stateIds[i] = 0;
}
int k = nn.hiddenLayers[i].numberOfNeurons;
weightIndex = 0;
while (k-- > 0) {
glslCode += "float v" + (baseId+k) + " = " + activeFunc + "(" + nn.hiddenLayers[i].biases[k].ToString(".0######")+"+";
if (i == 0) {
//input -> hidden
int j = lastNumNeurons;
while (j-- > 0)
{
glslCode += inNames[j] + "*" + nn.hiddenConnections[i].weights[weightIndex++].ToString(".0######") + (j == 0 ? "" : "+");
}
glslCode += ");";
} else {
//hidden -> hidden
int j = lastNumNeurons;
while (j-- > 0)
{
glslCode += "v" + (lastId + j) + "*" + nn.hiddenConnections[i].weights[weightIndex++].ToString(".0######") + (j == 0 ? "" : "+");
}
glslCode += ");";
}
}
lastNumNeurons = nn.hiddenLayers[i].numberOfNeurons;
baseId += lastNumNeurons;
}
//hidden/input->output
lastId = baseId - lastNumNeurons;
string oactiveFunc = GetActivationFunctionGLSLName(nn.outputLayer.activationFunction);
string[] ocs = new string[channels];
int c = channels;
weightIndex = 0;
while (c-- > 0)
{
string ostr = oactiveFunc + "(" + nn.outputLayer.biases[c].ToString(".0######") + "+";
if (nn.hiddenLayers.Length == 0)
{
int j = ichannels;
while (j-- > 0)
{
ostr += inNames[j] + "*" + nn.outputConnection.weights[weightIndex++].ToString(".0######") + ((j == 0) ? "" : "+");
}
}
else
{
int j = lastNumNeurons;
while (j-- > 0)
{
ostr += "v" + (lastId + j) + "*" + nn.outputConnection.weights[weightIndex++].ToString(".0######") + ((j == 0) ? "" : "+");
}
}
ocs[c] = ostr+")";
}
//prepare return statement and end of function
if (channels == 1)
{
glslCode += "return " + ocs[0] + ";}";
}
else
{
glslCode += "return " + chn + "(";
for (int i = 0; i < channels; i++)
{
glslCode += (i==0?"":",")+ocs[i];
}
glslCode += ");}";
}
if (!glsl) return glslCode.Replace("vec", "float");
return glslCode;
}
//sample 1d function points and return array of points
/// <summary>
/// Sample 1D function from xMin to xMax building array of 2D points.
/// </summary>
/// <param name="numSamples"></param>
/// <param name="func"></param>
/// <param name="xMin"></param>
/// <param name="xMax"></param>
/// <returns>Array of 2D points.</returns>
public static float[][] SampleFunction(int numSamples, NeuralNetwork.NeuronActivationFunction func, float xMin, float xMax)
{
float[][] res = new float[numSamples][];
for (int i = 0; i < numSamples; i++)
{
float sx = (i / (float)(numSamples - 1)) * (xMax - xMin) + xMin;
res[i] = new float[] {
sx,
func(sx)
};
}
return res;
}
/// <summary>
/// Sample 1D neural network from xMin to xMax building array of 2D points.
/// </summary>
/// <param name="numSamples"></param>
/// <param name="nn"></param>
/// <param name="xMin"></param>
/// <param name="xMax"></param>
/// <returns></returns>
public static float[][] SampleNeuralNetwork(int numSamples, NeuralNetwork nn, float xMin, float xMax)
{
NeuralNetworkProgram nnp = new NeuralNetworkProgram(nn);
nnp.context.Reset(true);
float[][] res = new float[numSamples][];
for (int i = 0; i < numSamples; i++)
{
float sx = (i / (float)(numSamples - 1)) * (xMax - xMin) + xMin;
nnp.context.inputData[0] = sx;
nnp.Execute();
res[i] = new float[] {
sx,
nnp.context.outputData[0]
};
}
return res;
}
/// <summary>
/// Get default activation function name from function.
/// </summary>
/// <param name="activeFunc"></param>
/// <returns>Name of activation function.</returns>
public static string GetActivationFunctionName(NeuralNetwork.NeuronActivationFunction activeFunc)
{
if (activeFunc == Identity_ActivationFunction) return "identity";
if (activeFunc == Rectifier_ActivationFunction) return "rectifier";
if (activeFunc == Sin_ActivationFunction) return "sin";
if (activeFunc == Cos_ActivationFunction) return "cos";
if (activeFunc == Tan_ActivationFunction) return "tan";
if (activeFunc == Tanh_ActivationFunction) return "tanh";
if (activeFunc == Sinh_ActivationFunction) return "sinh";
if (activeFunc == Exp_ActivationFunction) return "exp";
if (activeFunc == Sigmoid_ActivationFunction) return "sigmoid";
if (activeFunc == Sqrt_ActivationFunction) return "sqrt";
if (activeFunc == Pow2_ActivationFunction) return "pow2";
return "unknown";
}
public static string GetActivationFunctionGLSLName(NeuralNetwork.NeuronActivationFunction activeFunc)
{
if (activeFunc == Identity_ActivationFunction) return "";
if (activeFunc == Rectifier_ActivationFunction) return "rectifier";
if (activeFunc == Sin_ActivationFunction) return "sin";
if (activeFunc == Cos_ActivationFunction) return "cos";
if (activeFunc == Tan_ActivationFunction) return "tan";
if (activeFunc == Tanh_ActivationFunction) return "tanh";
if (activeFunc == Sinh_ActivationFunction) return "sinh";
if (activeFunc == Exp_ActivationFunction) return "exp";
if (activeFunc == Sigmoid_ActivationFunction) return "sigmoid";
if (activeFunc == Sqrt_ActivationFunction) return "sqrt";
if (activeFunc == Pow2_ActivationFunction) return "pow2";
return "";
}
public static int GetActivationFunctionID(NeuralNetwork.NeuronActivationFunction activeFunc)
{
if (activeFunc == Identity_ActivationFunction) return 0;
if (activeFunc == Rectifier_ActivationFunction) return 1;
if (activeFunc == Sin_ActivationFunction) return 2;
if (activeFunc == Cos_ActivationFunction) return 3;
if (activeFunc == Tan_ActivationFunction) return 4;
if (activeFunc == Tanh_ActivationFunction) return 5;
if (activeFunc == Sinh_ActivationFunction) return 6;
if (activeFunc == Exp_ActivationFunction) return 7;
if (activeFunc == Sigmoid_ActivationFunction) return 8;
if (activeFunc == Sqrt_ActivationFunction) return 9;
if (activeFunc == Pow2_ActivationFunction) return 10;
return -1;
}
public static NeuralNetwork.NeuronActivationFunction GetActivationFunctionFromID(int i)
{
switch (i)
{
case 0: return Identity_ActivationFunction;
case 1: return Rectifier_ActivationFunction;
case 2: return Sin_ActivationFunction;
case 3: return Cos_ActivationFunction;
case 4: return Tan_ActivationFunction;
case 5: return Tanh_ActivationFunction;
case 6: return Sinh_ActivationFunction;
case 7: return Exp_ActivationFunction;
case 8: return Sigmoid_ActivationFunction;
case 9: return Sqrt_ActivationFunction;
case 10: return Pow2_ActivationFunction;
}
return Identity_ActivationFunction;
}
//premade activation functions
/// <summary>
/// Identity(no activation function), linear.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Identity_ActivationFunction(float v)
{
return v;
}
/// <summary>
/// Rectifier activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Rectifier_ActivationFunction(float v)
{
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Unclamped exp activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Exp_ActivationFunction(float v)
{
v = (float)Math.Exp(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
return v;
}
/// <summary>
/// Sigmoid activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Sigmoid_ActivationFunction(float v)
{
v = 1.0f / (1.0f + (float)Math.Exp(-v));
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Sin activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Sin_ActivationFunction(float v)
{
v = (float)Math.Sin(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Cos activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Cos_ActivationFunction(float v)
{
v = (float)Math.Cos(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Tan activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Tan_ActivationFunction(float v)
{
v = (float)Math.Tan(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Tanh activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Tanh_ActivationFunction(float v)
{
v = (float)Math.Tanh(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Sinh activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Sinh_ActivationFunction(float v)
{
v = (float)Math.Sinh(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Sqrt activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Sqrt_ActivationFunction(float v)
{
v = (float)Math.Sqrt(v);
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
/// <summary>
/// Pow2 activation function.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float Pow2_ActivationFunction(float v)
{
v = v * v;
#pragma warning disable 414,1718
if (v != v) return 0.0f;
#pragma warning restore 1718
if (v < 0.0f) return 0.0f;
if (v > 1.0f) return 1.0f;
return v;
}
private static Random random = new Random();
/// <summary>
/// Random float(0-1), not thread safe.
/// </summary>
/// <returns>Random float(0-1).</returns>
public static float NextFloat01()
{
return (float)random.NextDouble();
}
/// <summary>
/// Random int between min and max, not thread safe.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static int NextInt(int min, int max)
{
return random.Next(max - min) + min;
}
public static void IntToStream(int i, Stream s)
{
s.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(i)), 0, 4);
}
public static int IntFromStream(Stream s)
{
byte[] b = new byte[4];
s.Read(b, 0, 4);
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(b, 0));
}
//convert int and float to bytes and big endian
/// <summary>
/// Convert int to bytes.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public static byte[] IntToBytes(int i)
{
return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(i));
}
/// <summary>
/// Convert array of bytes to int.
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public static int IntFromBytes(byte[] b)
{
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(b, 0));
}
/// <summary>
/// Convert array of bytes to int.
/// </summary>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
public static int IntFromBytes(byte[] b, int index)
{
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(b, index));
}
/// <summary>
/// Convert float to bytes.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static byte[] FloatToBytes(float f)
{
byte[] b = BitConverter.GetBytes(f);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(b);
}
return b;
}
public static void FloatToStream(float f, Stream s)
{
byte[] b = BitConverter.GetBytes(f);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(b);
}
s.Write(b, 0, 4);
}
/// <summary>
/// Convert array of bytes to float.
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public static float FloatFromBytes(byte[] b)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(b, 0, 4);
}
return BitConverter.ToSingle(b, 0);
}
/// <summary>
/// Convert array of bytes to float.
/// </summary>
/// <param name="b"></param>
/// <param name="index"></param>
/// <returns></returns>
public static float FloatFromBytes(byte[] b, int index)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(b, index, 4);
}
return BitConverter.ToSingle(b, index);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <param name="s">S.</param>
public static float FloatFromStream(Stream s)
{
byte[] b = new byte[4];
s.Read(b, 0, 4);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(b, 0, 4);
}
return BitConverter.ToSingle(b, 0);
}
/// <summary>
///
/// </summary>
/// <param name="f"></param>
/// <param name="s"></param>
public static void FloatArrayToStream(float[] f, Stream s)
{
IntToStream(f.Length, s);
int k = f.Length;
while (k-- > 0)
{
FloatToStream(f[k], s);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <param name="s"></param>
public static float[] FloatArrayFromStream(Stream s)
{
float[] f = new float[IntFromStream(s)];
int k = f.Length;
while (k-- > 0)
{
f[k] = FloatFromStream(s);
}
return f;
}
/// <summary>
///
/// </summary>
/// <param name="f"></param>
/// <param name="s"></param>
public static void FloatArrayFromStream(float[] f, Stream s)
{
int k = f.Length;
while (k-- > 0)
{
f[k] = FloatFromStream(s);
}
}
/// <summary>
/// Lerp from a to b over t.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="t"></param>
/// <returns></returns>
public static float Lerp(float a, float b, float t)
{
return a + (b - a) * t;
}
//fill float array with single value
/// <summary>
/// Fill float array with single value.
/// </summary>
/// <param name="f"></param>
/// <param name="v"></param>
public static void Fill(float[] f, float v)
{
int i = f.Length;
while (i-- > 0)
{
f[i] = v;
}
}
public static void Multiply(float[] f, float v)
{
int i = f.Length;
while (i-- > 0)
{
f[i] *= v;
}
}
//find largest value from array of values and return index
/// <summary>
/// Returns index of largest value in array.
/// </summary>
/// <param name="f"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns>Index of largest value.</returns>
public static int Largest(float[] f, int start, int end)
{
int k = end,
i = end - 1;
float l = float.MinValue;
while (k-- > start)
{
if (f[k] > l)
{
l = f[k];
i = k;
}
}
return i;
}
/// <summary>
/// Random int from array of probabilities.
/// </summary>
/// <param name="p"></param>
/// <returns>Index of selected probability.</returns>
public static int RandomChoice(float[] p)
{
float rand = NextFloat01(),
sum = 0.0f;
for (int i = 0; i < p.Length; i++)
{
float prob = p[i],
nsum = sum + prob;
if (rand >= sum && rand <= nsum)
{
return i;
}
sum = nsum;
}
return p.Length - 1;
}
/// <summary>
/// Normalize vector.
/// </summary>
/// <param name="f"></param>
public static void Normalize(float[] f)
{
float sum = 0.0f;
int i = f.Length;
while (i-- > 0)
{
sum += f[i];
}
if (sum > 0.0f)
{
i = f.Length;
while (i-- > 0)
{
f[i] /= sum;
}
}
}
/// <summary>
/// Puts probabilities to power of pow and re-normalizes.
/// </summary>
/// <param name="p"></param>
/// <param name="pow"></param>
public static void ProbabilityPower(float[] p, float pow)
{
float sum = 0.0f;
int i = p.Length;
while (i-- > 0)
{
p[i] = (float)Math.Pow(p[i], pow);
sum += p[i];
}
i = p.Length;
while (i-- > 0)
{
p[i] /= sum;
}
}
/// <summary>
/// Encode multiple strings into one-hot encoding and outputs dictionary of used characters.
/// </summary>
/// <param name="txt"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static float[][][] EncodeStringOneHot(string[] atxt, out List<char> dict)
{
dict = new List<char>();
for (int a = 0; a < atxt.Length; a++)
{
string txt = atxt[a];
for (int i = 0; i < txt.Length; i++)
{
if (!dict.Contains(txt[i]))
{
dict.Add(txt[i]);
}
}
}
float[][][] output = new float[atxt.Length][][];
for (int a = 0; a < atxt.Length; a++)
{
string txt = atxt[a];
output[a] = new float[txt.Length][];
for (int i = 0; i < txt.Length; i++)
{
output[a][i] = new float[dict.Count];
Fill(output[a][i], 0.0f);
output[a][i][dict.IndexOf(txt[i])] = 1.0f;
}
}
return output;
}
/// <summary>
/// Encode string into one-hot encoding and outputs dictionary of used characters.
/// </summary>
/// <param name="txt"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static float[][] EncodeStringOneHot(string txt, out List<char> dict)
{
dict = new List<char>();
for (int i = 0; i < txt.Length; i++)
{
if (!dict.Contains(txt[i]))
{
dict.Add(txt[i]);
}
}
float[][] output = new float[txt.Length][];
for (int i = 0; i < txt.Length; i++)
{
output[i] = new float[dict.Count];
Fill(output[i], 0.0f);
output[i][dict.IndexOf(txt[i])] = 1.0f;
}
return output;
}
/// <summary>
/// Decode one-hot encoded string using dictionary.
/// </summary>
/// <param name="txt"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static string DecodeStringOneHot(float[][] txt, List<char> dict)
{
string decoded = "";
for (int i = 0; i < txt.Length; i++)
{
decoded += dict[Largest(txt[i], 0, txt[i].Length)];
}
return decoded;
}
/// <summary>
/// Shuffle array.
/// </summary>
/// <param name="a"></param>
public static void Shuffle(Array a)
{
int l = a.Length,
i = l;
while (i-- > 0)
{
int r = NextInt(0,l),
w = NextInt(0,l);
object temp = a.GetValue(w);
a.SetValue(a.GetValue(r), w);
a.SetValue(temp, r);
}
}
public static void Shuffle(Array a, Array b)
{
int l = a.Length,
i = l;
while (i-- > 0)
{
int r = NextInt(0, l),
w = NextInt(0, l);
object temp = a.GetValue(w);
a.SetValue(a.GetValue(r), w);
a.SetValue(temp, r);
temp = b.GetValue(w);
b.SetValue(b.GetValue(r), w);
b.SetValue(temp, r);
}
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
/*
Note on transaction support:
Eventually we will want to add support for NT's transactions to our
RegistryKey API's. When we do this, here's
the list of API's we need to make transaction-aware:
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKeyEx
RegEnumValue
RegOpenKeyEx
RegQueryInfoKey
RegQueryValueEx
RegSetValueEx
We can ignore RegConnectRegistry (remote registry access doesn't yet have
transaction support) and RegFlushKey. RegCloseKey doesn't require any
additional work.
*/
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
registry key, then the ACL only gets checked when you construct handles to
them. So if you set an ACL to deny read access to yourself, you'll still be
able to read with that handle, but not with new handles.
Another peculiarity is a Terminal Server app compatibility hack. The OS
will second guess your attempt to open a handle sometimes. If a certain
combination of Terminal Server app compat registry keys are set, then the
OS will try to reopen your handle with lesser permissions if you couldn't
open it in the specified mode. So on some machines, we will see handles that
may not be able to read or write to a registry key. It's very strange. But
the real test of these handles is attempting to read or set a value in an
affected registry key.
For reference, at least two registry keys must be set to particular values
for this behavior:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
There might possibly be an interaction with yet a third registry key as well.
*/
namespace Microsoft.Win32
{
#if REGISTRY_ASSEMBLY
public
#else
internal
#endif
sealed partial class RegistryKey : IDisposable
{
private void ClosePerfDataKey()
{
// System keys should never be closed. However, we want to call RegCloseKey
// on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
// (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
// to be refreshed (by re-reading the registry) when accessed subsequently.
// This is the only way we can see the just installed perf counter.
// NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race in closing
// the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
// in this situation the down level OSes are not. We have a small window of race between
// the dispose below and usage elsewhere (other threads). This is By Design.
// This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
// (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
Interop.mincore.RegCloseKey(HKEY_PERFORMANCE_DATA);
}
private void FlushCore()
{
if (_hkey != null && IsDirty())
{
Interop.mincore.RegFlushKey(_hkey);
}
}
private unsafe RegistryKey CreateSubKeyInternalCore(string subkey, bool writable, RegistryOptions registryOptions)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
int disposition = 0;
// By default, the new key will be writable.
SafeRegistryHandle result = null;
int ret = Interop.mincore.RegCreateKeyEx(_hkey,
subkey,
0,
null,
(int)registryOptions /* specifies if the key is volatile */,
(int)GetRegistryKeyRights(writable) | (int)_regView,
ref secAttrs,
out result,
out disposition);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, _remoteKey, false, _regView);
if (subkey.Length == 0)
{
key._keyName = _keyName;
}
else
{
key._keyName = _keyName + "\\" + subkey;
}
return key;
}
else if (ret != 0) // syscall failed, ret is an error code.
{
Win32Error(ret, _keyName + "\\" + subkey); // Access denied?
}
Debug.Fail("Unexpected code path in RegistryKey::CreateSubKey");
return null;
}
private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey)
{
int ret = Interop.mincore.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
if (ret != 0)
{
if (ret == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
if (throwOnMissingSubKey)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent);
}
}
else
{
Win32Error(ret, null);
}
}
}
private void DeleteSubKeyTreeCore(string subkey)
{
int ret = Interop.mincore.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
if (ret != 0)
{
Win32Error(ret, null);
}
}
private void DeleteValueCore(string name, bool throwOnMissingValue)
{
int errorCode = Interop.mincore.RegDeleteValue(_hkey, name);
//
// From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND ||
errorCode == Interop.mincore.Errors.ERROR_FILENAME_EXCED_RANGE)
{
if (throwOnMissingValue)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyValueAbsent);
}
else
{
// Otherwise, reset and just return giving no indication to the user.
// (For compatibility)
errorCode = 0;
}
}
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/// <summary>
/// Retrieves a new RegistryKey that represents the requested key. Valid
/// values are:
/// HKEY_CLASSES_ROOT,
/// HKEY_CURRENT_USER,
/// HKEY_LOCAL_MACHINE,
/// HKEY_USERS,
/// HKEY_PERFORMANCE_DATA,
/// HKEY_CURRENT_CONFIG.
/// </summary>
/// <param name="hKeyHive">HKEY_* to open.</param>
/// <returns>The RegistryKey requested.</returns>
private static RegistryKey OpenBaseKeyCore(RegistryHive hKeyHive, RegistryView view)
{
IntPtr hKey = (IntPtr)((int)hKeyHive);
int index = ((int)hKey) & 0x0FFFFFFF;
Debug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!");
Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
// only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key._keyName = s_hkeyNames[index];
return key;
}
private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view)
{
int index = (int)hKey & 0x0FFFFFFF;
if (index < 0 || index >= s_hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000)
{
throw new ArgumentException(SR.Arg_RegKeyOutOfRange);
}
// connect to the specified remote registry
SafeRegistryHandle foreignHKey = null;
int ret = Interop.mincore.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out foreignHKey);
if (ret == Interop.mincore.Errors.ERROR_DLL_INIT_FAILED)
{
// return value indicates an error occurred
throw new ArgumentException(SR.Arg_DllInitFailure);
}
if (ret != 0)
{
Win32ErrorStatic(ret, null);
}
if (foreignHKey.IsInvalid)
{
// return value indicates an error occurred
throw new ArgumentException(SR.Format(SR.Arg_RegKeyNoRemoteConnect, machineName));
}
RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr)hKey) == HKEY_PERFORMANCE_DATA, view);
key._keyName = s_hkeyNames[index];
return key;
}
private RegistryKey InternalOpenSubKeyCore(string name, RegistryRights rights, bool throwOnPermissionFailure)
{
SafeRegistryHandle result = null;
int ret = Interop.mincore.RegOpenKeyEx(_hkey, name, 0, ((int)rights | (int)_regView), out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, IsWritable((int)rights), false, _remoteKey, false, _regView);
key._keyName = _keyName + "\\" + name;
return key;
}
if (throwOnPermissionFailure)
{
if (ret == Interop.mincore.Errors.ERROR_ACCESS_DENIED || ret == Interop.mincore.Errors.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reason,
// although UnauthorizedAccessException will make more sense.
ThrowHelper.ThrowSecurityException(SR.Security_RegistryPermission);
}
}
// Return null if we didn't find the key.
return null;
}
private SafeRegistryHandle SystemKeyHandle
{
get
{
Debug.Assert(IsSystemKey());
int ret = Interop.mincore.Errors.ERROR_INVALID_HANDLE;
IntPtr baseKey = (IntPtr)0;
switch (_keyName)
{
case "HKEY_CLASSES_ROOT":
baseKey = HKEY_CLASSES_ROOT;
break;
case "HKEY_CURRENT_USER":
baseKey = HKEY_CURRENT_USER;
break;
case "HKEY_LOCAL_MACHINE":
baseKey = HKEY_LOCAL_MACHINE;
break;
case "HKEY_USERS":
baseKey = HKEY_USERS;
break;
case "HKEY_PERFORMANCE_DATA":
baseKey = HKEY_PERFORMANCE_DATA;
break;
case "HKEY_CURRENT_CONFIG":
baseKey = HKEY_CURRENT_CONFIG;
break;
default:
Win32Error(ret, null);
break;
}
// open the base key so that RegistryKey.Handle will return a valid handle
SafeRegistryHandle result;
ret = Interop.mincore.RegOpenKeyEx(baseKey,
null,
0,
(int)GetRegistryKeyRights(IsWritable()) | (int)_regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
return result;
}
else
{
Win32Error(ret, null);
throw new IOException(Interop.mincore.GetMessage(ret), ret);
}
}
}
private int InternalSubKeyCountCore()
{
int subkeys = 0;
int junk = 0;
int ret = Interop.mincore.RegQueryInfoKey(_hkey,
null,
null,
IntPtr.Zero,
ref subkeys, // subkeys
null,
null,
ref junk, // values
null,
null,
null,
null);
if (ret != 0)
{
Win32Error(ret, null);
}
return subkeys;
}
private unsafe string[] InternalGetSubKeyNamesCore(int subkeys)
{
string[] names = new string[subkeys];
char[] name = new char[MaxKeyLength + 1];
int namelen;
fixed (char* namePtr = &name[0])
{
for (int i = 0; i < subkeys; i++)
{
namelen = name.Length; // Don't remove this. The API's doesn't work if this is not properly initialized.
int ret = Interop.mincore.RegEnumKeyEx(_hkey,
i,
namePtr,
ref namelen,
null,
null,
null,
null);
if (ret != 0)
{
Win32Error(ret, null);
}
names[i] = new string(namePtr);
}
}
return names;
}
private int InternalValueCountCore()
{
int values = 0;
int junk = 0;
int ret = Interop.mincore.RegQueryInfoKey(_hkey,
null,
null,
IntPtr.Zero,
ref junk, // subkeys
null,
null,
ref values, // values
null,
null,
null,
null);
if (ret != 0)
{
Win32Error(ret, null);
}
return values;
}
/// <summary>Retrieves an array of strings containing all the value names.</summary>
/// <returns>All value names.</returns>
private unsafe string[] GetValueNamesCore(int values)
{
string[] names = new string[values];
char[] name = new char[MaxValueLength + 1];
int namelen;
fixed (char* namePtr = &name[0])
{
for (int i = 0; i < values; i++)
{
namelen = name.Length;
int ret = Interop.mincore.RegEnumValue(_hkey,
i,
namePtr,
ref namelen,
IntPtr.Zero,
null,
null,
null);
if (ret != 0)
{
// ignore ERROR_MORE_DATA if we're querying HKEY_PERFORMANCE_DATA
if (!(IsPerfDataKey() && ret == Interop.mincore.Errors.ERROR_MORE_DATA))
Win32Error(ret, null);
}
names[i] = new string(namePtr);
}
}
return names;
}
private object InternalGetValueCore(string name, object defaultValue, bool doNotExpand)
{
object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
if (IsPerfDataKey())
{
int size = 65000;
int sizeInput = size;
int r;
byte[] blob = new byte[size];
while (Interop.mincore.Errors.ERROR_MORE_DATA == (r = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput)))
{
if (size == Int32.MaxValue)
{
// ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
Win32Error(r, name);
}
else if (size > (Int32.MaxValue / 2))
{
// at this point in the loop "size * 2" would cause an overflow
size = Int32.MaxValue;
}
else
{
size *= 2;
}
sizeInput = size;
blob = new byte[size];
}
if (r != 0)
{
Win32Error(r, name);
}
return blob;
}
else
{
// For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
// Some OS's returned ERROR_MORE_DATA even in success cases, so we
// want to continue on through the function.
if (ret != Interop.mincore.Errors.ERROR_MORE_DATA)
{
return data;
}
}
}
if (datasize < 0)
{
// unexpected code path
Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
switch (type)
{
case Interop.mincore.RegistryValues.REG_NONE:
case Interop.mincore.RegistryValues.REG_DWORD_BIG_ENDIAN:
case Interop.mincore.RegistryValues.REG_BINARY:
{
byte[] blob = new byte[datasize];
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_QWORD:
{ // also REG_QWORD_LITTLE_ENDIAN
if (datasize > 8)
{
// prevent an AV in the edge case that datasize is larger than sizeof(long)
goto case Interop.mincore.RegistryValues.REG_BINARY;
}
long blob = 0;
Debug.Assert(datasize == 8, "datasize==8");
// Here, datasize must be 8 when calling this
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_DWORD:
{ // also REG_DWORD_LITTLE_ENDIAN
if (datasize > 4)
{
// prevent an AV in the edge case that datasize is larger than sizeof(int)
goto case Interop.mincore.RegistryValues.REG_QWORD;
}
int blob = 0;
Debug.Assert(datasize == 4, "datasize==4");
// Here, datasize must be four when calling this
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new string(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new string(blob);
}
}
break;
case Interop.mincore.RegistryValues.REG_EXPAND_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new string(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new string(blob);
}
if (!doNotExpand)
{
data = Environment.ExpandEnvironmentVariables((string)data);
}
}
break;
case Interop.mincore.RegistryValues.REG_MULTI_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
// make sure the string is null terminated before processing the data
if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
Array.Resize(ref blob, blob.Length + 1);
}
string[] strings = Array.Empty<string>();
int stringsCount = 0;
int cur = 0;
int len = blob.Length;
while (ret == 0 && cur < len)
{
int nextNull = cur;
while (nextNull < len && blob[nextNull] != (char)0)
{
nextNull++;
}
string toAdd = null;
if (nextNull < len)
{
Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
if (nextNull - cur > 0)
{
toAdd = new string(blob, cur, nextNull - cur);
}
else
{
// we found an empty string. But if we're at the end of the data,
// it's just the extra null terminator.
if (nextNull != len - 1)
{
toAdd = string.Empty;
}
}
}
else
{
toAdd = new string(blob, cur, len - cur);
}
cur = nextNull + 1;
if (toAdd != null)
{
if (strings.Length == stringsCount)
{
Array.Resize(ref strings, stringsCount > 0 ? stringsCount * 2 : 4);
}
strings[stringsCount++] = toAdd;
}
}
Array.Resize(ref strings, stringsCount);
data = strings;
}
break;
case Interop.mincore.RegistryValues.REG_LINK:
default:
break;
}
return data;
}
private RegistryValueKind GetValueKindCore(string name)
{
int type = 0;
int datasize = 0;
int ret = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
Win32Error(ret, null);
}
return
type == Interop.mincore.RegistryValues.REG_NONE ? RegistryValueKind.None :
!Enum.IsDefined(typeof(RegistryValueKind), type) ? RegistryValueKind.Unknown :
(RegistryValueKind)type;
}
private unsafe void SetValueCore(string name, object value, RegistryValueKind valueKind)
{
int ret = 0;
try
{
switch (valueKind)
{
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
string data = value.ToString();
ret = Interop.mincore.RegSetValueEx(_hkey,
name,
0,
valueKind,
data,
checked(data.Length * 2 + 2));
break;
}
case RegistryValueKind.MultiString:
{
// Other thread might modify the input array after we calculate the buffer length.
// Make a copy of the input array to be safe.
string[] dataStrings = (string[])(((string[])value).Clone());
// First determine the size of the array
//
// Format is null terminator between strings and final null terminator at the end.
// e.g. str1\0str2\0str3\0\0
//
int sizeInChars = 1; // no matter what, we have the final null terminator.
for (int i = 0; i < dataStrings.Length; i++)
{
if (dataStrings[i] == null)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetStrArrNull);
}
sizeInChars = checked(sizeInChars + (dataStrings[i].Length + 1));
}
int sizeInBytes = checked(sizeInChars * sizeof(char));
// Write out the strings...
//
char[] dataChars = new char[sizeInChars];
int destinationIndex = 0;
for (int i = 0; i < dataStrings.Length; i++)
{
int length = dataStrings[i].Length;
dataStrings[i].CopyTo(0, dataChars, destinationIndex, length);
destinationIndex += (length + 1); // +1 for null terminator, which is already zero-initialized in new array.
}
ret = Interop.mincore.RegSetValueEx(_hkey,
name,
0,
RegistryValueKind.MultiString,
dataChars,
sizeInBytes);
break;
}
case RegistryValueKind.None:
case RegistryValueKind.Binary:
byte[] dataBytes = (byte[])value;
ret = Interop.mincore.RegSetValueEx(_hkey,
name,
0,
(valueKind == RegistryValueKind.None ? Interop.mincore.RegistryValues.REG_NONE : RegistryValueKind.Binary),
dataBytes,
dataBytes.Length);
break;
case RegistryValueKind.DWord:
{
// We need to use Convert here because we could have a boxed type cannot be
// unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.mincore.RegSetValueEx(_hkey,
name,
0,
RegistryValueKind.DWord,
ref data,
4);
break;
}
case RegistryValueKind.QWord:
{
long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.mincore.RegSetValueEx(_hkey,
name,
0,
RegistryValueKind.QWord,
ref data,
8);
break;
}
}
}
catch (Exception exc) when (exc is OverflowException || exc is InvalidOperationException || exc is FormatException || exc is InvalidCastException)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
}
if (ret == 0)
{
SetDirty();
}
else
{
Win32Error(ret, null);
}
}
/// <summary>
/// After calling GetLastWin32Error(), it clears the last error field,
/// so you must save the HResult and pass it to this method. This method
/// will determine the appropriate exception to throw dependent on your
/// error, and depending on the error, insert a string into the message
/// gotten from the ResourceManager.
/// </summary>
private void Win32Error(int errorCode, string str)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_ACCESS_DENIED:
throw str != null ?
new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) :
new UnauthorizedAccessException();
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
// For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
// However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
// SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
// in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
// on reentrant calls because of this error code path in RegistryKey
//
// Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
// however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
// this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
// having serialized access).
if (!IsPerfDataKey())
{
_hkey.SetHandleAsInvalid();
_hkey = null;
}
goto default;
case Interop.mincore.Errors.ERROR_FILE_NOT_FOUND:
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Interop.mincore.GetMessage(errorCode), errorCode);
}
}
private static void Win32ErrorStatic(int errorCode, string str)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_ACCESS_DENIED:
throw str != null ?
new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) :
new UnauthorizedAccessException();
default:
throw new IOException(Interop.mincore.GetMessage(errorCode), errorCode);
}
}
private static bool IsWritable(int rights)
{
return (rights & (Interop.mincore.RegistryOperations.KEY_SET_VALUE |
Interop.mincore.RegistryOperations.KEY_CREATE_SUB_KEY |
(int)RegistryRights.Delete |
(int)RegistryRights.TakeOwnership |
(int)RegistryRights.ChangePermissions)) != 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SecurityRulesOperations.
/// </summary>
public static partial class SecurityRulesOperationsExtensions
{
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void Delete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
operations.DeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static SecurityRule Get(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
return operations.GetAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> GetAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
public static SecurityRule CreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> CreateOrUpdateAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static IPage<SecurityRule> List(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
return operations.ListAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void BeginDelete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
public static SecurityRule BeginCreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> BeginCreateOrUpdateAsync(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SecurityRule> ListNext(this ISecurityRulesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListNextAsync(this ISecurityRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text.Json
{
public sealed partial class Utf8JsonWriter
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidatePropertyNameAndDepth(ReadOnlySpan<char> propertyName)
{
if (propertyName.Length > JsonConstants.MaxCharacterTokenSize || CurrentDepth >= JsonConstants.MaxWriterDepth)
ThrowHelper.ThrowInvalidOperationOrArgumentException(propertyName, _currentDepth);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidatePropertyNameAndDepth(ReadOnlySpan<byte> utf8PropertyName)
{
if (utf8PropertyName.Length > JsonConstants.MaxUnescapedTokenSize || CurrentDepth >= JsonConstants.MaxWriterDepth)
ThrowHelper.ThrowInvalidOperationOrArgumentException(utf8PropertyName, _currentDepth);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateDepth()
{
if (CurrentDepth >= JsonConstants.MaxWriterDepth)
ThrowHelper.ThrowInvalidOperationException(_currentDepth);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateWritingProperty()
{
if (!_options.SkipValidation)
{
if (!_inObject || _tokenType == JsonTokenType.PropertyName)
{
Debug.Assert(_tokenType != JsonTokenType.StartObject);
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, currentDepth: default, token: default, _tokenType);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateWritingProperty(byte token)
{
if (!_options.SkipValidation)
{
if (!_inObject || _tokenType == JsonTokenType.PropertyName)
{
Debug.Assert(_tokenType != JsonTokenType.StartObject);
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotWritePropertyWithinArray, currentDepth: default, token: default, _tokenType);
}
UpdateBitStackOnStart(token);
}
}
private void WritePropertyNameMinimized(ReadOnlySpan<byte> escapedPropertyName, byte token)
{
Debug.Assert(escapedPropertyName.Length < int.MaxValue - 5);
int minRequired = escapedPropertyName.Length + 4; // 2 quotes, 1 colon, and 1 start token
int maxRequired = minRequired + 1; // Optionally, 1 list separator
if (_memory.Length - BytesPending < maxRequired)
{
Grow(maxRequired);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
output[BytesPending++] = JsonConstants.Quote;
escapedPropertyName.CopyTo(output.Slice(BytesPending));
BytesPending += escapedPropertyName.Length;
output[BytesPending++] = JsonConstants.Quote;
output[BytesPending++] = JsonConstants.KeyValueSeperator;
output[BytesPending++] = token;
}
private void WritePropertyNameIndented(ReadOnlySpan<byte> escapedPropertyName, byte token)
{
int indent = Indentation;
Debug.Assert(indent <= 2 * JsonConstants.MaxWriterDepth);
Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - 6 - s_newLineLength);
int minRequired = indent + escapedPropertyName.Length + 5; // 2 quotes, 1 colon, 1 space, and 1 start token
int maxRequired = minRequired + 1 + s_newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line
if (_memory.Length - BytesPending < maxRequired)
{
Grow(maxRequired);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
Debug.Assert(_options.SkipValidation || _tokenType != JsonTokenType.PropertyName);
if (_tokenType != JsonTokenType.None)
{
WriteNewLine(output);
}
JsonWriterHelper.WriteIndentation(output.Slice(BytesPending), indent);
BytesPending += indent;
output[BytesPending++] = JsonConstants.Quote;
escapedPropertyName.CopyTo(output.Slice(BytesPending));
BytesPending += escapedPropertyName.Length;
output[BytesPending++] = JsonConstants.Quote;
output[BytesPending++] = JsonConstants.KeyValueSeperator;
output[BytesPending++] = JsonConstants.Space;
output[BytesPending++] = token;
}
private void WritePropertyNameMinimized(ReadOnlySpan<char> escapedPropertyName, byte token)
{
Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - 5);
// All ASCII, 2 quotes, 1 colon, and 1 start token => escapedPropertyName.Length + 4
// Optionally, 1 list separator, and up to 3x growth when transcoding
int maxRequired = (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 5;
if (_memory.Length - BytesPending < maxRequired)
{
Grow(maxRequired);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
output[BytesPending++] = JsonConstants.Quote;
TranscodeAndWrite(escapedPropertyName, output);
output[BytesPending++] = JsonConstants.Quote;
output[BytesPending++] = JsonConstants.KeyValueSeperator;
output[BytesPending++] = token;
}
private void WritePropertyNameIndented(ReadOnlySpan<char> escapedPropertyName, byte token)
{
int indent = Indentation;
Debug.Assert(indent <= 2 * JsonConstants.MaxWriterDepth);
Debug.Assert(escapedPropertyName.Length < (int.MaxValue / JsonConstants.MaxExpansionFactorWhileTranscoding) - indent - 6 - s_newLineLength);
// All ASCII, 2 quotes, 1 colon, 1 space, and 1 start token => indent + escapedPropertyName.Length + 5
// Optionally, 1 list separator, 1-2 bytes for new line, and up to 3x growth when transcoding
int maxRequired = indent + (escapedPropertyName.Length * JsonConstants.MaxExpansionFactorWhileTranscoding) + 6 + s_newLineLength;
if (_memory.Length - BytesPending < maxRequired)
{
Grow(maxRequired);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
Debug.Assert(_options.SkipValidation || _tokenType != JsonTokenType.PropertyName);
if (_tokenType != JsonTokenType.None)
{
WriteNewLine(output);
}
JsonWriterHelper.WriteIndentation(output.Slice(BytesPending), indent);
BytesPending += indent;
output[BytesPending++] = JsonConstants.Quote;
TranscodeAndWrite(escapedPropertyName, output);
output[BytesPending++] = JsonConstants.Quote;
output[BytesPending++] = JsonConstants.KeyValueSeperator;
output[BytesPending++] = JsonConstants.Space;
output[BytesPending++] = token;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void TranscodeAndWrite(ReadOnlySpan<char> escapedPropertyName, Span<byte> output)
{
ReadOnlySpan<byte> byteSpan = MemoryMarshal.AsBytes(escapedPropertyName);
OperationStatus status = JsonWriterHelper.ToUtf8(byteSpan, output.Slice(BytesPending), out int consumed, out int written);
Debug.Assert(status == OperationStatus.Done);
Debug.Assert(consumed == byteSpan.Length);
BytesPending += written;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="SyncResponse.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the SyncResponse class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
/// <summary>
/// Represents the base response class for synchronuization operations.
/// </summary>
/// <typeparam name="TServiceObject">ServiceObject type.</typeparam>
/// <typeparam name="TChange">Change type.</typeparam>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class SyncResponse<TServiceObject, TChange> : ServiceResponse
where TServiceObject : ServiceObject
where TChange : Change
{
private ChangeCollection<TChange> changes = new ChangeCollection<TChange>();
private PropertySet propertySet;
/// <summary>
/// Initializes a new instance of the <see cref="SyncResponse<TServiceObject, TChange>"/> class.
/// </summary>
/// <param name="propertySet">Property set.</param>
internal SyncResponse(PropertySet propertySet)
: base()
{
this.propertySet = propertySet;
EwsUtilities.Assert(
this.propertySet != null,
"SyncResponse.ctor",
"PropertySet should not be null");
}
/// <summary>
/// Gets the name of the includes last in range XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal abstract string GetIncludesLastInRangeXmlElementName();
/// <summary>
/// Creates the change instance.
/// </summary>
/// <returns>TChange instance</returns>
internal abstract TChange CreateChangeInstance();
/// <summary>
/// Gets the name of the change element.
/// </summary>
/// <returns>Change element name.</returns>
internal abstract string GetChangeElementName();
/// <summary>
/// Gets the name of the change id element.
/// </summary>
/// <returns>Change id element name.</returns>
internal abstract string GetChangeIdElementName();
/// <summary>
/// Reads response elements from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadElementsFromXml(EwsServiceXmlReader reader)
{
this.Changes.SyncState = reader.ReadElementValue(XmlNamespace.Messages, XmlElementNames.SyncState);
this.Changes.MoreChangesAvailable = !reader.ReadElementValue<bool>(XmlNamespace.Messages, this.GetIncludesLastInRangeXmlElementName());
reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.Changes);
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if (reader.IsStartElement())
{
TChange change = this.CreateChangeInstance();
switch (reader.LocalName)
{
case XmlElementNames.Create:
change.ChangeType = ChangeType.Create;
break;
case XmlElementNames.Update:
change.ChangeType = ChangeType.Update;
break;
case XmlElementNames.Delete:
change.ChangeType = ChangeType.Delete;
break;
case XmlElementNames.ReadFlagChange:
change.ChangeType = ChangeType.ReadFlagChange;
break;
default:
reader.SkipCurrentElement();
break;
}
if (change != null)
{
reader.Read();
reader.EnsureCurrentNodeIsStartElement();
switch (change.ChangeType)
{
case ChangeType.Delete:
case ChangeType.ReadFlagChange:
change.Id = change.CreateId();
change.Id.LoadFromXml(reader, change.Id.GetXmlElementName());
if (change.ChangeType == ChangeType.ReadFlagChange)
{
reader.Read();
reader.EnsureCurrentNodeIsStartElement();
ItemChange itemChange = change as ItemChange;
EwsUtilities.Assert(
itemChange != null,
"SyncResponse.ReadElementsFromXml",
"ReadFlagChange is only valid on ItemChange");
itemChange.IsRead = reader.ReadElementValue<bool>(XmlNamespace.Types, XmlElementNames.IsRead);
}
break;
default:
change.ServiceObject = EwsUtilities.CreateEwsObjectFromXmlElementName<TServiceObject>(
reader.Service,
reader.LocalName);
change.ServiceObject.LoadFromXml(
reader,
true, /* clearPropertyBag */
this.propertySet,
this.SummaryPropertiesOnly);
break;
}
reader.ReadEndElementIfNecessary(XmlNamespace.Types, change.ChangeType.ToString());
this.changes.Add(change);
}
}
}
while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.Changes));
}
}
/// <summary>
/// Reads response elements from Json.
/// </summary>
/// <param name="responseObject">The response object.</param>
/// <param name="service">The service.</param>
internal override void ReadElementsFromJson(JsonObject responseObject, ExchangeService service)
{
this.Changes.SyncState = responseObject.ReadAsString(XmlElementNames.SyncState);
this.Changes.MoreChangesAvailable = !responseObject.ReadAsBool(this.GetIncludesLastInRangeXmlElementName());
JsonObject changesElement = responseObject.ReadAsJsonObject(XmlElementNames.Changes);
foreach (object changeElement in changesElement.ReadAsArray(XmlElementNames.Changes))
{
JsonObject jsonChange = changeElement as JsonObject;
TChange change = this.CreateChangeInstance();
string changeType = jsonChange.ReadAsString(XmlElementNames.ChangeType);
switch (changeType)
{
case XmlElementNames.Create:
change.ChangeType = ChangeType.Create;
break;
case XmlElementNames.Update:
change.ChangeType = ChangeType.Update;
break;
case XmlElementNames.Delete:
change.ChangeType = ChangeType.Delete;
break;
case XmlElementNames.ReadFlagChange:
change.ChangeType = ChangeType.ReadFlagChange;
break;
default:
break;
}
if (change != null)
{
switch (change.ChangeType)
{
case ChangeType.Delete:
case ChangeType.ReadFlagChange:
change.Id = change.CreateId();
JsonObject jsonChangeId = jsonChange.ReadAsJsonObject(this.GetChangeIdElementName());
change.Id.LoadFromJson(jsonChangeId, service);
if (change.ChangeType == ChangeType.ReadFlagChange)
{
ItemChange itemChange = change as ItemChange;
EwsUtilities.Assert(
itemChange != null,
"SyncResponse.ReadElementsFromJson",
"ReadFlagChange is only valid on ItemChange");
itemChange.IsRead = jsonChange.ReadAsBool(XmlElementNames.IsRead);
}
break;
default:
JsonObject jsonServiceObject = jsonChange.ReadAsJsonObject(this.GetChangeElementName());
change.ServiceObject = EwsUtilities.CreateEwsObjectFromXmlElementName<TServiceObject>(service, jsonServiceObject.ReadTypeString());
change.ServiceObject.LoadFromJson(
jsonServiceObject,
service,
true, /* clearPropertyBag */
this.propertySet,
this.SummaryPropertiesOnly);
break;
}
this.changes.Add(change);
}
}
}
/// <summary>
/// Gets a list of changes that occurred on the synchronized folder.
/// </summary>
public ChangeCollection<TChange> Changes
{
get { return this.changes; }
}
/// <summary>
/// Gets a value indicating whether this request returns full or summary properties.
/// </summary>
internal abstract bool SummaryPropertiesOnly
{
get;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Tests;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Tests
{
public static partial class LazyTests
{
[Fact]
public static void Ctor()
{
var lazyString = new Lazy<string>();
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
var lazyObject = new Lazy<int>();
VerifyLazy(lazyObject, 0, hasValue: true, isValueCreated: false);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void Ctor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(isThreadSafe);
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory()
{
var lazyString = new Lazy<string>(() => "foo");
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
var lazyInt = new Lazy<int>(() => 1);
VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory_NullValueFactory_ThrowsArguentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null)); // Value factory is null
}
[Fact]
public static void Ctor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
}
[Fact]
public static void Ctor_LazyThreadSafetyMode_InvalidMode_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void Ctor_ValueFactor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(() => "foo", isThreadSafe);
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory_Bool_NullValueFactory_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, false)); // Value factory is null
}
[Fact]
public static void Ctor_ValueFactor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(() => "foo", LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
var lazyInt = new Lazy<int>(() => 1, LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactor_LazyThreadSafetyMode_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, LazyThreadSafetyMode.PublicationOnly)); // Value factory is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foo", LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foof", LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Fact]
public static void ToString_DoesntForceAllocation()
{
var lazy = new Lazy<object>(() => 1);
Assert.NotEqual("1", lazy.ToString());
Assert.False(lazy.IsValueCreated);
object tmp = lazy.Value;
Assert.Equal("1", lazy.ToString());
}
private static void Value_Invalid_Impl<T>(ref Lazy<T> x, Lazy<T> lazy)
{
x = lazy;
Assert.Throws<InvalidOperationException>(() => lazy.Value);
}
[Fact]
public static void Value_Invalid()
{
Lazy<int> x = null;
Func<int> f = () => x.Value;
Value_Invalid_Impl(ref x, new Lazy<int>(f));
Value_Invalid_Impl(ref x, new Lazy<int>(f, true));
Value_Invalid_Impl(ref x, new Lazy<int>(f, false));
Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.ExecutionAndPublication));
Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.None));
// When used with LazyThreadSafetyMode.PublicationOnly this causes a stack overflow
// Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.PublicationOnly));
}
public class InitiallyExceptionThrowingCtor
{
public static int counter = 0;
public static int getValue()
{
if (++counter < 5)
throw new Exception();
else
return counter;
}
public int Value { get; }
public InitiallyExceptionThrowingCtor()
{
Value = getValue();
}
}
private static IEnumerable<Lazy<InitiallyExceptionThrowingCtor>> Ctor_ExceptionRecovery_MemberData()
{
yield return new Lazy<InitiallyExceptionThrowingCtor>();
yield return new Lazy<InitiallyExceptionThrowingCtor>(true);
yield return new Lazy<InitiallyExceptionThrowingCtor>(false);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.ExecutionAndPublication);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.None);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.PublicationOnly);
}
//
// Do not use [Theory]. XUnit argument formatter can invoke the lazy.Value property underneath you and ruin the assumptions
// made by the test.
//
[Fact]
public static void Ctor_ExceptionRecovery()
{
foreach (Lazy<InitiallyExceptionThrowingCtor> lazy in Ctor_ExceptionRecovery_MemberData())
{
InitiallyExceptionThrowingCtor.counter = 0;
InitiallyExceptionThrowingCtor result = null;
for (int i = 0; i < 10; ++i)
{
try
{ result = lazy.Value; }
catch (Exception) { }
}
Assert.Equal(5, result.Value);
}
}
private static void Value_ExceptionRecovery_IntImpl(Lazy<int> lazy, ref int counter, int expected)
{
counter = 0;
int result = 0;
for (var i = 0; i < 10; ++i)
{
try { result = lazy.Value; } catch (Exception) { }
}
Assert.Equal(result, expected);
}
private static void Value_ExceptionRecovery_StringImpl(Lazy<string> lazy, ref int counter, string expected)
{
counter = 0;
var result = default(string);
for (var i = 0; i < 10; ++i)
{
try { result = lazy.Value; } catch (Exception) { }
}
Assert.Equal(expected, result);
}
[Fact]
public static void Value_ExceptionRecovery()
{
int counter = 0; // set in test function
var fint = new Func<int> (() => { if (++counter < 5) throw new Exception(); else return counter; });
var fobj = new Func<string>(() => { if (++counter < 5) throw new Exception(); else return counter.ToString(); });
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, true), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, false), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.None), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.PublicationOnly), ref counter, 5);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, true), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, false), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.None), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.PublicationOnly), ref counter, 5.ToString());
}
class MyException
: Exception
{
public int Value { get; }
public MyException(int value)
{
Value = value;
}
}
public class ExceptionInCtor
{
public ExceptionInCtor() : this(99) { }
public ExceptionInCtor(int value)
{
throw new MyException(value);
}
}
public static IEnumerable<object[]> Value_Func_Exception_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_Func_Exception_MemberData))]
public static void Value_Func_Exception(Lazy<int> lazy)
{
Assert.Throws<MyException>(() => lazy.Value);
}
public static IEnumerable<object[]> Value_FuncCtor_Exception_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_FuncCtor_Exception_MemberData))]
public static void Value_FuncCtor_Exception(Lazy<ExceptionInCtor> lazy)
{
Assert.Throws<MyException>(() => lazy.Value);
}
public static IEnumerable<object[]> Value_TargetInvocationException_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>() };
yield return new object[] { new Lazy<ExceptionInCtor>(true) };
yield return new object[] { new Lazy<ExceptionInCtor>(false) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_TargetInvocationException_MemberData))]
public static void Value_TargetInvocationException(Lazy<ExceptionInCtor> lazy)
{
Assert.Throws<TargetInvocationException>(() => lazy.Value);
}
public static IEnumerable<object[]> Exceptions_Func_Idempotent_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) };
}
[Theory]
[MemberData(nameof(Exceptions_Func_Idempotent_MemberData))]
public static void Exceptions_Func_Idempotent(Lazy<int> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
public static IEnumerable<object[]> Exceptions_Ctor_Idempotent_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) };
}
[Theory]
[MemberData(nameof(Exceptions_Ctor_Idempotent_MemberData))]
public static void Exceptions_Ctor_Idempotent(Lazy<ExceptionInCtor> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
public static IEnumerable<object[]> Exceptions_Func_NotIdempotent_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) };
}
public static IEnumerable<object[]> Exceptions_Ctor_NotIdempotent_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>() };
yield return new object[] { new Lazy<ExceptionInCtor>(true) };
yield return new object[] { new Lazy<ExceptionInCtor>(false) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Exceptions_Func_NotIdempotent_MemberData))]
public static void Exceptions_Func_NotIdempotent(Lazy<int> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
[Theory]
[MemberData(nameof(Exceptions_Ctor_NotIdempotent_MemberData))]
public static void Exceptions_Ctor_NotIdempotent(Lazy<ExceptionInCtor> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
[Fact]
[ActiveIssue(19119, TargetFrameworkMonikers.Netcoreapp)]
public static void Serialization_ValueType()
{
Lazy<int> fortytwo = BinaryFormatterHelpers.Clone(new Lazy<int>(() => 42));
Assert.True(fortytwo.IsValueCreated);
Assert.Equal(fortytwo.Value, 42);
}
[Fact]
[ActiveIssue(19119, TargetFrameworkMonikers.Netcoreapp)]
public static void Serialization_RefType()
{
Lazy<string> fortytwo = BinaryFormatterHelpers.Clone(new Lazy<string>(() => "42"));
Assert.True(fortytwo.IsValueCreated);
Assert.Equal(fortytwo.Value, "42");
}
[Theory]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
[InlineData(LazyThreadSafetyMode.None)]
public static void Value_ThrownException_DoesntCreateValue(LazyThreadSafetyMode mode)
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, mode);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.Same(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void Value_ThrownException_DoesntCreateValue_PublicationOnly()
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, LazyThreadSafetyMode.PublicationOnly);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.NotSame(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void EnsureInitalized_SimpleRefTypes()
{
var hdcTemplate = new HasDefaultCtor();
string strTemplate = "foo";
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a));
Assert.Same(a, LazyInitializer.EnsureInitialized(ref a));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b));
Assert.Same(b, LazyInitializer.EnsureInitialized(ref b));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, () => strTemplate));
Assert.Same(c, LazyInitializer.EnsureInitialized(ref c));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, () => strTemplate + "bar"));
Assert.Same(d, LazyInitializer.EnsureInitialized(ref d));
Assert.Equal(strTemplate, d);
}
[Fact]
public static void EnsureInitalized_SimpleRefTypes_Invalid()
{
// Func based initialization (nulls not permitted).
string e = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref e, () => null));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc));
}
[Fact]
public static void EnsureInitialized_ComplexRefTypes()
{
string strTemplate = "foo";
var hdcTemplate = new HasDefaultCtor();
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
bool aInit = false;
object aLock = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock));
Assert.NotNull(a);
Assert.True(aInit);
Assert.NotNull(aLock);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
bool bInit = true;
object bLock = null;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock));
Assert.Equal(hdcTemplate, b);
Assert.True(bInit);
Assert.Null(bLock);
// Func based initialization (uninitialized).
string c = null;
bool cInit = false;
object cLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => strTemplate));
Assert.Equal(strTemplate, c);
Assert.True(cInit);
Assert.NotNull(cLock);
// Func based initialization (already initialized).
string d = strTemplate;
bool dInit = true;
object dLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
Assert.True(dInit);
Assert.Null(dLock);
// Func based initialization (nulls *ARE* permitted).
string e = null;
bool einit = false;
object elock = null;
int initCount = 0;
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
Assert.Null(e);
Assert.Equal(1, initCount);
Assert.True(einit);
Assert.NotNull(elock);
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
}
[Fact]
public static void EnsureInitalized_ComplexRefTypes_Invalid()
{
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
bool ndcInit = false;
object ndcLock = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc, ref ndcInit, ref ndcLock));
}
[Fact]
public static void LazyInitializerComplexValueTypes()
{
var empty = new LIX();
var template = new LIX(33);
// Activator.CreateInstance (uninitialized).
LIX a = default(LIX);
bool aInit = false;
object aLock = null;
LIX ensuredValA = LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock);
Assert.Equal(empty, ensuredValA);
Assert.Equal(empty, a);
// Activator.CreateInstance (already initialized).
LIX b = template;
bool bInit = true;
object bLock = null;
LIX ensuredValB = LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock);
Assert.Equal(template, ensuredValB);
Assert.Equal(template, b);
// Func based initialization (uninitialized).
LIX c = default(LIX);
bool cInit = false;
object cLock = null;
LIX ensuredValC = LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => template);
Assert.Equal(template, c);
Assert.Equal(template, ensuredValC);
// Func based initialization (already initialized).
LIX d = template;
bool dInit = true;
object dLock = null;
LIX template2 = new LIX(template.f * 2);
LIX ensuredValD = LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => template2);
Assert.Equal(template, ensuredValD);
Assert.Equal(template, d);
}
private static void VerifyLazy<T>(Lazy<T> lazy, T expectedValue, bool hasValue, bool isValueCreated)
{
Assert.Equal(isValueCreated, lazy.IsValueCreated);
if (hasValue)
{
Assert.Equal(expectedValue, lazy.Value);
Assert.True(lazy.IsValueCreated);
}
else
{
Assert.Throws<MissingMemberException>(() => lazy.Value); // Value could not be created
Assert.False(lazy.IsValueCreated);
}
}
private class HasDefaultCtor { }
private class NoDefaultCtor
{
public NoDefaultCtor(int x) { }
}
private struct LIX
{
public int f;
public LIX(int f) { this.f = f; }
public override bool Equals(object other) => other is LIX && ((LIX)other).f == f;
public override int GetHashCode() => f.GetHashCode();
public override string ToString() => "LIX<" + f + ">";
}
}
}
| |
// 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>
/// ToInt64(System.Object)
/// </summary>
public class ConvertToInt64_9
{
#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;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
//
// TODO: Add your negative test cases here
//
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt64((object)random).");
try
{
object random = TestLibrary.Generator.GetInt64(-55);
long actual = Convert.ToInt64(random);
long expected = (long)random;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt64((object)0)");
try
{
object obj = 0;
long actual = Convert.ToInt64(obj);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt64((object)int64.max)");
try
{
object obj = Int64.MaxValue;
long actual = Convert.ToInt64(obj);
long expected = Int64.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt64((object)int64.min)");
try
{
object obj = Int64.MinValue;
long actual = Convert.ToInt64(obj);
long expected = Int64.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt64(true)");
try
{
object obj = true;
long actual = Convert.ToInt64(obj);
long expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify method ToInt64(false)");
try
{
object obj = false;
long actual = Convert.ToInt64(obj);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("006.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify method ToInt64(null)");
try
{
object obj = null;
long actual = Convert.ToInt64(obj);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("007.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007.2", "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: InvalidCastException is not thrown.");
try
{
object obj = new object();
long r = Convert.ToInt64(obj);
TestLibrary.TestFramework.LogError("101.1", "InvalidCastException is not thrown.");
retVal = false;
}
catch (InvalidCastException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt64_9 test = new ConvertToInt64_9();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt64_9");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using nanoFramework.Tools.Debugger.WireProtocol;
using Polly;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using nanoFramework.Tools.Debugger.Extensions;
using nanoFramework.Tools.Debugger.PortTcpIp;
namespace nanoFramework.Tools.Debugger
{
[AddINotifyPropertyChangedInterface]
public abstract class NanoDeviceBase
{
/// <summary>
/// nanoFramework debug engine.
/// </summary>
///
public Engine DebugEngine { get; set; }
/// <summary>
/// Creates a new debug engine for this nanoDevice.
/// </summary>
public void CreateDebugEngine()
{
DebugEngine = new Engine(this);
DebugEngine.DefaultTimeout = Transport switch
{
TransportType.Serial => NanoSerialDevice.SafeDefaultTimeout,
TransportType.TcpIp => NanoNetworkDevice.SafeDefaultTimeout,
_ => throw new NotImplementedException()
};
}
/// <summary>
/// Creates a new debug engine for this nanoDevice.
/// </summary>
/// <param name="timeoutMilliseconds"></param>
public void CreateDebugEngine(int timeoutMilliseconds)
{
DebugEngine = new Engine(this);
DebugEngine.DefaultTimeout = NanoSerialDevice.SafeDefaultTimeout;
}
/// <summary>
/// Transport to the device.
/// </summary>
public TransportType Transport { get; set; }
/// <summary>
/// Port here this device is connected.
/// </summary>
public IPort ConnectionPort { get; set; }
/// <summary>
/// Id of the connection to the device.
/// </summary>
public string ConnectionId { get; internal set; }
/// <summary>
/// Device description.
/// </summary>
public string Description => TargetName + " @ " + ConnectionId;
/// <summary>
/// Target name.
/// </summary>
public string TargetName { get; internal set; }
/// <summary>
/// Target platform.
/// </summary>
public string Platform { get; internal set; }
/// <summary>
/// Device serial number (if define on the target).
/// </summary>
public string SerialNumber { get; internal set; }
/// <summary>
/// Unique ID of the NanoDevice.
/// </summary>
public Guid DeviceUniqueId { get; internal set; }
/// <summary>
/// Version of nanoBooter.
/// </summary>
public Version BooterVersion
{
get
{
try
{
return DebugEngine.TargetInfo.BooterVersion;
}
catch
{
return new Version();
}
}
}
/// <summary>
/// Version of nanoCLR.
/// </summary>
public Version CLRVersion
{
get
{
try
{
return DebugEngine.TargetInfo.CLRVersion;
}
catch
{
return new Version();
}
}
}
/// <summary>
/// Detailed info about the NanoFramework device hardware, solution and CLR.
/// </summary>
public INanoFrameworkDeviceInfo DeviceInfo { get; internal set; }
/// <summary>
/// This indicates if the device has a proprietary bootloader.
/// </summary>
public bool HasProprietaryBooter
{
get
{
return DebugEngine != null && DebugEngine.HasProprietaryBooter;
}
}
/// <summary>
/// This indicates if the target device has nanoBooter.
/// </summary>
public bool HasNanoBooter
{
get
{
return DebugEngine != null && DebugEngine.HasNanoBooter;
}
}
/// <summary>
/// This indicates if the target device is IFU capable.
/// </summary>
public bool IsIFUCapable
{
get
{
return DebugEngine != null && DebugEngine.IsIFUCapable;
}
}
private readonly object m_serverCert = null;
private readonly Dictionary<uint, string> m_execSrecHash = new Dictionary<uint, string>();
private readonly Dictionary<uint, int> m_srecHash = new Dictionary<uint, int>();
private readonly AutoResetEvent m_evtMicroBooter = new AutoResetEvent(false);
private readonly AutoResetEvent m_evtMicroBooterError = new AutoResetEvent(false);
private readonly ManualResetEvent m_evtMicroBooterStart = new ManualResetEvent(false);
protected NanoDeviceBase()
{
DeviceInfo = new NanoFrameworkDeviceInfo(this);
DeviceUniqueId = Guid.NewGuid();
}
private bool IsCLRDebuggerEnabled
{
get
{
try
{
if (DebugEngine.IsConnectedTonanoCLR)
{
return (DebugEngine.Capabilities.SourceLevelDebugging);
}
}
catch
{
}
return false;
}
}
public object OnProgress { get; private set; }
public object DeviceBase { get; internal set; }
public abstract void Disconnect(bool force = false);
/// <summary>
/// Get <see cref="INanoFrameworkDeviceInfo"/> from device.
/// If the device information has been retrieved before this method returns the cached data, unless the force argument is true.
/// </summary>
/// <param name="force">Force retrieving the information from the device.</param>
/// <returns>Return the <see cref="INanoFrameworkDeviceInfo"/> for this device.</returns>
public INanoFrameworkDeviceInfo GetDeviceInfo(bool force = true)
{
// start by checking if we already have this available
if (!DeviceInfo.Valid || force)
{
// seems to be invalid so get it from device
NanoFrameworkDeviceInfo nfDeviceInfo = new NanoFrameworkDeviceInfo(this);
nfDeviceInfo.GetDeviceInfo();
DeviceInfo = nfDeviceInfo;
}
return DeviceInfo;
}
/// <summary>
/// Attempts to communicate with the connected nanoFramework device
/// </summary>
/// <returns></returns>
public ConnectionSource Ping()
{
if(DebugEngine == null)
{
return ConnectionSource.Unknown;
}
return DebugEngine.GetConnectionSource();
}
/// <summary>
/// Start address of the deployment block.
/// Returns (-1) as invalid value if the address can't be retrieved from the device properties.
/// </summary>
public int GetDeploymentStartAddress()
{
if (DebugEngine != null)
{
return (int)DebugEngine.FlashSectorMap.FirstOrDefault(s =>
{
return (s.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT;
}).StartAddress;
}
return -1;
}
/// <summary>
/// Start address of the CLR block.
/// Returns (-1) as invalid value if the address can't be retrieved from the device properties.
/// </summary>
public int GetCLRStartAddress()
{
if (DebugEngine != null)
{
return (int)DebugEngine.FlashSectorMap.FirstOrDefault(s =>
{
return (s.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE;
}).StartAddress;
}
return -1;
}
/// <summary>
/// Attempt to establish a connection with nanoBooter (with reboot if necessary)
/// </summary>
/// <returns>true connection was made, false otherwise</returns>
public bool ConnectToNanoBooter()
{
bool ret = false;
if (!DebugEngine.Connect(1000, true))
{
return false;
}
if (DebugEngine != null)
{
if (DebugEngine.IsConnectedTonanoBooter) return true;
try
{
DebugEngine.RebootDevice(RebootOptions.EnterNanoBooter);
/////////////////////////////////////////
// FIXME
/////////////////////////////////////////
//// nanoBooter is only com port so
//if (Transport == TransportType.TcpIp)
//{
// _DBG.PortDefinition pdTmp = m_port;
// Disconnect();
// try
// {
// m_port = m_portNanoBooter;
// // digi takes forever to reset
// if (!Connect(60000, true))
// {
// Console.WriteLine(Properties.Resources.ErrorUnableToConnectToNanoBooterSerial);
// return false;
// }
// }
// finally
// {
// m_port = pdTmp;
// }
//}
bool fConnected = false;
for (int i = 0; i < 40; i++)
{
if (DebugEngine == null)
{
CreateDebugEngine();
}
if (fConnected = DebugEngine.Connect(
true))
{
ret = (DebugEngine.GetConnectionSource() == ConnectionSource.nanoBooter);
break;
}
}
if (!fConnected)
{
//Debug.WriteLine("Unable to connect to NanoBooter");
}
}
catch
{
// need a catch all here because some targets re-enumerate the USB device and that makes it impossible to catch them here
}
}
return ret;
}
/// <summary>
/// Erases the deployment sectors of the connected nanoDevice
/// </summary>
/// <param name="options">Identifies which areas are to be erased</param>
/// <param name="cancellationToken">Cancellation token to allow caller to cancel task</param>
/// <param name="log">Progress report of execution</param>
/// <returns>Returns false if the erase fails, true otherwise
/// Possible exceptions: MFUserExitException, MFDeviceNoResponseException
/// </returns>
public bool Erase(
EraseOptions options,
IProgress<MessageWithProgress> progress = null,
IProgress<string> log = null)
{
bool fReset = false;
bool requestBooter = false;
if (DebugEngine == null)
{
return false;
}
if (!IsCLRDebuggerEnabled || 0 != (options & EraseOptions.Firmware))
{
log?.Report("Connecting to nanoBooter...");
fReset = DebugEngine.IsConnectedTonanoCLR;
if (!ConnectToNanoBooter())
{
log?.Report("*** ERROR: request to connect to nanoBooter failed ***");
return false;
}
// flag request to launch nanoBooter
requestBooter = true;
}
if (DebugEngine.FlashSectorMap.Count == 0)
{
log?.Report("*** ERROR: device flash map not available, aborting ***");
return false;
}
if (requestBooter)
{
log?.Report("Getting connection source...");
DebugEngine.GetConnectionSource();
}
long total = 0;
if (DebugEngine.IsConnectedTonanoCLR)
{
var deviceState = DebugEngine.GetExecutionMode();
if (deviceState == Commands.DebuggingExecutionChangeConditions.State.Unknown)
{
log?.Report("*** ERROR: failed to retrieve device execution state ***");
return false;
}
if(!deviceState.IsDeviceInStoppedState())
{
log?.Report("Connected to CLR. Pausing execution...");
if (!DebugEngine.PauseExecution())
{
log?.Report("*** ERROR: failed to stop execution ***");
return false;
}
}
}
List<Commands.Monitor_FlashSectorMap.FlashSectorData> eraseSectors = new List<Commands.Monitor_FlashSectorMap.FlashSectorData>();
foreach (Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData in DebugEngine.FlashSectorMap)
{
switch (flashSectorData.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK)
{
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT:
if (EraseOptions.Deployment == (options & EraseOptions.Deployment))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_UPDATE:
if (EraseOptions.UpdateStorage == (options & EraseOptions.UpdateStorage))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_SIMPLE_A:
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_SIMPLE_B:
if (EraseOptions.SimpleStorage == (options & EraseOptions.SimpleStorage))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_STORAGE_A:
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_STORAGE_B:
if (EraseOptions.UserStorage == (options & EraseOptions.UserStorage))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_FS:
if (EraseOptions.FileSystem == (options & EraseOptions.FileSystem))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CONFIG:
if (EraseOptions.Configuration == (options & EraseOptions.Configuration))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
case Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE:
if (EraseOptions.Firmware == (options & EraseOptions.Firmware))
{
eraseSectors.Add(flashSectorData);
total++;
}
break;
}
}
uint totalBytes = (uint)eraseSectors.Sum(s => s.NumBlocks * s.BytesPerBlock);
uint current = 0;
foreach (Commands.Monitor_FlashSectorMap.FlashSectorData flashSectorData in eraseSectors)
{
var sectorSize = flashSectorData.NumBlocks * flashSectorData.BytesPerBlock;
progress?.Report(new MessageWithProgress($"Erasing sector @ 0x{flashSectorData.StartAddress:X8}...", current, totalBytes));
log?.Report($"Erasing sector @ 0x{flashSectorData.StartAddress:X8}...");
(AccessMemoryErrorCodes ErrorCode, bool Success) = DebugEngine.EraseMemory(
flashSectorData.StartAddress,
sectorSize);
if (!Success)
{
log?.Report($"Error erasing sector @ 0x{flashSectorData.StartAddress:X8}.");
return false;
}
// check the error code returned
if (ErrorCode != AccessMemoryErrorCodes.NoError)
{
// operation failed
log?.Report($"Error erasing sector @ 0x{flashSectorData.StartAddress:X8}. Error code: {ErrorCode}.");
// don't bother continuing
return false;
}
current += sectorSize;
}
// reset if we specifically entered nanoBooter to erase
if (fReset)
{
log?.Report("Executing memory...");
DebugEngine.ExecuteMemory(0);
}
// reboot if we are talking to the CLR
if (DebugEngine.IsConnectedTonanoCLR)
{
progress?.Report(new MessageWithProgress("Rebooting..."));
RebootOptions rebootOptions = RebootOptions.ClrOnly;
DebugEngine.RebootDevice(rebootOptions, log);
}
return true;
}
//public bool DeployUpdateAsync(StorageFile comprFilePath, CancellationToken cancellationToken, IProgress<string> progress = null)
//{
// if (DebugEngine.IsConnectedTonanoCLR)
// {
// if (await DeployMFUpdateAsync(comprFilePath, cancellationToken, progress))
// {
// return true;
// }
// }
// return false;
//}
/// <summary>
/// Attempts to deploy a binary (.bin) file to the connected nanoFramework device.
/// </summary>
/// <param name="binFile">Path to the binary file (.bin).</param>
/// <param name="address">Address to write to.</param>
/// <returns>Returns false if the deployment fails, true otherwise.
/// </returns>
/// <remarks>
/// To perform the update the device has to be running:
/// - nanoCLR if this is meant to update the deployment region.
/// - nanoBooter if this is meant to update nanoCLR
/// Failing to meet this condition will abort the operation.
/// </remarks>
public bool DeployBinaryFile(
string binFile,
uint address,
IProgress<string> progress = null)
{
// validate if file exists
if(!File.Exists(binFile))
{
return false;
}
if (DebugEngine == null)
{
return false;
}
var data = File.ReadAllBytes(binFile);
if (!PrepareForDeploy(
address,
progress))
{
return false;
}
if(!DeployFile(
data,
address,
0,
progress))
{
return false;
}
progress?.Report($"Verifying image...");
if (!VerifyMemory(
data,
address,
progress))
{
return false;
}
return true;
}
/// <summary>
/// Attempts to deploy an SREC (.hex) file to the connected nanoFramework device.
/// </summary>
/// <param name="srecFile">Path to the SREC file (.hex) file.</param>
/// <returns>Returns <see langword="false"/> if the deployment fails, <see langword="true"/> otherwise.
/// Also returns the entry point address for the given SREC file.
/// </returns>
// TODO this is not working most likely because of the format or parsing.
private bool DeploySrecFile(
string srecFile,
CancellationToken cancellationToken,
IProgress<string> progress = null)
{
// validate if file exists
if (!File.Exists(srecFile))
{
return false;
}
if (DebugEngine == null)
{
return false;
}
List<SRecordFile.Block> blocks = SRecordFile.Parse(srecFile);
if (blocks.Count > 0)
{
long total = 0;
long value = 0;
for (int i = 0; i < blocks.Count; i++)
{
total += blocks[i].data.Length;
}
if(!PrepareForDeploy(blocks, progress))
{
return false;
}
progress?.Report($"Deploying {Path.GetFileNameWithoutExtension(srecFile)}...");
foreach (SRecordFile.Block block in blocks)
{
uint addr = block.address;
// check if cancellation was requested
if (cancellationToken.IsCancellationRequested)
{
return false;
}
block.data.Seek(0, SeekOrigin.Begin);
byte[] data = new byte[block.data.Length];
if (!DeployFile(
data,
addr,
0,
progress))
{
return false;
}
}
}
return true;
}
private bool DeployFile(
byte[] buffer,
uint address,
int programAligment = 0,
IProgress<string> progress = null)
{
AccessMemoryErrorCodes errorCode = DebugEngine.WriteMemory(
address,
buffer,
programAligment);
if (errorCode != AccessMemoryErrorCodes.NoError)
{
progress?.Report($"Error writing to device memory @ 0x{address:X8}, error {errorCode}.");
return false;
}
return true;
}
private bool VerifyMemory(
byte[] buffer,
uint address,
IProgress<string> progress = null)
{
if (!DebugEngine.PerformWriteMemoryCheck(address, buffer))
{
progress?.Report($"Verification failed.");
return false;
}
return true;
}
/// <summary>
/// Starts execution on the connected nanoDevice at the supplied address (parameter entrypoint).
/// This method is generally used after the Deploy method to jump into the code that was deployed.
/// </summary>
/// <param name="entrypoint">Entry point address for execution to begin</param>
/// <returns>Returns false if execution fails, true otherwise
/// </returns>
public bool Execute(uint entryPoint)
{
if (DebugEngine == null)
{
return false;
}
if (CheckForMicroBooter())
{
if (m_execSrecHash.ContainsKey(entryPoint))
{
string execRec = m_execSrecHash[entryPoint];
bool fRet = false;
for (int retry = 0; retry < 10; retry++)
{
try
{
DebugEngine.SendBuffer(Encoding.UTF8.GetBytes(execRec));
DebugEngine.SendBuffer(Encoding.UTF8.GetBytes("\n"));
}
catch
{
// catch all, doesn't care about the return
return false;
}
if (m_evtMicroBooter.WaitOne(1000))
{
fRet = true;
break;
}
}
return fRet;
}
return false;
}
var connectionSource = DebugEngine.GetConnectionSource();
if (connectionSource == ConnectionSource.Unknown)
{
return false;
}
// only execute if connected to nanoBooter, otherwise reboot
if (connectionSource == ConnectionSource.nanoBooter)
{
return DebugEngine.ExecuteMemory(entryPoint);
}
else
{
// if connected to CLR then this was just a deployment update, reboot
DebugEngine.RebootDevice(RebootOptions.ClrOnly);
}
return true;
}
internal bool CheckForMicroBooter()
{
if (DebugEngine == null) return false;
try
{
m_evtMicroBooterStart.Set();
m_evtMicroBooterError.Reset();
// try to see if we are connected to MicroBooter
for (int retry = 0; retry < 5; retry++)
{
DebugEngine.SendBuffer(Encoding.UTF8.GetBytes("xx\n"));
if (m_evtMicroBooterError.WaitOne(100))
{
return true;
}
}
}
finally
{
m_evtMicroBooterStart.Reset();
}
return false;
}
//private bool DeployMFUpdateAsync(StorageFile zipFile, CancellationToken cancellationToken, IProgress<string> progress = null)
//{
// if (zipFile.IsAvailable)
// {
// byte[] packet = new byte[DebugEngine.WireProtocolPacketSize];
// try
// {
// int handle = -1;
// int idx = 0;
// Windows.Storage.FileProperties.BasicProperties fileInfo = await zipFile.GetBasicPropertiesAsync();
// uint numPkts = (uint)(fileInfo.Size + DebugEngine.WireProtocolPacketSize - 1) / DebugEngine.WireProtocolPacketSize;
// byte[] hashData = Encoding.UTF8.GetBytes(zipFile.Name + fileInfo.DateModified.ToString());
// uint updateId = CRC.ComputeCRC(hashData, 0, hashData.Length, 0);
// uint imageCRC = 0;
// byte[] sig = null;
// //Debug.WriteLine(updateId);
// handle = DebugEngine.StartUpdate("NetMF", 4, 4, updateId, 0, 0, (uint)fileInfo.Size, DebugEngine.WireProtocolPacketSize, 0);
// if (handle > -1)
// {
// uint authType;
// IAsyncResult iar = null;
// // perform request
// (byte[] Response, bool Success) resp = DebugEngine.UpdateAuthCommand(handle, 1, null);
// // check result
// if (!resp.Success || resp.Response.Length < 4) return false;
// using (MemoryStream ms = new MemoryStream(resp.Item1))
// using (BinaryReader br = new BinaryReader(ms))
// {
// authType = br.ReadUInt32();
// }
// byte[] pubKey = null;
// // FIXME
// //if (m_serverCert != null)
// //{
// // RSACryptoServiceProvider rsa = m_serverCert.PrivateKey as RSACryptoServiceProvider;
// // if (rsa != null)
// // {
// // pubKey = rsa.ExportCspBlob(false);
// // }
// //}
// if (!DebugEngine.UpdateAuthenticate(handle, pubKey))
// {
// return false;
// }
// // FIXME
// //if (authType == 1 && m_serverCert != null)
// //{
// // iar = await DebugEngine.UpgradeConnectionToSsl_Begin(m_serverCert, m_requireClientCert);
// // if (0 == WaitHandle.WaitAny(new WaitHandle[] { iar.AsyncWaitHandle, EventCancel }, 10000))
// // {
// // try
// // {
// // if (!m_eng.UpgradeConnectionToSSL_End(iar))
// // {
// // m_eng.Dispose();
// // m_eng = null;
// // return false;
// // }
// // }
// // catch
// // {
// // m_eng.Dispose();
// // m_eng = null;
// // return false;
// // }
// // }
// // else
// // {
// // return false;
// // }
// //}
// // FIXME
// //RSAPKCS1SignatureFormatter alg = null;
// object alg = null;
// HashAlgorithmProvider hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
// byte[] hashValue = null;
// try
// {
// if (m_serverCert != null)
// {
// //alg = new RSAPKCS1SignatureFormatter(m_serverCert.PrivateKey);
// //alg.SetHashAlgorithm("SHA1");
// hash = HashAlgorithmProvider.OpenAlgorithm("SHA1");
// hashValue = new byte[hash.HashLength / 8];
// }
// }
// catch
// {
// }
// IBuffer buffer = await FileIO.ReadBufferAsync(zipFile);
// using (DataReader dataReader = DataReader.FromBuffer(buffer))
// {
// dataReader.ReadBytes(packet);
// uint crc = CRC.ComputeCRC(packet, 0, packet.Length, 0);
// if (!DebugEngine.AddPacket(handle, (uint)idx++, packet, CRC.ComputeCRC(packet, 0, packet.Length, 0))) return false;
// imageCRC = CRC.ComputeCRC(packet, 0, packet.Length, imageCRC);
// progress?.Report($"Deploying {idx}...");
// }
// if (hash != null)
// {
// buffer = await FileIO.ReadBufferAsync(zipFile);
// // hash it
// IBuffer hashed = hash.HashData(buffer);
// CryptographicBuffer.CopyToByteArray(hashed, out sig);
// }
// if (alg != null)
// {
// //sig = alg.CreateSignature(hash);
// //CryptographicBuffer.CopyToByteArray(sig)
// }
// else
// {
// sig = new byte[4];
// using (MemoryStream ms = new MemoryStream(sig))
// using (BinaryWriter br = new BinaryWriter(ms))
// {
// br.Write(imageCRC);
// }
// }
// if (DebugEngine.InstallUpdate(handle, sig))
// {
// return true;
// }
// }
// }
// catch
// {
// }
// }
// return false;
//}
//private async Task<Tuple<uint, bool>> DeploySRECAsync(StorageFile srecFile, CancellationToken cancellationToken)
//{
// m_srecHash.Clear();
// m_execSrecHash.Clear();
// // create .EXT file for SREC file
// StorageFolder folder = await srecFile.GetParentAsync();
// int m_totalSrecs = 0;
// uint m_minSrecAddr = uint.MaxValue;
// uint m_maxSrecAddr = 0;
// if (srecFile.IsAvailable)
// {
// // check is EXT file exists, if yes delete it
// StorageFile srecExtFile = await folder.TryGetItemAsync(Path.GetFileNameWithoutExtension(srecFile.Name) + ".ext") as StorageFile;
// if (srecExtFile != null)
// {
// await srecExtFile.DeleteAsync();
// }
// if (await PreProcesSrecAsync(srecFile))
// {
// srecExtFile = await folder.TryGetItemAsync(srecFile.Name.Replace(srecFile.FileType, "") + ".ext") as StorageFile;
// }
// // check if cancellation was requested
// if (cancellationToken.IsCancellationRequested)
// {
// new Tuple<uint, bool>(0, false);
// }
// SrecParseResult parsedFile = await ParseSrecFileAsync(srecExtFile);
// try
// {
// int sleepTime = 5000;
// UInt32 imageAddr = 0xFFFFFFFF;
// m_totalSrecs = parsedFile.Records.Count;
// //m_evtMicroBooterStart.Set();
// //m_evtMicroBooter.Reset();
// //m_evtMicroBooterError.Reset();
// while (parsedFile.Records.Count > 0)
// {
// // check if cancellation was requested
// if (cancellationToken.IsCancellationRequested)
// {
// new Tuple<uint, bool>(0, false);
// }
// List<uint> remove = new List<uint>();
// const int c_MaxPipeline = 4;
// int pipe = c_MaxPipeline;
// uint[] keys = new uint[parsedFile.Records.Count];
// parsedFile.Records.Keys.CopyTo(keys, 0);
// Array.Sort(keys);
// if (keys[0] < imageAddr) imageAddr = keys[0];
// foreach (uint key in keys)
// {
// // check if cancellation was requested
// if (cancellationToken.IsCancellationRequested)
// {
// new Tuple<uint, bool>(0, false);
// }
// if (key < m_minSrecAddr) m_minSrecAddr = key;
// if (key > m_maxSrecAddr) m_maxSrecAddr = key;
// if (m_srecHash.ContainsKey(key))
// {
// remove.Add(key);
// continue;
// }
// await DebugEngine.SendBufferAsync(Encoding.UTF8.GetBytes("\n"), TimeSpan.FromMilliseconds(1000), cancellationToken).ConfigureAwait(true);
// await DebugEngine.SendBufferAsync(Encoding.UTF8.GetBytes(parsedFile.Records[key]), TimeSpan.FromMilliseconds(20000), cancellationToken).ConfigureAwait(true);
// await DebugEngine.SendBufferAsync(Encoding.UTF8.GetBytes("\n"), TimeSpan.FromMilliseconds(1000), cancellationToken).ConfigureAwait(true);
// if (pipe-- <= 0)
// {
// //m_evtMicroBooter.WaitOne(sleepTime);
// pipe = c_MaxPipeline;
// }
// }
// int cnt = remove.Count;
// if (cnt > 0)
// {
// for (int i = 0; i < cnt; i++)
// {
// parsedFile.Records.Remove(remove[i]);
// }
// }
// }
// if (imageAddr != 0)
// {
// string basefile = Path.GetFileNameWithoutExtension(srecFile.Name);
// // srecfile might be .bin.ext (for srec updates)
// if (!string.IsNullOrEmpty(Path.GetExtension(basefile)))
// {
// basefile = Path.GetFileNameWithoutExtension(basefile);
// }
// string path = folder.Path;
// string binFilePath = "";
// string symdefFilePath = "";
// if (folder.Path.ToLower().EndsWith("\\nanoCLR.hex"))
// {
// binFilePath = Path.GetDirectoryName(path) + "\\nanoCLR.bin\\" + basefile;
// symdefFilePath = Path.GetDirectoryName(path) + "\\nanoCLR.symdefs";
// }
// else
// {
// binFilePath = Path.GetDirectoryName(srecFile.Path) + "\\" + basefile + ".bin";
// symdefFilePath = Path.GetDirectoryName(srecFile.Path) + "\\" + basefile + ".symdefs";
// }
// StorageFile binFile = await folder.TryGetItemAsync(binFilePath) as StorageFile;
// StorageFile symdefFile = await folder.TryGetItemAsync(symdefFilePath) as StorageFile;
// // check if cancellation was requested
// if (cancellationToken.IsCancellationRequested)
// {
// new Tuple<uint, bool>(0, false);
// }
// // send image crc
// if (binFile != null && symdefFile != null)
// {
// Windows.Storage.FileProperties.BasicProperties fileInfo = await binFile.GetBasicPropertiesAsync();
// UInt32 imageCRC = 0;
// // read lines from SREC file
// IList<string> textLines = await FileIO.ReadLinesAsync(symdefFile);
// foreach (string line in textLines)
// {
// // check if cancellation was requested
// if (cancellationToken.IsCancellationRequested)
// {
// new Tuple<uint, bool>(0, false);
// }
// if (line.Contains("LOAD_IMAGE_CRC"))
// {
// int idxEnd = line.IndexOf(' ', 2);
// imageCRC = UInt32.Parse(line.Substring(2, idxEnd - 2), System.Globalization.NumberStyles.HexNumber);
// }
// }
// m_execSrecHash[parsedFile.EntryPoint] = string.Format("<CRC>{0:X08},{1:X08},{2:X08},{3:X08}</CRC>\n", imageAddr, fileInfo.Size, imageCRC, parsedFile.EntryPoint);
// }
// }
// return new Tuple<uint, bool>(parsedFile.EntryPoint, true);
// }
// finally
// {
// //m_evtMicroBooterStart.Reset();
// }
// }
// return new Tuple<uint, bool>(0, false);
//}
//private async Task<SrecParseResult> ParseSrecFileAsync(StorageFile srecFile)
//{
// SrecParseResult reply = new SrecParseResult();
// Dictionary<uint, string> recs = new Dictionary<uint, string>();
// try
// {
// int total = 0;
// IList<string> textLines = await FileIO.ReadLinesAsync(srecFile);
// foreach (string line in textLines)
// {
// string addr = line.Substring(4, 8);
// // we only support s7, s3 records
// if (line.ToLower().StartsWith("s7"))
// {
// reply.EntryPoint = uint.Parse(addr, System.Globalization.NumberStyles.HexNumber);
// }
// else if (line.ToLower().StartsWith("s3"))
// {
// total += line.Length - 14;
// reply.Records[uint.Parse(addr, System.Globalization.NumberStyles.HexNumber)] = line;
// }
// }
// reply.ImageSize = (uint)total;
// }
// catch
// {
// return null;
// }
// return reply;
//}
//private bool PreProcesSrecAsync(StorageFile srecFile)
//{
// if (!srecFile.IsAvailable) return false;
// // create .EXT file for SREC file
// StorageFolder folder = await srecFile.GetParentAsync();
// try
// {
// // read lines from SREC file
// IList<string> textLines = await FileIO.ReadLinesAsync(srecFile);
// StorageFile srecExtFile = await folder.CreateFileAsync(Path.GetFileNameWithoutExtension(srecFile.Name) + ".ext", CreationCollisionOption.ReplaceExisting);
// const int c_MaxRecords = 8;
// int iRecord = 0;
// int currentCRC = 0;
// int iDataLength = 0;
// string s7rec = "";
// StringBuilder sb = new StringBuilder();
// foreach (string line in textLines)
// {
// // we only support s7, s3 records
// if (line.ToLower().StartsWith("s7"))
// {
// s7rec = line;
// continue;
// }
// if (!line.ToLower().StartsWith("s3")) continue;
// string crcData;
// if (iRecord == 0)
// {
// crcData = line.Substring(4, line.Length - 6);
// }
// else
// {
// crcData = line.Substring(12, line.Length - 14);
// }
// iDataLength += crcData.Length / 2; // 2 chars per byte
// if (iRecord == 0)
// {
// sb.Append(line.Substring(0, 2));
// }
// sb.Append(crcData);
// iRecord++;
// for (int i = 0; i < crcData.Length - 1; i += 2)
// {
// currentCRC += Byte.Parse(crcData.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
// }
// if (iRecord == c_MaxRecords)
// {
// iDataLength += 1; // crc
// sb = sb.Insert(2, string.Format("{0:X02}", iDataLength));
// currentCRC += (iDataLength & 0xFF) + ((iDataLength >> 8) & 0xFF);
// // write crc
// sb.Append(string.Format("{0:X02}", (0xFF - (0xFF & currentCRC))));
// await FileIO.WriteTextAsync(srecExtFile, sb.ToString());
// currentCRC = 0;
// iRecord = 0;
// iDataLength = 0;
// sb.Length = 0;
// }
// }
// if (iRecord != 0)
// {
// iDataLength += 1; // crc
// sb = sb.Insert(2, string.Format("{0:X02}", iDataLength));
// currentCRC += (iDataLength & 0xFF) + ((iDataLength >> 8) & 0xFF);
// // write crc
// sb.Append(string.Format("{0:X02}", (0xFF - (0xFF & currentCRC))));
// await FileIO.WriteTextAsync(srecExtFile, sb.ToString());
// }
// if (s7rec != "")
// {
// await FileIO.WriteTextAsync(srecExtFile, s7rec);
// }
// }
// catch
// {
// StorageFile thisFile = await folder.TryGetItemAsync(Path.GetFileNameWithoutExtension(srecFile.Name) + ".ext") as StorageFile;
// if (thisFile != null)
// {
// await thisFile.DeleteAsync();
// }
// return false;
// }
// return true;
//}
private bool PrepareForDeploy(
uint address,
IProgress<string> progress = null)
{
return PrepareForDeploy(
address,
null,
progress);
}
private bool PrepareForDeploy(
List<SRecordFile.Block> blocks,
IProgress<string> progress = null)
{
return PrepareForDeploy(
0,
blocks,
progress);
}
private bool PrepareForDeploy(
uint address,
List<SRecordFile.Block> blocks,
IProgress<string> progress = null)
{
// get flash sector map, only if needed
List<Commands.Monitor_FlashSectorMap.FlashSectorData> flashSectorsMap = DebugEngine.FlashSectorMap;
// sanity check
if (flashSectorsMap == null ||
flashSectorsMap.Count == 0)
{
return false;
}
// validate deployment
bool updatesDeployment = false;
bool updatesClr = false;
bool updatesBooter = false;
if (blocks != null)
{
foreach (SRecordFile.Block bl in blocks)
{
var startSector = flashSectorsMap.Find(s => s.StartAddress == bl.address);
if (startSector.NumBlocks > 0)
{
updatesDeployment ^= (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT;
updatesClr ^= (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE;
updatesBooter ^= (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_BOOTSTRAP;
}
}
}
else
{
var startSector = flashSectorsMap.Find(s => s.StartAddress == address);
if (startSector.NumBlocks > 0)
{
updatesDeployment = (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_DEPLOYMENT;
updatesClr = (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE;
updatesBooter = (startSector.Flags & Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_MASK) == Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_BOOTSTRAP;
}
}
// sanity check
if (updatesBooter)
{
// can't handle this update because it touches nanoBooter
progress?.Report("Can't deploy file because it updates nanoBooter.");
return false;
}
if(
!updatesDeployment &&
!updatesClr &&
!updatesBooter)
{
// nothing to update???
return false;
}
if (updatesClr)
{
// if this is updating the CLR need to launch nanoBooter
if (!DebugEngine.IsConnectedTonanoBooter)
{
progress?.Report("Need to launch nanoBooter before updating the firmware.");
return false;
}
}
// erase whatever blocks are required
if (updatesClr)
{
if (!Erase(
EraseOptions.Firmware,
null,
progress))
{
return false;
}
}
if (updatesDeployment)
{
if (!Erase(
EraseOptions.Deployment,
null,
progress))
{
return false;
}
}
if (DebugEngine.IsConnectedTonanoCLR)
{
DebugEngine.PauseExecution();
}
return true;
}
}
}
| |
namespace System.Collections.Generic
{
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Security.Permissions;
[Serializable()]
////[DebuggerTypeProxy( typeof( System_CollectionDebugView<> ) )]
////[DebuggerDisplay( "Count = {Count}" )]
public class LinkedList<T> : ICollection<T>, System.Collections.ICollection/*, ISerializable, IDeserializationCallback*/
{
// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;
internal int count;
internal int version;
private Object _syncRoot;
//// private SerializationInfo siInfo; //A temporary variable which we need during deserialization.
////
//// // names for serialization
//// const String VersionName = "Version";
//// const String CountName = "Count";
//// const String ValuesName = "Data";
public LinkedList()
{
}
public LinkedList( IEnumerable<T> collection )
{
if(collection == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "collection" );
#else
throw new ArgumentNullException();
#endif
}
foreach(T item in collection)
{
AddLast( item );
}
}
//// protected LinkedList( SerializationInfo info, StreamingContext context )
//// {
//// siInfo = info;
//// }
public int Count
{
get
{
return count;
}
}
public LinkedListNode<T> First
{
get
{
return head;
}
}
public LinkedListNode<T> Last
{
get
{
return head == null ? null : head.prev;
}
}
bool ICollection<T>.IsReadOnly
{
get
{
return false;
}
}
void ICollection<T>.Add( T value )
{
AddLast( value );
}
public LinkedListNode<T> AddAfter( LinkedListNode<T> node ,
T value )
{
ValidateNode( node );
LinkedListNode<T> result = new LinkedListNode<T>( node.list, value );
InternalInsertNodeBefore( node.next, result );
return result;
}
public void AddAfter( LinkedListNode<T> node ,
LinkedListNode<T> newNode )
{
ValidateNode( node );
ValidateNewNode( newNode );
InternalInsertNodeBefore( node.next, newNode );
newNode.list = this;
}
public LinkedListNode<T> AddBefore( LinkedListNode<T> node ,
T value )
{
ValidateNode( node );
LinkedListNode<T> result = new LinkedListNode<T>( node.list, value );
InternalInsertNodeBefore( node, result );
if(node == head)
{
head = result;
}
return result;
}
public void AddBefore( LinkedListNode<T> node ,
LinkedListNode<T> newNode )
{
ValidateNode( node );
ValidateNewNode( newNode );
InternalInsertNodeBefore( node, newNode );
newNode.list = this;
if(node == head)
{
head = newNode;
}
}
public LinkedListNode<T> AddFirst( T value )
{
LinkedListNode<T> result = new LinkedListNode<T>( this, value );
if(head == null)
{
InternalInsertNodeToEmptyList( result );
}
else
{
InternalInsertNodeBefore( head, result );
head = result;
}
return result;
}
public void AddFirst( LinkedListNode<T> node )
{
ValidateNewNode( node );
if(head == null)
{
InternalInsertNodeToEmptyList( node );
}
else
{
InternalInsertNodeBefore( head, node );
head = node;
}
node.list = this;
}
public LinkedListNode<T> AddLast( T value )
{
LinkedListNode<T> result = new LinkedListNode<T>( this, value );
if(head == null)
{
InternalInsertNodeToEmptyList( result );
}
else
{
InternalInsertNodeBefore( head, result );
}
return result;
}
public void AddLast( LinkedListNode<T> node )
{
ValidateNewNode( node );
if(head == null)
{
InternalInsertNodeToEmptyList( node );
}
else
{
InternalInsertNodeBefore( head, node );
}
node.list = this;
}
public void Clear()
{
LinkedListNode<T> current = head;
while(current != null)
{
LinkedListNode<T> temp = current;
current = current.Next; // use Next the instead of "next", otherwise it will loop forever
temp.Invalidate();
}
head = null;
count = 0;
version++;
}
public bool Contains( T value )
{
return Find( value ) != null;
}
public void CopyTo( T[] array, int index )
{
if(array == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "array" );
#else
throw new ArgumentNullException();
#endif
}
if(index < 0 || index > array.Length)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index" ); //, SR.GetString( SR.IndexOutOfRange, index ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(array.Length - index < Count)
{
throw new ArgumentException(); // SR.GetString( SR.Arg_InsufficientSpace ) );
}
LinkedListNode<T> node = head;
if(node != null)
{
do
{
array[index++] = node.item;
node = node.next;
} while(node != head);
}
}
public LinkedListNode<T> Find( T value )
{
LinkedListNode<T> node = head;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if(node != null)
{
if(value != null)
{
do
{
if(c.Equals( node.item, value ))
{
return node;
}
node = node.next;
} while(node != head);
}
else
{
do
{
if(node.item == null)
{
return node;
}
node = node.next;
} while(node != head);
}
}
return null;
}
public LinkedListNode<T> FindLast( T value )
{
if(head == null) return null;
LinkedListNode<T> last = head.prev;
LinkedListNode<T> node = last;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if(node != null)
{
if(value != null)
{
do
{
if(c.Equals( node.item, value ))
{
return node;
}
node = node.prev;
} while(node != last);
}
else
{
do
{
if(node.item == null)
{
return node;
}
node = node.prev;
} while(node != last);
}
}
return null;
}
public Enumerator GetEnumerator()
{
return new Enumerator( this );
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
public bool Remove( T value )
{
LinkedListNode<T> node = Find( value );
if(node != null)
{
InternalRemoveNode( node );
return true;
}
return false;
}
public void Remove( LinkedListNode<T> node )
{
ValidateNode( node );
InternalRemoveNode( node );
}
public void RemoveFirst()
{
if(head == null) {
throw new InvalidOperationException(); // SR.GetString( SR.LinkedListEmpty ) );
}
InternalRemoveNode( head );
}
public void RemoveLast()
{
if(head == null) {
throw new InvalidOperationException(); // SR.GetString( SR.LinkedListEmpty ) );
}
InternalRemoveNode( head.prev );
}
//// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
//// public virtual void GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// // Customized serialization for LinkedList.
//// // We need to do this because it will be too expensive to Serialize each node.
//// // This will give us the flexiblility to change internal implementation freely in future.
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
//// info.AddValue( VersionName, version );
//// info.AddValue( CountName, count ); //This is the length of the bucket array.
//// if(count != 0)
//// {
//// T[] array = new T[Count];
//// CopyTo( array, 0 );
//// info.AddValue( ValuesName, array, typeof( T[] ) );
//// }
//// }
////
//// public virtual void OnDeserialization( Object sender )
//// {
//// if(siInfo == null)
//// {
//// return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
//// }
////
//// int realVersion = siInfo.GetInt32( VersionName );
//// int count = siInfo.GetInt32( CountName );
////
//// if(count != 0)
//// {
//// T[] array = (T[])siInfo.GetValue( ValuesName, typeof( T[] ) );
////
//// if(array == null)
//// {
//// throw new SerializationException( SR.GetString( SR.Serialization_MissingValues ) );
//// }
//// for(int i = 0; i < array.Length; i++)
//// {
//// AddLast( array[i] );
//// }
//// }
//// else
//// {
//// head = null;
//// }
////
//// version = realVersion;
//// siInfo = null;
//// }
private void InternalInsertNodeBefore( LinkedListNode<T> node, LinkedListNode<T> newNode )
{
newNode.next = node;
newNode.prev = node.prev;
node.prev.next = newNode;
node.prev = newNode;
version++;
count++;
}
private void InternalInsertNodeToEmptyList( LinkedListNode<T> newNode )
{
//Debug.Assert( head == null && count == 0, "LinkedList must be empty when this method is called!" );
newNode.next = newNode;
newNode.prev = newNode;
head = newNode;
version++;
count++;
}
internal void InternalRemoveNode( LinkedListNode<T> node )
{
//Debug.Assert( node.list == this, "Deleting the node from another list!" );
//Debug.Assert( head != null, "This method shouldn't be called on empty list!" );
if(node.next == node)
{
//Debug.Assert( count == 1 && head == node, "this should only be true for a list with only one node" );
head = null;
}
else
{
node.next.prev = node.prev;
node.prev.next = node.next;
if(head == node)
{
head = node.next;
}
}
node.Invalidate();
count--;
version++;
}
internal void ValidateNewNode( LinkedListNode<T> node )
{
if(node == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "node" );
#else
throw new ArgumentNullException();
#endif
}
if(node.list != null)
{
throw new InvalidOperationException(); // SR.GetString( SR.LinkedListNodeIsAttached ) );
}
}
internal void ValidateNode( LinkedListNode<T> node )
{
if(node == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "node" );
#else
throw new ArgumentNullException();
#endif
}
if(node.list != this)
{
throw new InvalidOperationException(); // SR.GetString( SR.ExternalLinkedListNode ) );
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return false;
}
}
object System.Collections.ICollection.SyncRoot
{
get
{
if(_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange( ref _syncRoot, new Object(), null );
}
return _syncRoot;
}
}
void System.Collections.ICollection.CopyTo( Array array, int index )
{
if(array == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "array" );
#else
throw new ArgumentNullException();
#endif
}
if(array.Rank != 1)
{
throw new ArgumentException(); // SR.GetString( SR.Arg_MultiRank ) );
}
if(array.GetLowerBound( 0 ) != 0)
{
throw new ArgumentException(); // SR.GetString( SR.Arg_NonZeroLowerBound ) );
}
if(index < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index" ); //, SR.GetString( SR.IndexOutOfRange, index ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(array.Length - index < Count)
{
throw new ArgumentException(); // SR.GetString( SR.Arg_InsufficientSpace ) );
}
T[] tArray = array as T[];
if(tArray != null)
{
CopyTo( tArray, index );
}
else
{
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof( T );
if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType )))
{
throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) );
}
object[] objects = array as object[];
if(objects == null)
{
throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) );
}
LinkedListNode<T> node = head;
try
{
if(node != null)
{
do
{
objects[index++] = node.item;
node = node.next;
} while(node != head);
}
}
catch(ArrayTypeMismatchException)
{
throw new ArgumentException(); // SR.GetString( SR.Invalid_Array_Type ) );
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[Serializable()]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator/*, ISerializable, IDeserializationCallback*/
{
private LinkedList<T> list;
private LinkedListNode<T> node;
private int version;
private T current;
private int index;
//// private SerializationInfo siInfo; //A temporary variable which we need during deserialization.
////
//// const string LinkedListName = "LinkedList";
//// const string CurrentValueName = "Current";
//// const string VersionName = "Version";
//// const string IndexName = "Index";
////
internal Enumerator( LinkedList<T> list )
{
this.list = list;
version = list.version;
node = list.head;
current = default( T );
index = 0;
//// siInfo = null;
}
//// internal Enumerator( SerializationInfo info, StreamingContext context )
//// {
//// siInfo = info;
//// list = null;
//// version = 0;
//// node = null;
//// current = default( T );
//// index = 0;
//// }
public T Current
{
get { return current; }
}
object System.Collections.IEnumerator.Current
{
get
{
if(index == 0 || (index == list.Count + 1))
{
ThrowHelper.ThrowInvalidOperationException( ExceptionResource.InvalidOperation_EnumOpCantHappen );
}
return current;
}
}
public bool MoveNext()
{
if(version != list.version)
{
throw new InvalidOperationException(); // SR.GetString( SR.InvalidOperation_EnumFailedVersion ) );
}
if(node == null)
{
index = list.Count + 1;
return false;
}
++index;
current = node.item;
node = node.next;
if(node == list.head)
{
node = null;
}
return true;
}
void System.Collections.IEnumerator.Reset()
{
if(version != list.version)
{
throw new InvalidOperationException(); // SR.GetString( SR.InvalidOperation_EnumFailedVersion ) );
}
current = default( T );
node = list.head;
index = 0;
}
public void Dispose()
{
}
//// void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// info.AddValue( LinkedListName, list );
//// info.AddValue( VersionName, version );
//// info.AddValue( CurrentValueName, current );
//// info.AddValue( IndexName, index );
//// }
////
//// void IDeserializationCallback.OnDeserialization( Object sender )
//// {
//// if(list != null)
//// {
//// return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
//// }
////
//// if(siInfo == null)
//// {
//// throw new SerializationException( SR.GetString( SR.Serialization_InvalidOnDeser ) );
//// }
////
//// list = (LinkedList<T>)siInfo.GetValue( LinkedListName, typeof( LinkedList<T> ) );
//// version = siInfo.GetInt32( VersionName );
//// current = (T)siInfo.GetValue( CurrentValueName, typeof( T ) );
//// index = siInfo.GetInt32( IndexName );
////
//// if(list.siInfo != null)
//// {
//// list.OnDeserialization( sender );
//// }
////
//// if(index == list.Count + 1)
//// { // end of enumeration
//// node = null;
//// }
//// else
//// {
//// node = list.First;
//// // We don't care if we can point to the correct node if the LinkedList was changed
//// // MoveNext will throw upon next call and Current has the correct value.
//// if(node != null && index != 0)
//// {
//// for(int i = 0; i < index; i++)
//// {
//// node = node.next;
//// }
//// if(node == list.First)
//// {
//// node = null;
//// }
//// }
//// }
//// siInfo = null;
//// }
}
}
// Note following class is not serializable since we customized the serialization of LinkedList.
public sealed class LinkedListNode<T>
{
internal LinkedList<T> list;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
internal T item;
public LinkedListNode( T value )
{
this.item = value;
}
internal LinkedListNode( LinkedList<T> list ,
T value )
{
this.list = list;
this.item = value;
}
public LinkedList<T> List
{
get
{
return list;
}
}
public LinkedListNode<T> Next
{
get
{
return next == null || next == list.head ? null : next;
}
}
public LinkedListNode<T> Previous
{
get
{
return prev == null || this == list.head ? null : prev;
}
}
public T Value
{
get
{
return item;
}
set
{
item = value;
}
}
internal void Invalidate()
{
list = null;
next = null;
prev = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using Codentia.Common.Data;
using Codentia.Common.Reporting.DL;
using Microsoft.Reporting.WebForms;
namespace Codentia.Common.Reporting.BL
{
/// <summary>
/// CEReportDataSource class
/// </summary>
public class CEReportDataSource
{
private string _reportDataSourceCode = string.Empty;
private string _reportDataSourceSP = string.Empty;
private int _reportDataSourceId;
private Dictionary<string, CEReportParameter> _mitReportParameters = new Dictionary<string, CEReportParameter>();
private DbParameter[] _sqlParams = null;
private ReportParameter[] _repParams = null;
private bool _isDirty = true;
/// <summary>
/// Initializes a new instance of the <see cref="CEReportDataSource"/> class.
/// </summary>
/// <param name="reportDataSourceId">The report data source id.</param>
/// <param name="reportDataSourceCode">The report data source code.</param>
/// <param name="reportDataSourceSP">The report data source SP.</param>
public CEReportDataSource(int reportDataSourceId, string reportDataSourceCode, string reportDataSourceSP)
{
_reportDataSourceId = reportDataSourceId;
_reportDataSourceCode = reportDataSourceCode;
_reportDataSourceSP = reportDataSourceSP;
LoadParameters();
}
/// <summary>
/// Gets the CEReportParameters
/// </summary>
public Dictionary<string, CEReportParameter> CEReportParameters
{
get
{
return _mitReportParameters;
}
}
/// <summary>
/// Gets the ResultTable
/// </summary>
public DataTable ResultTable
{
get
{
UpdateArrays();
DataTable dt = ReportingData.RunReportProc(_reportDataSourceSP, _sqlParams);
dt.TableName = _reportDataSourceCode;
return dt;
}
}
/// <summary>
/// Gets the DbParameters
/// </summary>
public DbParameter[] DbParameters
{
get
{
return _sqlParams;
}
}
/// <summary>
/// Gets the ReportParameter
/// </summary>
public ReportParameter[] ReportParameters
{
get
{
return _repParams;
}
}
/// <summary>
/// Gets the ReportDataSourceCode
/// </summary>
public string ReportDataSourceCode
{
get
{
return _reportDataSourceCode;
}
}
/// <summary>
/// Gets the ReportDataSourceSP
/// </summary>
public string ReportDataSourceSP
{
get
{
return _reportDataSourceSP;
}
}
/// <summary>
/// Gets the ReportDataSourceId
/// </summary>
public int ReportDataSourceId
{
get
{
return _reportDataSourceId;
}
}
/// <summary>
/// Gets a value indicating whether ParametersAreRendered
/// </summary>
public bool ParametersAreRendered
{
get
{
IEnumerator<string> ieRP = _mitReportParameters.Keys.GetEnumerator();
while (ieRP.MoveNext())
{
CEReportParameter rp = _mitReportParameters[ieRP.Current];
if (_mitReportParameters.Count > 0)
{
if (rp.IsRendered)
{
return true;
}
}
}
return false;
}
}
/// <summary>
/// Set Parameter Value
/// </summary>
/// <param name="paramCode">code of Param</param>
/// <param name="paramValue">value of Param</param>
public void SetParameterValue(string paramCode, object paramValue)
{
CEReportParameter rp = _mitReportParameters[paramCode];
rp.Value = paramValue;
_isDirty = true;
}
private void LoadParameters()
{
DataTable dt = ReportingData.GetParametersForDataSource(_reportDataSourceId);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
string paramCode = Convert.ToString(dr["ReportParameterCode"]);
string paramName = Convert.ToString(dr["ReportParameterName"]);
string paramCaption = Convert.ToString(dr["ReportParameterCaption"]);
string sourceSP = Convert.ToString(dr["ReportParameterSourceSP"]);
string sourceValues = Convert.ToString(dr["ReportParameterSourceValues"]);
string rptParamTypeCode = Convert.ToString(dr["ReportParameterTypeCode"]);
string sqlDBTypeCode = Convert.ToString(dr["SqlDbTypeCode"]);
int sqlDBTypeSize = Convert.ToInt32(dr["SqlDbTypeSize"]);
string defaultValue = Convert.ToString(dr["DefaultValue"]);
bool isNullAllowed = Convert.ToBoolean(dr["IsNullAllowed"]);
string errorMessageCaption = Convert.ToString(dr["ErrorMessageCaption"]);
bool isRendered = Convert.ToBoolean(dr["IsRendered"]);
if (!isNullAllowed && string.IsNullOrEmpty(errorMessageCaption))
{
errorMessageCaption = "Parameter value is incorrect";
}
CEReportParameter param = new CEReportParameter(paramCode, paramName, paramCaption, sqlDBTypeCode, sqlDBTypeSize, rptParamTypeCode, sourceSP, sourceValues, defaultValue, isNullAllowed, errorMessageCaption, isRendered);
_mitReportParameters.Add(string.Format("{0}_{1}", _reportDataSourceCode, paramCode), param);
}
}
}
/// <summary>
/// Update Arrays
/// </summary>
private void UpdateArrays()
{
if (_isDirty)
{
// Set or refresh parameter arrays
DbParameter[] spArray = new DbParameter[_mitReportParameters.Count];
ReportParameter[] repArray = new ReportParameter[_mitReportParameters.Count];
IEnumerator<string> ie = _mitReportParameters.Keys.GetEnumerator();
int i = 0;
while (ie.MoveNext())
{
spArray[i] = _mitReportParameters[ie.Current].DbParameter;
repArray[i] = _mitReportParameters[ie.Current].ReportParameter;
i++;
}
_sqlParams = spArray;
_repParams = repArray;
_isDirty = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
using System.Collections.Generic;
using System.Text;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
private byte[] providerMetadata;
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException("eventSourceName");
}
Contract.EndContractBlock();
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
[SecuritySafeCritical]
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
var data = new EmptyStruct();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
[SecuritySafeCritical]
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var data = new EmptyStruct();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
ref data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if !ES_BUILD_PCL
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
eventTypes.typeInfos[i].WriteObjectData(TraceLoggingDataCollector.Instance, values[i]);
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
[SecuritySafeCritical]
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size;
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
}
[SecuritySafeCritical]
private unsafe void WriteImpl<T>(
string eventName,
ref EventSourceOptions options,
ref T data,
Guid* pActivityId,
Guid* pRelatedActivityId)
{
try
{
var eventTypes = SimpleEventTypes<T>.Instance;
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if !ES_BUILD_PCL
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
eventTypes.typeInfo.WriteData(TraceLoggingDataCollector.Instance, ref data);
this.WriteEventRaw(
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
//
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfo.GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch(Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
}
[SecurityCritical]
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DisptachToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if !ES_BUILD_PCL
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[SecurityCritical]
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i != cPins; i++)
{
if (IntPtr.Zero != (IntPtr)pPins[i])
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_"))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
traitNum = 1;
else
throw new ArgumentException(Environment.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length-traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skp spaces between bytes.
{
if (!(i + 1 < value.Length))
throw new ArgumentException(Environment.GetResourceString("EvenHexDigits"), "traits");
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if (' ' <= firstChar) // Is it alphabetic (excludes digits and most punctuation.
metaData.AddRange(Encoding.UTF8.GetBytes(value));
else
throw new ArgumentException(Environment.GetResourceString("IllegalValue", value), "traits");
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
return (c - '0');
if ('a' <= c)
c = unchecked((char) (c - ('a' - 'A'))); // Convert to lower case
if ('A' <= c && c <= 'F')
return (c - 'A' + 10);
throw new ArgumentException(Environment.GetResourceString("BadHexDigit", c), "traits");
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/20/2009 3:52:22 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// PointScheme
/// </summary>
public class PolygonScheme : FeatureScheme, IPolygonScheme
{
#region Private Variables
private PolygonCategoryCollection _categories;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of PointScheme with no categories added to the list yet.
/// </summary>
public PolygonScheme()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the PolygonScheme class.
/// </summary>
/// <param name="fs">THe featureset with the data Table definition to use for symbolizing.</param>
/// <param name="uniqueField">The string name of the field to use
/// when calculating separate color codes. Unique entries will be
/// assigned a random color.</param>
public PolygonScheme(IFeatureSet fs, string uniqueField)
{
GenerateUniqueColors(fs, uniqueField);
}
/// <summary>
/// Calculates the unique colors as a scheme.
/// </summary>
/// <param name="fs">The featureset with the data Table definition.</param>
/// <param name="uniqueField">The unique field.</param>
public Hashtable GenerateUniqueColors(IFeatureSet fs, string uniqueField)
{
return GenerateUniqueColors(fs, uniqueField, color => new PolygonCategory(color, color, 1));
}
private void Configure()
{
_categories = new PolygonCategoryCollection();
OnIncludeCategories(_categories);
PolygonCategory def = new PolygonCategory();
_categories.Add(def);
}
private void CategoriesItemChanged(object sender, EventArgs e)
{
OnItemChanged(sender);
}
#endregion
#region Methods
/// <summary>
/// Draws the regular symbolizer for the specified cateogry to the specified graphics
/// surface in the specified bounding rectangle.
/// </summary>
/// <param name="index">The integer index of the feature to draw.</param>
/// <param name="g">The Graphics object to draw to</param>
/// <param name="bounds">The rectangular bounds to draw in</param>
public override void DrawCategory(int index, Graphics g, Rectangle bounds)
{
Categories[index].Symbolizer.Draw(g, bounds);
}
/// <summary>
/// Adds a new scheme, assuming that the new scheme is the correct type.
/// </summary>
/// <param name="category">The category to add</param>
public override void AddCategory(ICategory category)
{
IPolygonCategory pc = category as IPolygonCategory;
if (pc != null) _categories.Add(pc);
}
/// <summary>
/// Reduces the index value of the specified category by 1 by
/// exchaning it with the category before it. If there is no
/// category before it, then this does nothing.
/// </summary>
/// <param name="category">The category to decrease the index of</param>
public override bool DecreaseCategoryIndex(ICategory category)
{
IPolygonCategory pc = category as IPolygonCategory;
return pc != null && Categories.DecreaseIndex(pc);
}
/// <summary>
/// Re-orders the specified member by attempting to exchange it with the next higher
/// index category. If there is no higher index, this does nothing.
/// </summary>
/// <param name="category">The category to increase the index of</param>
public override bool IncreaseCategoryIndex(ICategory category)
{
IPolygonCategory pc = category as IPolygonCategory;
return pc != null && Categories.IncreaseIndex(pc);
}
/// <summary>
/// Inserts the category at the specified index
/// </summary>
/// <param name="index">The integer index where the category should be inserted</param>
/// <param name="category">The category to insert</param>
public override void InsertCategory(int index, ICategory category)
{
IPolygonCategory pc = category as IPolygonCategory;
if (pc != null) _categories.Insert(index, pc);
}
/// <summary>
/// Removes the specified category
/// </summary>
/// <param name="category">The category to remove</param>
public override void RemoveCategory(ICategory category)
{
IPolygonCategory pc = category as IPolygonCategory;
if (pc != null) _categories.Remove(pc);
}
/// <summary>
/// Suspends the category events
/// </summary>
public override void SuspendEvents()
{
_categories.SuspendEvents();
}
/// <summary>
/// Resumes the category events
/// </summary>
public override void ResumeEvents()
{
_categories.ResumeEvents();
}
/// <summary>
/// Clears the categories
/// </summary>
public override void ClearCategories()
{
_categories.Clear();
}
/// <summary>
/// If possible, use the template to control the colors. Otherwise, just use the default
/// settings for creating "unbounded" colors.
/// </summary>
/// <param name="count">The integer count.</param>
/// <returns>The List of colors</returns>
protected override List<Color> GetDefaultColors(int count)
{
if (EditorSettings != null)
{
IPolygonSymbolizer ps = EditorSettings.TemplateSymbolizer as IPolygonSymbolizer;
if (ps != null)
{
List<Color> result = new List<Color>();
Color c = ps.GetFillColor();
for (int i = 0; i < count; i++)
{
result.Add(c);
}
return result;
}
}
return base.GetDefaultColors(count);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the symbolic categories as a valid IPointSchemeCategoryCollection.
/// </summary>
[Serialize("Categories")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public PolygonCategoryCollection Categories
{
get { return _categories; }
set
{
OnExcludeCategories(_categories);
_categories = value;
OnIncludeCategories(_categories);
}
}
/// <summary>
/// Gets the number of categories in this scheme
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override int NumCategories
{
get
{
if (_categories != null)
{
return _categories.Count;
}
else
{
return 0;
}
}
}
/// <summary>
/// Gets teh categories as an IEnumerable of type IFeatureCategory
/// </summary>
/// <returns></returns>
public override IEnumerable<IFeatureCategory> GetCategories()
{
IEnumerable<IFeatureCategory> result = _categories.Cast<IFeatureCategory>();
return result;
}
/// <summary>
/// Creates the category using a random fill color
/// </summary>
/// <param name="fillColor">The base color to use for creating the category</param>
/// <param name="size">This is ignored for polygons</param>
/// <returns>A new polygon category</returns>
public override ICategory CreateNewCategory(Color fillColor, double size)
{
PolygonCategory result = new PolygonCategory();
if (EditorSettings.UseGradient)
{
result.Symbolizer = new PolygonSymbolizer(fillColor.Lighter(.2f), fillColor.Darker(.2f), EditorSettings.GradientAngle,
GradientType.Linear, fillColor.Darker(.5f), 1);
}
else
{
if (EditorSettings.TemplateSymbolizer != null)
{
result.Symbolizer = EditorSettings.TemplateSymbolizer.Copy() as IPolygonSymbolizer;
result.SetColor(fillColor);
}
else
{
result.Symbolizer = new PolygonSymbolizer(fillColor, fillColor.Darker(.5f));
}
}
return result;
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new IFeatureCategory</returns>
public override IFeatureCategory CreateRandomCategory(string filterExpression)
{
PolygonCategory result = new PolygonCategory();
Color fillColor = CreateRandomColor();
if (EditorSettings.UseGradient)
{
result.Symbolizer = new PolygonSymbolizer(fillColor.Lighter(.2f), fillColor.Darker(.2f), EditorSettings.GradientAngle,
GradientType.Linear, fillColor.Darker(.5f), 1);
}
else
{
result.Symbolizer = new PolygonSymbolizer(fillColor, fillColor.Darker(.5f));
}
result.FilterExpression = filterExpression;
result.LegendText = filterExpression;
return result;
}
/// <summary>
/// Handle the event un-wiring and scheme update for the old categories
/// </summary>
/// <param name="categories">The category collection to update.</param>
protected virtual void OnExcludeCategories(PolygonCategoryCollection categories)
{
if (categories == null) return;
categories.Scheme = null;
categories.ItemChanged -= CategoriesItemChanged;
categories.SelectFeatures -= OnSelectFeatures;
categories.DeselectFeatures -= OnDeselectFeatures;
}
/// <summary>
/// Handle the event wiring and scheme update for the new categories.
/// </summary>
/// <param name="categories">The category collection to update</param>
protected virtual void OnIncludeCategories(PolygonCategoryCollection categories)
{
if (categories == null) return;
categories.Scheme = this;
categories.SelectFeatures += OnSelectFeatures;
categories.DeselectFeatures += OnDeselectFeatures;
categories.ItemChanged += CategoriesItemChanged;
}
#endregion
}
}
| |
//
// Basic test for dependent handles.
//
// Note that though this test uses ConditionalWeakTable it is not a test for that class. This is a stress
// test that utilizes ConditionalWeakTable features, which would be used heavily if Dynamic Language Runtime
// catches on.
//
// Basic test overview:
// * Allocate an array of objects (we call these Nodes) with finalizers.
// * Create a set of dependent handles that reference these objects as primary and secondary members (this is
// where ConditionalWeakTable comes in, adding a key/value pair to such a table creates a dependent handle
// with the primary set to the key and the secondary set to the value).
// * Null out selected objects from the array in various patterns. This removes the only normal strong root
// for such objects (leaving only the dependent handles to provide additional roots).
// * Perform a full GC and wait for it and finalization to complete. Each object which is collected will use
// its finalizer to inform the test that it's been disposed of.
// * Run our own reachability analysis (a simple mark array approach) to build a picture of which objects in
// the array should have been collected or not.
// * Validate that the actual set of live objects matches our computed live set exactly.
//
// Test variations include the number of objects allocated, the relationship between the primary and secondary
// in each handle we allocate and the pattern with which we null out object references in the array.
//
// Additionally this test stresses substantially more complex code paths in the GC if server mode is enabled.
// This can be achieved by setting the environment variable COMPlus_BuildFlavor=svr prior to executing the
// test executable.
//
// Note that we don't go to any lengths to ensure that dependent handle ownership is spread over multiple cpus
// on a server GC/MP test run. For large node counts (e.g. 100000) this happens naturally since initialization
// takes a while with multiple thread/CPU switches involved. We could be more explicit here (allocate handles
// using CPU affinitized threads) but if we do that we'd probably better look into different patterns of node
// ownership to avoid unintentionally restricting our test coverage.
//
// Another area into which we could look deeper is trying to force mark stack overflows in the GC (presumably
// by allocating complex object graphs with lots of interconnections, though I don't the specifics of the best
// way to force this). Causing mark stack overflows should open up a class of bug the old dependent handle
// implementation was subject to without requiring server GC mode or multiple CPUs.
//
using System;
using System.Runtime.CompilerServices;
// How we assign nodes to dependent handles.
enum TableStyle
{
Unconnected, // The primary and secondary handles are assigned completely disjoint objects
ForwardLinked, // The primary of each handle is the secondary of the previous handle
BackwardLinked, // The primary of each handle is the secondary of the next handle
Random // The primaries are each object in sequence, the secondaries are selected randomly from
// the same set
}
// How we choose object references in the array to null out (and thus potentially become collected).
enum CollectStyle
{
None, // Don't null out any (nothing should be collected)
All, // Null them all out (any remaining live objects should be collected)
Alternate, // Null out every second reference
Random // Null out each entry with a 50% probability
}
// We report errors by throwing an exception. Define our own Exception subclass so we can identify these
// errors unambiguously.
class TestException : Exception
{
// We just supply a simple message string on error.
public TestException(string message) : base(message)
{
}
}
// Class encapsulating test runs over a set of objects/handles allocated with the specified TableStyle.
class TestSet
{
// Create a new test with the given table style and object count.
public TestSet(TableStyle ts, int count)
{
// Use one random number generator for the life of the test. Could support explicit seeds for
// reproducible tests here.
m_rng = new Random();
// Remember our parameters.
m_count = count;
m_style = ts;
// Various arrays.
m_nodes = new Node[count]; // The array of objects
m_collected = new bool[count]; // Records whether each object has been collected (entries are set by
// the finalizer on Node)
m_marks = new bool[count]; // Array used during individual test runs to calculate whether each
// object should still be alive (allocated once here to avoid
// injecting further garbage collections at run time)
// Allocate each object (Node). Each knows its own unique ID (the index into the node array) and has a
// back pointer to this test object (so it can phone home to report its own collection at finalization
// time).
for (int i = 0; i < count; i++)
m_nodes[i] = new Node(this, i);
// Determine how many handles we need to allocate given the number of nodes. This varies based on the
// table style.
switch (ts)
{
case TableStyle.Unconnected:
// Primaries and secondaries are completely different objects so we split our nodes in half and
// allocate that many handles.
m_handleCount = count / 2;
break;
case TableStyle.ForwardLinked:
// Nodes are primaries in one handle and secondary in another except one that falls off the end.
// So we have as many handles as nodes - 1.
m_handleCount = count - 1;
break;
case TableStyle.BackwardLinked:
// Nodes are primaries in one handle and secondary in another except one that falls off the end.
// So we have as many handles as nodes - 1.
m_handleCount = count - 1;
break;
case TableStyle.Random:
// Each node is a primary in some handle (secondaries are selected from amongst all the same nodes
// randomly). So we have as many nodes as handles.
m_handleCount = count;
break;
}
// Allocate an array of HandleSpecs. These aren't the real handles, just structures that allow us
// remember what's in each handle (in terms of the node index number for the primary and secondary).
// We need to track this information separately because we can't access the real handles directly
// (ConditionalWeakTable hides them) and we need to recall exactly what the primary and secondary of
// each handle is so we can compute our own notion of object liveness later.
m_handles = new HandleSpec[m_handleCount];
// Initialize the handle specs to assign objects to handles based on the table style.
for (int i = 0; i < m_handleCount; i++)
{
int primary = -1, secondary = -1;
switch (ts)
{
case TableStyle.Unconnected:
// Assign adjacent nodes to the primary and secondary of each handle.
primary = i * 2;
secondary = (i * 2) + 1;
break;
case TableStyle.ForwardLinked:
// Primary of each handle is the secondary of the last handle.
primary = i;
secondary = i + 1;
break;
case TableStyle.BackwardLinked:
// Primary of each handle is the secondary of the next handle.
primary = i + 1;
secondary = i;
break;
case TableStyle.Random:
// Primary is each node in sequence, secondary is any of the nodes randomly.
primary = i;
secondary = m_rng.Next(m_handleCount);
break;
}
m_handles[i].Set(primary, secondary);
}
// Allocate a ConditionalWeakTable mapping Node keys to Node values.
m_table = new ConditionalWeakTable<Node, Node>();
// Using our handle specs computed above add each primary/secondary node pair to the
// ConditionalWeakTable in turn. This causes the ConditionalWeakTable to allocate a dependent handle
// for each entry with the primary and secondary objects we specified as keys and values (note that
// this scheme prevents us from creating multiple handles with the same primary though if this is
// desired we could achieve it by allocating multiple ConditionalWeakTables).
for (int i = 0; i < m_handleCount; i++)
m_table.Add(m_nodes[m_handles[i].m_primary], m_nodes[m_handles[i].m_secondary]);
}
// Call this method to indicate a test error with a given message. This will terminate the test
// immediately.
void Error(string message)
{
throw new TestException(message);
}
// Run a single test pass on the node set. Null out node references according to the given CollectStyle,
// run a garbage collection and then verify that each node is either live or dead as we predict. Take care
// of the order in which test runs are made against a single TestSet: e.g. running a CollectStyle.All will
// collect all nodes, rendering further runs relatively uninteresting.
public void Run(CollectStyle cs)
{
Console.WriteLine("Running test TS:{0} CS:{1} {2} entries...",
Enum.GetName(typeof(TableStyle), m_style),
Enum.GetName(typeof(CollectStyle), cs),
m_count);
// Iterate over the array of nodes deciding for each whether to sever the reference (null out the
// entry).
for (int i = 0; i < m_count; i++)
{
bool sever = false;
switch (cs)
{
case CollectStyle.All:
// Sever all references.
sever = true;
break;
case CollectStyle.None:
// Don't sever any references.
break;
case CollectStyle.Alternate:
// Sever every second reference (starting with the first).
if ((i % 2) == 0)
sever = true;
break;
case CollectStyle.Random:
// Sever any reference with a 50% probability.
if (m_rng.Next(100) > 50)
sever = true;
break;
}
if (sever)
m_nodes[i] = null;
}
// Initialize a full GC and wait for all finalizers to complete (so we get an accurate picture of
// which nodes were collected).
GC.Collect();
GC.WaitForPendingFinalizers();
// Calculate our own view of which nodes should be alive or dead. Use a simple mark array for this.
// Once the algorithm is complete a true value at a given index in the array indicates a node that
// should still be alive, otherwise the node should have been collected.
// Initialize the mark array. Set true for nodes we still have a strong reference to from the array
// (these should definitely not have been collected yet). Set false for the other nodes (we assume
// they must have been collected until we prove otherwise).
for (int i = 0; i < m_count; i++)
m_marks[i] = m_nodes[i] != null;
// Perform multiple passes over the handles we allocated (or our recorded version of the handles at
// least). If we find a handle with a marked (live) primary where the secondary is not yet marked then
// go ahead and mark that secondary (dependent handles are defined to do this: primaries act as if
// they have a strong reference to the secondary up until the point they are collected). Repeat this
// until we manage a scan over the entire table without marking any additional nodes as live. At this
// point the marks array should reflect which objects are still live.
while (true)
{
// Assume we're not going any further nodes to mark as live.
bool marked = false;
// Look at each handle in turn.
for (int i = 0; i < m_handleCount; i++)
if (m_marks[m_handles[i].m_primary])
{
// Primary is live.
if (!m_marks[m_handles[i].m_secondary])
{
// Secondary wasn't marked as live yet. Do so and remember that we marked at least
// node as live this pass (so we need to loop again since this secondary could be the
// same as a primary earlier in the table).
m_marks[m_handles[i].m_secondary] = true;
marked = true;
}
}
// Terminate the loop if we scanned the entire table without marking any additional nodes as live
// (since additional scans can't make any difference).
if (!marked)
break;
}
// Validate our view of node liveness (m_marks) correspond to reality (m_nodes and m_collected).
for (int i = 0; i < m_count; i++)
{
// Catch nodes which still have strong references but have collected anyway. This is stricly a
// subset of the next test but it would be a very interesting bug to call out.
if (m_nodes[i] != null && m_collected[i])
Error(String.Format("Node {0} was collected while it still had a strong root", i));
// Catch nodes which we compute as alive but have been collected.
if (m_marks[i] && m_collected[i])
Error(String.Format("Node {0} was collected while it was still reachable", i));
// Catch nodes which we compute as dead but haven't been collected.
if (!m_marks[i] && !m_collected[i])
Error(String.Format("Node {0} wasn't collected even though it was unreachable", i));
}
}
// Method called by nodes when they're finalized (i.e. the node has been collected).
public void Collected(int id)
{
// Catch nodes which are collected twice.
if (m_collected[id])
Error(String.Format("Node {0} collected twice", id));
m_collected[id] = true;
}
// Structure used to record the primary and secondary nodes in every dependent handle we allocated. Nodes
// are identified by ID (their index into the node array).
struct HandleSpec
{
public int m_primary;
public int m_secondary;
public void Set(int primary, int secondary)
{
m_primary = primary;
m_secondary = secondary;
}
}
int m_count; // Count of nodes in array
TableStyle m_style; // Style of handle creation
Node[] m_nodes; // Array of nodes
bool[] m_collected; // Array indicating which nodes have been collected
bool[] m_marks; // Array indicating which nodes should be live
ConditionalWeakTable<Node, Node> m_table; // Table that creates and holds our dependent handles
int m_handleCount; // Number of handles we create
HandleSpec[] m_handles; // Array of descriptions of each handle
Random m_rng; // Random number generator
}
// The type of object we reference from our dependent handles. Doesn't do much except report its own garbage
// collection to the owning TestSet.
class Node
{
// Allocate a node and remember our owner (TestSet) and ID (index into node array).
public Node(TestSet owner, int id)
{
m_owner = owner;
m_id = id;
}
// On finalization report our collection to the owner TestSet.
~Node()
{
m_owner.Collected(m_id);
}
TestSet m_owner; // TestSet which created us
int m_id; // Our index into above TestSet's node array
}
// The test class itself.
class DhTest1
{
// Entry point.
public static int Main()
{
// The actual test runs are controlled from RunTest. True is returned if all succeeded, false
// otherwise.
if (new DhTest1().RunTest())
{
Console.WriteLine("Test PASS");
return 100;
}
else
{
Console.WriteLine("Test FAIL");
return 999;
}
}
// Run a series of tests with different table and collection styles.
bool RunTest()
{
// Number of nodes we'll allocate in each run (we could take this as an argument instead).
int numNodes = 10000;
// Run everything under an exception handler since test errors are reported as exceptions.
try
{
// Run a pass with each table style. For each style run through the collection styles in the order
// None, Alternate, Random and All. This sequence is carefully selected to remove progressively
// more nodes from the array (since, within a given TestSet instance, once a node has actually
// been collected it won't be resurrected for future runs).
TestSet ts1 = new TestSet(TableStyle.Unconnected, numNodes);
ts1.Run(CollectStyle.None);
ts1.Run(CollectStyle.Alternate);
ts1.Run(CollectStyle.Random);
ts1.Run(CollectStyle.All);
TestSet ts2 = new TestSet(TableStyle.ForwardLinked, numNodes);
ts2.Run(CollectStyle.None);
ts2.Run(CollectStyle.Alternate);
ts2.Run(CollectStyle.Random);
ts2.Run(CollectStyle.All);
TestSet ts3 = new TestSet(TableStyle.BackwardLinked, numNodes);
ts3.Run(CollectStyle.None);
ts3.Run(CollectStyle.Alternate);
ts3.Run(CollectStyle.Random);
ts3.Run(CollectStyle.All);
TestSet ts4 = new TestSet(TableStyle.Random, numNodes);
ts4.Run(CollectStyle.None);
ts4.Run(CollectStyle.Alternate);
ts4.Run(CollectStyle.Random);
ts4.Run(CollectStyle.All);
}
catch (TestException te)
{
// "Expected" errors.
Console.WriteLine("TestError: {0}", te.Message);
return false;
}
catch (Exception e)
{
// Totally unexpected errors (probably shouldn't see these unless there's a test bug).
Console.WriteLine("Unexpected exception: {0}", e.GetType().Name);
return false;
}
// If we get as far as here the test succeeded.
return true;
}
}
| |
using System.Diagnostics.CodeAnalysis;
namespace System.Activities.Presentation.PropertyEditing
{
using System.ComponentModel;
using System.Collections;
using System;
using System.Diagnostics;
using System.Activities.Presentation;
/// <summary>
/// The PropertyEntry class provides additional, mostly type-specific data for a property.
/// </summary>
public abstract class PropertyEntry : INotifyPropertyChanged, IPropertyFilterTarget {
private PropertyValue _parentValue;
private bool _matchesFilter = true;
private PropertyValue _value;
/// <summary>
/// Creates a PropertyEntry. For host infrastructure derived classes.
/// </summary>
protected PropertyEntry() : this(null) { }
/// <summary>
/// Creates a PropertyEntry that acts as a sub-property of the specified PropertyValue.
/// For host infrastructure derived classes.
/// </summary>
/// <param name="parentValue">The parent PropertyValue.
/// Root properties do not have a parent PropertyValue.</param>
protected PropertyEntry(PropertyValue parentValue) {
_parentValue = parentValue;
}
/// <summary>
/// Gets the name of the encapsulated property.
/// </summary>
public abstract string PropertyName { get; }
/// <summary>
/// Gets the DisplayName for the property. By default, it is the
/// PropertyName.
/// </summary>
public virtual string DisplayName { get { return this.PropertyName; } }
/// <summary>
/// Gets the Type of the encapsulated property.
/// </summary>
public abstract Type PropertyType { get; }
/// <summary>
/// Gets the name of the category that this property resides in.
/// </summary>
public abstract string CategoryName { get; }
/// <summary>
/// Gets the description of the encapsulated property.
/// </summary>
public abstract string Description { get; }
/// <summary>
/// Returns true if there are standard values for this property.
/// The default implementation checks if the StandardValues property
/// returns a non-null collection with a count > 0.
/// </summary>
protected virtual bool HasStandardValues {
get {
ICollection values = StandardValues;
return values != null && values.Count > 0;
}
}
/// <summary>
/// Accessor because we use this property in the property container.
/// </summary>
internal bool HasStandardValuesInternal {
get { return HasStandardValues; }
}
/// <summary>
/// Gets the read-only attribute of the encapsulated property.
/// </summary>
public abstract bool IsReadOnly { get; }
/// <summary>
/// Gets a flag indicating whether the encapsulated property is an advanced property.
/// </summary>
public abstract bool IsAdvanced { get; }
/// <summary>
/// Gets any StandardValues that the encapsulated property supports.
/// </summary>
public abstract ICollection StandardValues { get; }
/// <summary>
/// Gets to PropertyValueEditor to be used for editing of this PropertyEntry.
/// May be null. PropertyContainer listens to changes made to this property.
/// If the value changes, it's the responsibility of the deriving class to fire the
/// appropriate PropertyChanged event.
/// </summary>
public abstract PropertyValueEditor PropertyValueEditor { get; }
/// <summary>
/// Gets the parent PropertyValue. This is only used for sub-properties and,
/// hence, its balue may be null.
/// </summary>
public PropertyValue ParentValue {
get {
return _parentValue;
}
}
/// <summary>
/// Gets the PropertyValue (data model) for this PropertyEntry.
/// </summary>
public PropertyValue PropertyValue {
get {
if (_value == null)
_value = CreatePropertyValueInstance();
return _value;
}
}
/// <summary>
/// Used by the host infrastructure to create a new host-specific PropertyValue instance.
/// </summary>
/// <returns>new PropertyValue</returns>
protected abstract PropertyValue CreatePropertyValueInstance();
// IPropertyFilterTarget Members
/// <summary>
/// IPropertyFilterTarget event
/// </summary>
public event EventHandler<PropertyFilterAppliedEventArgs> FilterApplied;
/// <summary>
/// IPropertyFilterTarget method. PropertyContainer listens to changes made to this property.
/// </summary>
public bool MatchesFilter {
get {
return _matchesFilter;
}
protected set {
if (value != _matchesFilter) {
_matchesFilter = value;
OnPropertyChanged("MatchesFilter");
}
}
}
/// <summary>
/// IPropertyFilterTarget method
/// </summary>
/// <param name="predicate">the predicate to match against</param>
/// <returns>true if there is a match</returns>
public virtual bool MatchesPredicate(PropertyFilterPredicate predicate) {
return predicate == null ?
false :
predicate.Match(this.DisplayName) || predicate.Match(this.PropertyType.Name);
}
/// <summary>
/// IPropertyFilterTarget method
/// </summary>
/// <param name="filter">the PropertyFilter to apply</param>
public virtual void ApplyFilter(PropertyFilter filter) {
this.MatchesFilter = filter == null ? true : filter.Match(this);
OnFilterApplied(filter);
}
/// <summary>
/// Used to raise the IPropertyFilterTarget FilterApplied event
/// </summary>
/// <param name="filter"></param>
protected virtual void OnFilterApplied(PropertyFilter filter) {
if (FilterApplied != null)
FilterApplied(this, new PropertyFilterAppliedEventArgs(filter));
}
// INotifyPropertyChanged
/// <summary>
/// INotifyPropertyChanged event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Used to raise the INotifyPropertyChanged PropertyChanged event
/// </summary>
/// <param name="e">EventArgs for this event</param>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
if (e == null)
throw FxTrace.Exception.ArgumentNull("e");
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
/// <summary>
/// Used to raise the INotifyPropertyChanged event
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">When propertyName is null</exception>
protected virtual void OnPropertyChanged(string propertyName) {
if (propertyName == null)
throw FxTrace.Exception.ArgumentNull("propertyName");
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Xml;
namespace XMLTests.ReaderWriter.ReadContentTests
{
public class DateTimeTests
{
[Fact]
public static void ReadContentAsDateTime1()
{
var reader = Utils.CreateFragmentReader("<Root>0001-<![CDATA[01]]>-01T0<?a?>0:00:00<!-- Comment inbetween--></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime10()
{
var reader = Utils.CreateFragmentReader("<Root> 20<?a?>02-1<![CDATA[2]]>-3<!-- Comment inbetween-->0 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(2002, 12, 30, 0, 0, 0), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime11()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[2]]>00<?a?>2-1<!-- Comment inbetween-->2-30Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(2002, 12, 30, 0, 0, 0, 0).Add(new TimeSpan(0, 0, 0)), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime12()
{
var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0002-01-01T00:00:00+00:00 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(2, 1, 1, 0, 0, 0).Add(TimeZoneInfo.Local.GetUtcOffset(new DateTime(2, 1, 1))), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime13()
{
var reader = Utils.CreateFragmentReader("<Root>001-01-01T00:00:00+00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime14()
{
var reader = Utils.CreateFragmentReader("<Root>99<?a?>99-12-31T12:59:59+14:00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime15()
{
var reader = Utils.CreateFragmentReader("<Root>0<?a?></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime16()
{
var reader = Utils.CreateFragmentReader("<Root> 9<?a?>999 Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime17()
{
var reader = Utils.CreateFragmentReader("<Root> ABC<?a?>D </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime18()
{
var reader = Utils.CreateFragmentReader("<Root>yyy<?a?>y-MM-ddTHH:mm</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime19()
{
var reader = Utils.CreateFragmentReader("<Root>21<?a?>00-02-29T23:59:59.9999999+13:60 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime2()
{
var reader = Utils.CreateFragmentReader("<Root>99<!-- Comment inbetween-->99-1<?a?>2-31T1<![CDATA[2]]>:59:59</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(9999, 12, 31, 12, 59, 59), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime20()
{
var reader = Utils.CreateFragmentReader("<Root>3 000-0<?a?>2-29T23:59:59.999999999999-13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime21()
{
var reader = Utils.CreateFragmentReader("<Root>2002-12-33</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime22()
{
var reader = Utils.CreateFragmentReader("<Root >2002-13-30 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime3()
{
var reader = Utils.CreateFragmentReader("<Root> 0<?a?>0:0<!-- Comment inbetween-->0:00+00:00 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, DateTimeKind.Utc).ToLocalTime(), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime4()
{
var reader = Utils.CreateFragmentReader("<Root>00<!-- Comment inbetween-->01</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime5()
{
var reader = Utils.CreateFragmentReader("<Root> 999<!-- Comment inbetween-->9 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(9999, 1, 1, 0, 0, 0), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime6()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[0]]>001Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, 0).Add(new TimeSpan(0, 0, 0)), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime7()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[9]]>999Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(9999, 1, 1, 0, 0, 0, 0).Add(new TimeSpan(0, 0, 0)), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime8()
{
var reader = Utils.CreateFragmentReader("<Root> 2000-0<![CDATA[2]]>-29T23:59:59.999<?a?>9999 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(2000, 2, 29, 23, 59, 59).AddTicks(9999999), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTime9()
{
var reader = Utils.CreateFragmentReader("<Root> 2<?a?>00<!-- Comment inbetween-->0-02-29T23:59:5<?a?>9-13:<![CDATA[60]]> </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTime(2000, 2, 29, 23, 59, 59).Add(TimeZoneInfo.Local.GetUtcOffset(new DateTime(2000, 2, 29)) + new TimeSpan(14, 0, 0)), (DateTime)reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRange1()
{
var reader = Utils.CreateFragmentReader(@"<doc> 99<!-- Comment inbetween-->99-1<![CDATA[2]]>-31T01:60:5<?a?>9.99<?a?>9999<![CDATA[4]]>9<?Zz?>-00<![CDATA[:]]>00 </doc>");
reader.PositionOnElementNoDoctype("doc");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRange2()
{
var reader = Utils.CreateFragmentReader(@"<f a='2002-02-29T23:59:59.9999999999999+13:61'/>");
reader.PositionOnElementNoDoctype("f");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRange3()
{
var reader = Utils.CreateFragmentReader(@"<f a='2002-02-29T23:59:59.9999999999999+13:61'/>");
reader.PositionOnElementNoDoctype("f");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRange4()
{
var reader = Utils.CreateFragmentReader(@"<doc> 99<!-- Comment inbetween-->99-1<![CDATA[2]]>-31T01:60:5<?a?>9.99<?a?>9999<![CDATA[4]]>9<?Zz?>-00<![CDATA[:]]>00 </doc>");
reader.PositionOnElementNoDoctype("doc");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRangeDateTimeOffset1()
{
var reader = Utils.CreateFragmentReader(@"<doc> 99<!-- Comment inbetween-->99-1<![CDATA[2]]>-31T01:60:5<?a?>9.99<?a?>9999<![CDATA[4]]>9<?Zz?>-00<![CDATA[:]]>00 </doc>");
reader.PositionOnElementNoDoctype("doc");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeIsOutOfRangeDateTimeOffset2()
{
var reader = Utils.CreateFragmentReader(@"<f a='2002-02-29T23:59:59.9999999999999+13:61'/>");
reader.PositionOnElementNoDoctype("f");
if (!reader.MoveToAttribute("a"))
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeWithWhitespace1()
{
var reader = Utils.CreateFragmentReader(@"<doc> 9999-12-31 </doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
reader.Read();
Assert.Equal(new DateTime(9999, 12, 31, 0, 0, 0), reader.ReadContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadContentAsDateTimeWithWhitespace2()
{
var reader = Utils.CreateFragmentReader(@"<doc> 9999-12-31 </doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
reader.Read();
Assert.Equal(new DateTimeOffset(9999, 12, 31, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(9999, 12, 31))).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Rhapsody.Core.Mpeg;
using Rhapsody.Core.Tags.Ape;
using Rhapsody.Core.Tags.Id3v1;
using Rhapsody.Core.Tags.Id3v2;
using Rhapsody.Core.Tags.Id3v2.Frames;
using Rhapsody.Core.Tags.Lyrics3v2;
using Rhapsody.Utilities;
namespace Rhapsody.Core
{
internal class Track
{
private Context _context;
private Session _session;
private long _mpegDataOffset;
private long _mpegDataSize;
public event EventHandler NameChanged;
public string Name
{
get;
set;
}
public string FileName
{
get
{
return string.Format("{0:00} - {1}.mp3", Index, StringHelper.MakeFileSystemFriendly(Name));
}
}
public FileInfo SourceFile
{
get;
private set;
}
public MpegFileInfo MpegFileInfo
{
get;
private set;
}
public List<ITag> Tags
{
get;
private set;
}
public Disc Disc
{
get;
set;
}
public int Index
{
get
{
return Disc.Tracks.IndexOf(this) + 1;
}
}
public bool IsMpegDataValid
{
get
{
if (!MpegFileInfo.Exists)
return false;
if (MpegFileInfo.Errors.Count > 0)
return false;
if (IsInvalidVbr)
return false;
return true;
}
}
public bool IsAudioVersionValid
{
get
{
return MpegFileInfo.AudioVersion == AudioVersion.Mpeg1;
}
}
public bool IsLayerValid
{
get
{
return MpegFileInfo.Layer == Layer.Layer3;
}
}
public bool IsBitrateValid
{
get
{
return MpegFileInfo.IsVbr || MpegFileInfo.Bitrate >= 128000;
}
}
public bool IsSampleRateValid
{
get
{
return MpegFileInfo.SampleRate >= 44100;
}
}
public bool IsChannelModeValid
{
get
{
return MpegFileInfo.ChannelMode == ChannelMode.JointStereo || MpegFileInfo.ChannelMode == ChannelMode.Stereo;
}
}
public List<TimeSpan> Glitches
{
get
{
return MpegFileInfo.Errors.OfType<MisplacedFrameMpegError>().Select(error => TimeSpan.FromSeconds(Math.Floor(error.Time.TotalSeconds))).Distinct().ToList();
}
}
public bool IsTruncated
{
get
{
return MpegFileInfo.Errors.Any(error => error is LastFrameTruncatedMpegError);
}
}
public bool IsInvalidVbr
{
get
{
return MpegFileInfo.IsVbr && !(MpegFileInfo.HasXingHeader || MpegFileInfo.HasVbriHeader);
}
}
private Track()
{
Tags = new List<ITag>();
}
private Track(Session session, Context context) : this()
{
_session = session;
_context = context;
}
public Track(FileInfo sourceFile, Disc disc, Session session, Context context) : this(session, context)
{
SourceFile = sourceFile;
Disc = disc;
// Find tags
using (var stream = new BufferedStream(sourceFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read)))
{
_mpegDataOffset = 0;
_mpegDataSize = stream.Length;
Stream dataStream;
// Better be sorted from outer to inner
Type[] tagTypes = {
typeof(Id3v2Tag),
typeof(Id3v1Tag),
typeof(Lyrics3v2Tag),
typeof(ApeTag)
};
while (true)
{
dataStream = new SubStream(stream, _mpegDataOffset, _mpegDataSize);
var anyTagFound = false;
foreach (var tagType in tagTypes)
{
var tag = (ITag)Activator.CreateInstance(tagType);
if (!tag.Read(dataStream))
continue;
if (tag.Position == TagPosision.Beginning)
{
_mpegDataOffset += tag.Size;
_mpegDataSize -= tag.Size;
}
else
{
_mpegDataSize -= tag.Size;
}
Tags.Add(tag);
anyTagFound = true;
break;
}
if (!anyTagFound)
break;
}
MpegFileInfo = new MpegFileInfo(dataStream);
}
}
public void SaveTo(DirectoryInfo discDirectory, IProgress progress, CancellationToken cancellationToken)
{
var sourceFilePath = SourceFile.FullName;
var mpegDataOffset = _mpegDataOffset;
var mpegDataSize = _mpegDataSize;
string reEncodedFilePath = null;
if (NeedsReEncoding() && _session.ReEncodeFiles)
{
var encoder = _context.GetEncoder();
reEncodedFilePath = Path.GetTempFileName();
var minBirtate = Disc.MostCommonBitrate != null ? Disc.MostCommonBitrate.Value : MpegFileInfo.MinBitrate;
var maxBirtate = Disc.MostCommonBitrate != null ? Disc.MostCommonBitrate.Value : MpegFileInfo.MaxBitrate;
var sampleRate = Disc.MostCommonSampleRate.Value;
var channelMode = Disc.MostCommonChannelMode.Value;
encoder.Encode(sourceFilePath, reEncodedFilePath, minBirtate, maxBirtate, sampleRate, channelMode);
var tempTrack = new Track(new FileInfo(reEncodedFilePath), null, _session, _context);
mpegDataOffset = tempTrack._mpegDataOffset;
mpegDataSize = tempTrack._mpegDataSize;
sourceFilePath = reEncodedFilePath;
}
using (var sourceStream = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var destinationStream = File.Open(Path.Combine(discDirectory.FullName, FileName), FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
var id3Tagv2 = new Id3Tagv2();
id3Tagv2.Version = new Version(3, 0);
id3Tagv2.Frames.Add(new Tpe1Frame(Disc.Album.ArtistName));
id3Tagv2.Frames.Add(new TyerFrame(Disc.Album.ReleaseYear));
id3Tagv2.Frames.Add(new TalbFrame(Disc.Album.FullName));
id3Tagv2.Frames.Add(new TposFrame(string.Format("{0}/{1}", Disc.Index, Disc.Album.Discs.Count)));
id3Tagv2.Frames.Add(new TrckFrame(string.Format("{0}/{1}", Index, Disc.Tracks.Count)));
id3Tagv2.Frames.Add(new Tit2Frame(Name));
id3Tagv2.Frames.Add(new PrivFrame("RHAPSODY", Encoding.ASCII.GetBytes(string.Format("RHAPSODY/{0}", VersionHelper.GetAppVersion()))));
if (Disc.Album.Cover != null)
id3Tagv2.Frames.Add(new ApicFrame(Disc.Album.Cover, PictureType.FrontCover));
if (!string.IsNullOrEmpty(Disc.Name))
id3Tagv2.Frames.Add(new TsstFrame(Disc.Name));
id3Tagv2.WriteTo(destinationStream);
StreamHelper.Copy(sourceStream, destinationStream, mpegDataOffset, mpegDataSize);
}
}
if (reEncodedFilePath != null)
File.Delete(reEncodedFilePath);
}
private bool NeedsReEncoding()
{
if (IsTruncated)
return true;
if (Glitches.Count > 0)
return true;
if (MpegFileInfo.AudioVersion != AudioVersion.Mpeg1)
return true;
if (MpegFileInfo.Layer != Layer.Layer3)
return true;
if (!MpegFileInfo.IsVbr)
if (MpegFileInfo.Bitrate != Disc.MostCommonBitrate)
return true;
if (MpegFileInfo.SampleRate != Disc.MostCommonSampleRate)
return true;
if (MpegFileInfo.ChannelMode != Disc.MostCommonChannelMode)
return true;
return false;
}
public void Remove()
{
Disc.Tracks.Remove(this);
if (Disc.Tracks.Count == 0)
Disc.Remove();
}
public void OnNameChanged()
{
if (NameChanged != null)
NameChanged(this, EventArgs.Empty);
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Collections.Generic;
using Cassandra.MetadataHelpers;
using NUnit.Framework;
namespace Cassandra.Tests.MetadataHelpers
{
[TestFixture]
public class NetworkTopologyStrategyTests
{
[Test]
public void AreReplicationFactorsSatisfied_Should_ReturnTrue_When_NoHostInDc()
{
var ksReplicationFactor = new Dictionary<string, ReplicationFactor>
{
{"dc1", ReplicationFactor.Parse("1")},
{"dc2", ReplicationFactor.Parse("3")},
{"dc3", ReplicationFactor.Parse("1")}
};
var replicasByDc = new Dictionary<string, int>
{
{"dc1", 1},
{"dc2", 3}
};
//no host in DC 3
var datacenters = new Dictionary<string, DatacenterInfo>
{
{"dc1", new DatacenterInfo { HostLength = 10 } },
{"dc2", new DatacenterInfo { HostLength = 10 } }
};
Assert.True(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters));
}
[Test]
public void AreReplicationFactorsSatisfied_Should_ReturnFalse_When_LessReplicasThanReplicationFactorInOneDc()
{
var ksReplicationFactor = new Dictionary<string, ReplicationFactor>
{
{"dc1", ReplicationFactor.Parse("1")},
{"dc2", ReplicationFactor.Parse("3")},
{"dc3", ReplicationFactor.Parse("1")}
};
var replicasByDc = new Dictionary<string, int>
{
{"dc1", 1},
{"dc2", 1}
};
//no host in DC 3
var datacenters = new Dictionary<string, DatacenterInfo>
{
{"dc1", new DatacenterInfo { HostLength = 10 } },
{"dc2", new DatacenterInfo { HostLength = 10 } }
};
Assert.False(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters));
}
[Test]
public void AreReplicationFactorsSatisfied_Should_ReturnTrue_When_OnlyFullReplicas()
{
var ksReplicationFactor = new Dictionary<string, ReplicationFactor>
{
{"dc1", ReplicationFactor.Parse("1")},
{"dc2", ReplicationFactor.Parse("3/1")},
{"dc3", ReplicationFactor.Parse("1")}
};
var replicasByDc = new Dictionary<string, int>
{
{"dc1", 1},
{"dc2", 2},
{"dc3", 1}
};
//no host in DC 3
var datacenters = new Dictionary<string, DatacenterInfo>
{
{"dc1", new DatacenterInfo { HostLength = 10 } },
{"dc2", new DatacenterInfo { HostLength = 10 } },
{"dc3", new DatacenterInfo { HostLength = 10 } }
};
Assert.True(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters));
}
[Test]
public void AreReplicationFactorsSatisfied_Should_ReturnFalse_When_LessReplicasThanRf()
{
var ksReplicationFactor = new Dictionary<string, ReplicationFactor>
{
{"dc1", ReplicationFactor.Parse("1")},
{"dc2", ReplicationFactor.Parse("3/1")},
{"dc3", ReplicationFactor.Parse("1")}
};
var replicasByDc = new Dictionary<string, int>
{
{"dc1", 1},
{"dc2", 1},
{"dc3", 1}
};
//no host in DC 3
var datacenters = new Dictionary<string, DatacenterInfo>
{
{"dc1", new DatacenterInfo { HostLength = 10 } },
{"dc2", new DatacenterInfo { HostLength = 10 } },
{"dc3", new DatacenterInfo { HostLength = 10 } }
};
Assert.False(NetworkTopologyStrategy.AreReplicationFactorsSatisfied(ksReplicationFactor, replicasByDc, datacenters));
}
[Test]
public void Should_ReturnAppropriateReplicasPerDcPerToken()
{
var target = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/1") },
{ "dc3", ReplicationFactor.Parse("3/2") }
});
var testData = ReplicationStrategyTestData.Create();
var result = target.ComputeTokenToReplicaMap(
testData.Ring, testData.PrimaryReplicas, testData.NumberOfHostsWithTokens, testData.Datacenters);
// 3 dcs, 3 hosts per rack, 3 racks per dc, 10 tokens per host
Assert.AreEqual(10 * 3 * 3 * 3, result.Count);
foreach (var token in result)
{
// 2 for dc1, 2 for dc2, 1 for dc3
Assert.AreEqual(2 + 2 + 1, token.Value.Count);
}
}
[Test]
public void Should_ReturnEqualsTrueAndSameHashCode_When_BothStrategiesHaveSameReplicationSettings()
{
var target1 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/1") },
{ "dc3", ReplicationFactor.Parse("3/2") }
});
var target2 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc3", ReplicationFactor.Parse("3/2") },
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/1") }
});
Assert.AreEqual(target1.GetHashCode(), target2.GetHashCode());
Assert.IsTrue(target1.Equals(target2));
Assert.IsTrue(target2.Equals(target1));
Assert.AreEqual(target1, target2);
}
[Test]
public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentReplicationFactors()
{
var target1 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/1") },
{ "dc3", ReplicationFactor.Parse("3/2") }
});
var target2 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc3", ReplicationFactor.Parse("3/2") },
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/2") }
});
Assert.AreNotEqual(target1.GetHashCode(), target2.GetHashCode());
Assert.IsFalse(target1.Equals(target2));
Assert.IsFalse(target2.Equals(target1));
Assert.AreNotEqual(target1, target2);
}
[Test]
public void Should_NotReturnEqualsTrue_When_StrategiesHaveDifferentDatacenters()
{
var target1 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc1", ReplicationFactor.Parse("2") },
{ "dc2", ReplicationFactor.Parse("3/1") },
});
var target2 = new NetworkTopologyStrategy(
new Dictionary<string, ReplicationFactor>
{
{ "dc1", ReplicationFactor.Parse("2") },
});
Assert.AreNotEqual(target1.GetHashCode(), target2.GetHashCode());
Assert.IsFalse(target1.Equals(target2));
Assert.IsFalse(target2.Equals(target1));
Assert.AreNotEqual(target1, target2);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ClientAppUsingB2C.Server.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_BeginRead_Generic : PortsTest
{
// Set bounds fore random timeout values.
// If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
// If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
// If the percentage difference between the expected timeout and the actual timeout
// found through Stopwatch is greater then 10% then the timeout value was not correctly
// to the read method and the testcase fails.
public const double maxPercentageDifference = .15;
// The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
// The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
// The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
// When we test Read and do not care about actually reading anything we must still
// create an byte array to pass into the method the following is the size of the
// byte array used in this situation
private const int defaultByteArraySize = 1;
private const int NUM_TRYS = 5;
private const int MAX_WAIT_THREAD = 1000;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
Stream serialStream = com.BaseStream;
com.Close();
VerifyReadException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterSerialStreamClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to BaseStream.Close()");
com.Open();
Stream serialStream = com.BaseStream;
com.BaseStream.Close();
VerifyReadException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void TimeoutIsIgnoredForBeginRead()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
com1.Open();
com2.Open();
com1.ReadTimeout = 100;
var mre = new ManualResetEvent(false);
IAsyncResult ar = com1.BaseStream.BeginRead(
new byte[8], 0, 8,
(r) => {
mre.Set();
},
null);
Thread.Sleep(200);
Assert.False(ar.IsCompleted, "Expected read to not have timed out");
com2.Write(new byte[8], 0, 8);
com1.BaseStream.EndRead(ar);
Assert.True(mre.WaitOne(200));
}
}
private void WriteToCom1()
{
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
// Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
if (com2.IsOpen)
com2.Close();
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
var rndGen = new Random(-55);
// if(!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), new System.Text.UTF7Encoding())){
VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), Encoding.Unicode);
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
var rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding());
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(15);
var bytesToWrite = new byte[numRndBytesPairty];
var expectedBytes = new byte[numRndBytesPairty];
var actualBytes = new byte[numRndBytesPairty + 1];
IAsyncResult readAsyncResult;
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
// Generate random characters without an parity error
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedBytes[i] = randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
// Create a parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace;
// Set the last expected byte to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
readAsyncResult = com2.BaseStream.BeginWrite(bytesToWrite, 0, bytesToWrite.Length, null, null);
com2.BaseStream.EndWrite(readAsyncResult);
com1.Read(actualBytes, 0, actualBytes.Length);
// Compare the chars that were written with the ones we expected to read
for (var i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != actualBytes[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i],
(int)actualBytes[i]);
}
}
if (1 < com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
// Clear the parity error on the last byte
expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
var rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
// if(!VerifyBytesToRead(1, new System.Text.UTF7Encoding())){
VerifyBytesToRead(1, Encoding.UTF32);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
var rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead, new UTF8Encoding());
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(Stream serialStream, Type expectedException)
{
Assert.Throws(expectedException, () =>
{
IAsyncResult readAsyncResult = serialStream.BeginRead(new byte[defaultByteArraySize], 0, defaultByteArraySize,
null, null);
readAsyncResult.AsyncWaitHandle.WaitOne();
});
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding());
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numRndBytesPairty];
var expectedBytes = new byte[numRndBytesPairty];
byte expectedByte;
// Generate random characters without an parity error
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedBytes[i] = randByte;
}
if (-1 == parityReplace)
{
// If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
// If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
// Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
// Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedBytes[parityErrorIndex] = (byte)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Encoding = encoding;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
VerifyBytesToRead(numBytesRead, new ASCIIEncoding());
}
private void VerifyBytesToRead(int numBytesRead, Encoding encoding)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
var bytesToWrite = new byte[numRndBytesToRead];
// Generate random characters
for (var i = 0; i < bytesToWrite.Length; i++)
{
var randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Encoding = encoding;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize)
{
var rcvBuffer = new byte[rcvBufferSize];
var buffer = new byte[bytesToWrite.Length];
int totalBytesRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
bytesToRead = com1.BytesToRead;
while (0 != com1.BytesToRead)
{
int bytesRead = com1.BaseStream.EndRead(com1.BaseStream.BeginRead(rcvBuffer, 0, rcvBufferSize, null, null));
// While their are more characters to be read
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
// If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (bytesToWrite.Length < totalBytesRead + bytesRead)
{
// If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
break;
}
Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead);
totalBytesRead += bytesRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
// Compare the bytes that were written with the ones we expected to read
for (var i = 0; i < bytesToWrite.Length; i++)
{
if (expectedBytes[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Text;
using Alachisoft.NosDB.Common.DataStructures;
using Alachisoft.NosDB.Common.DataStructures.Clustered;
using Alachisoft.NosDB.Common.Logger;
using Alachisoft.NosDB.Common.Replication;
using Alachisoft.NosDB.Common.Server.Engine;
using Alachisoft.NosDB.Common.Toplogies.Impl.Distribution;
using Alachisoft.NosDB.Common.Toplogies.Impl.StateTransfer;
using Alachisoft.NosDB.Common.Toplogies.Impl.StateTransfer.Operations;
using Alachisoft.NosDB.Core.Toplogies.Impl.Replication;
namespace Alachisoft.NosDB.Core.Toplogies.Impl.StateTransfer
{
class StateTrxfrOnReplicaTask : StateTransferTask
{
private OperationId _startedFrom;
public StateTrxfrOnReplicaTask(NodeContext context, String dbName, String colName, IDispatcher operationDispatcher, DistributionMethod distributionType)
: base(context,dbName,colName,operationDispatcher,StateTransferType.INTRA_SHARD,distributionType)
{
_allowBulkInSparsedBuckets = false;
_trasferType = StateTransferType.INTRA_SHARD;
}
/// <summary>
/// Remove Log Table from oplog for provided bucket id
/// </summary>
/// <param name="bucketID"></param>
//private void RemoveLoggedOperations(int bucketID)
//{
// IStateTransferOperation operation = this.CreateStateTransferOperation(StateTransferOpCode.RemoveLoggedOperations);
// operation.Params.SetParamValue(ParamName.BucketID, bucketID);
// operationDispatcher.DispatchOperation<Object>(operation);
//}
protected override void EndBucketsStateTxfr(ArrayList buckets)
{
if (buckets != null)
{
LoggingIdentity identity=new LoggingIdentity(taskIdentity.DBName, taskIdentity.ColName, (int)buckets[0]);
StopLoggingOnReplica(identity);
ICollection loggedOperations = GetLoggedOperations(_startedFrom, identity);
//STD: Apply logged operations on collection
ApplyLogOperation(loggedOperations as ClusteredArrayList);
RemoveLoggedOperations((int)buckets[0]);
}
}
/// <summary>
/// Updates the state transfer task in synchronus way. It adds/remove buckets
/// to be transferred by the state transfer task.
/// </summary>
/// <param name="myBuckets"></param>
public override bool UpdateStateTransfer(ArrayList myBuckets, int updateId)
{
if (_databasesManager != null && _databasesManager.HasDisposed(taskIdentity.DBName, taskIdentity.ColName)/* _parent.HasDisposed*/)
return false;
StringBuilder sb = new StringBuilder();
lock (_updateIdMutex)
{
if (updateId != updateCount)
{
if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsInfoEnabled)
LoggerManager.Instance.StateXferLogger.Info(loggingModule + "UpdateStateTxfr", " Do not need to update the task as update id does not match; provided id :" + updateId + " currentId :" + updateCount);
return false;
}
}
lock (_stateTxfrMutex)
{
try
{
if (myBuckets != null)
{
if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsInfoEnabled)
LoggerManager.Instance.StateXferLogger.Info(loggingModule + ".UpdateStateTxfr", " my buckets " + myBuckets.Count);
//we work on the copy of the map.
ArrayList buckets = myBuckets.Clone() as ArrayList;
ArrayList leavingShards = new ArrayList();
//if (_sparsedBuckets != null && _sparsedBuckets.Count > 0)
//{
// //ArrayList tmp = _sparsedBuckets.Clone() as ArrayList;
// IEnumerator e = _sparsedBuckets.GetEnumerator();
// lock (_sparsedBuckets.SyncRoot)
// {
// while (e.MoveNext())
// {
// BucketsPack bPack = (BucketsPack)e.Current;
// ArrayList bucketIds = bPack.BucketIds.Clone() as ArrayList;
// foreach (int bucketId in bucketIds)
// {
// HashMapBucket current = new HashMapBucket(null, bucketId);
// if (!buckets.Contains(current))
// {
// ((BucketsPack)e.Current).BucketIds.Remove(bucketId);
// }
// else
// {
// HashMapBucket bucket = buckets[buckets.IndexOf(current)] as HashMapBucket;
// if (!bPack.Owner.Equals(new NodeIdentity(bucket.CurrentShard, GetShardPrimary(bucket.CurrentShard))))
// {
// //either i have become owner of the bucket or
// //some one else for e.g a replica node
// if (logger != null && logger.IsInfoEnabled)
// logger.Info(loggingModule + ".UpdateStateTxfer", bucket.BucketId + "bucket owner changed old :" + bPack.Owner + " new :" + bucket.CurrentShard);
// bPack.BucketIds.Remove(bucketId);
// }
// }
// }
// if (bPack.BucketIds.Count == 0)
// {
// //This owner has left.
// leavingShards.Add(bPack.Owner);
// }
// }
// foreach (NodeIdentity leavingShard in leavingShards)
// {
// BucketsPack bPack = new BucketsPack(null, leavingShard);
// _sparsedBuckets.Remove(bPack);
// }
// leavingShards.Clear();
// }
//}
if (_filledBuckets != null && _filledBuckets.Count > 0)
{
//ArrayList tmp = _filledBuckets.Clone() as ArrayList;
IEnumerator e = _filledBuckets.GetEnumerator();
lock (_filledBuckets.SyncRoot)
{
while (e.MoveNext())
{
BucketsPack bPack = (BucketsPack)e.Current;
ArrayList bucketIds = bPack.BucketIds.Clone() as ArrayList;
foreach (int bucketId in bucketIds)
{
HashMapBucket current = new HashMapBucket(null, bucketId);
if (!buckets.Contains(current))
{
((BucketsPack)e.Current).BucketIds.Remove(bucketId);
}
else
{
HashMapBucket bucket = buckets[buckets.IndexOf(current)] as HashMapBucket;
if (!bPack.Owner.Equals(new NodeIdentity(bucket.CurrentShard/*, GetShardPrimary(bucket.CurrentShard)*/)))
{
//either i have become owner of the bucket or
//some one else for e.g a replica node
bPack.BucketIds.Remove(bucketId);
}
}
}
if (bPack.BucketIds.Count == 0)
{
//This owner has left.
leavingShards.Add(bPack.Owner);
}
}
foreach (NodeIdentity leavingShard in leavingShards)
{
BucketsPack bPack = new BucketsPack(null, leavingShard);
_filledBuckets.Remove(bPack);
}
leavingShards.Clear();
}
}
//Now we add those buckets which we have to be state transferred
//and are not currently in our list
IEnumerator ie = buckets.GetEnumerator();
ArrayList loggableBuckets = new ArrayList();
while (ie.MoveNext())
{
HashMapBucket bucket = ie.Current as HashMapBucket;
if (Context.LocalShardName.Equals(bucket.FinalShard, StringComparison.OrdinalIgnoreCase) && Context.LocalShardName.Equals(bucket.CurrentShard, StringComparison.OrdinalIgnoreCase))
{
BucketsPack bPack = new BucketsPack(null, new NodeIdentity(bucket.CurrentShard/*, GetShardPrimary(bucket.CurrentShard)*/));
//if (IsSparsedBucket(bucket.BucketId, bPack.Owner))
//{
// int index = _sparsedBuckets.IndexOf(bPack);
// if (index != -1)
// {
// bPack = _sparsedBuckets[index] as BucketsPack;
// }
// else
// _sparsedBuckets.Add(bPack);
// if (!bPack.BucketIds.Contains(bucket.BucketId))
// {
// bPack.BucketIds.Add(bucket.BucketId);
// }
//}
//else
{
int index = _filledBuckets.IndexOf(bPack);
if (index != -1)
{
bPack = _filledBuckets[index] as BucketsPack;
}
else
_filledBuckets.Add(bPack);
if (!bPack.BucketIds.Contains(bucket.BucketId))
{
bPack.BucketIds.Add(bucket.BucketId);
loggableBuckets.Add(bucket.BucketId);
}
}
}
}
_startedFrom = StartLoggingOnReplica(loggableBuckets);
}
}
catch (NullReferenceException ex)
{
if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsErrorEnabled)
LoggerManager.Instance.StateXferLogger.Error(loggingModule + ".UpdateStateTxfr", ex.ToString());
}
catch (Exception e)
{
if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsErrorEnabled)
LoggerManager.Instance.StateXferLogger.Error(loggingModule + ".UpdateStateTxfr", e.ToString());
}
finally
{
if (LoggerManager.Instance.StateXferLogger != null && LoggerManager.Instance.StateXferLogger.IsInfoEnabled)
LoggerManager.Instance.StateXferLogger.Info(loggingModule + ".UpdateStateTxfr", " Pulsing waiting thread");
System.Threading.Monitor.PulseAll(_stateTxfrMutex);
}
}
return true;
}
protected override Hashtable AcquireLockOnBuckets(ArrayList buckets, NodeIdentity finalShard)
{
//In case of a replica node replicate a bucket from the source,it is not required
//to get a proper lock. we simply simulate
Hashtable result = new Hashtable();
result[BucketLockResult.OwnerChanged] = null;
result[BucketLockResult.LockAcquired] = buckets;
return result;
}
public override void AckBucketTxfer(NodeIdentity owner, ArrayList buckets)
{
//no need to send an acknowlegement to the owner.
}
protected override void FinalizeStateTransfer()
{
//NTD: [High] Remove Extra buckets locally
//PartitionOfReplicasServerCache cache = _parent as PartitionOfReplicasServerCache;
//cache.RemoveExtraBuckets();
}
#region State Transfer Logging Code
private OperationId StartLoggingOnReplica(ArrayList bucketIds)
{
//opId is latest operation id at time when bucket logging been started so that we can use it during query
OperationId opId = new OperationId();
if (Context.OperationLog != null)
{
ILogOperation lastOperation = Context.OperationLog.LastOperation;
if (lastOperation != null && lastOperation.OperationId != null)
opId = Context.OperationLog.LastOperation.OperationId;
}
foreach (int bucketID in bucketIds)
{
if (Context.OperationLog != null)
Context.OperationLog.StartLogging(new LoggingIdentity(taskIdentity.DBName,taskIdentity.ColName, bucketID), LogMode.BeforeActualOperation);
}
return opId;
}
private void StopLoggingOnReplica(LoggingIdentity identity)
{
if (Context.OperationLog != null)
{
Context.OperationLog.StopLogging(identity);
}
}
private ICollection GetLoggedOperations(OperationId operationId, LoggingIdentity identity)
{
if (Context.OperationLog != null)
{
return Context.OperationLog.GetLoggedOperations(identity, operationId);
}
return null;
}
private void ApplyLogOperation(ClusteredArrayList logOperations)
{
if (this.operationDispatcher != null && logOperations!=null && logOperations.Count>0)
{
IStateTransferOperation operation = this.CreateStateTransferOperation(StateTransferOpCode.ApplyLogOperations);
operation.Params.SetParamValue(ParamName.LogOperations, logOperations);
operationDispatcher.DispatchOperation<Object>(operation);
}
}
private object RemoveLoggedOperations(int bucketID)
{
LoggingIdentity identity = new LoggingIdentity(taskIdentity.DBName, taskIdentity.ColName, bucketID);
if (Context.OperationLog != null)
return Context.OperationLog.RemoveLoggedOperations(identity);
return null;
}
#endregion
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.Protobuf
{
public class CodedInputStreamTest
{
/// <summary>
/// Helper to construct a byte array from a bunch of bytes. The inputs are
/// actually ints so that I can use hex notation and not get stupid errors
/// about precision.
/// </summary>
private static byte[] Bytes(params int[] bytesAsInts)
{
byte[] bytes = new byte[bytesAsInts.Length];
for (int i = 0; i < bytesAsInts.Length; i++)
{
bytes[i] = (byte) bytesAsInts[i];
}
return bytes;
}
/// <summary>
/// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
/// </summary>
private static void AssertReadVarint(byte[] data, ulong value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual((uint) value, input.ReadRawVarint32());
input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
Assert.AreEqual((uint) value, input.ReadRawVarint32());
input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
}
// Try reading directly from a MemoryStream. We want to verify that it
// doesn't read past the end of the input, so write an extra byte - this
// lets us test the position at the end.
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(data, 0, data.Length);
memoryStream.WriteByte(0);
memoryStream.Position = 0;
Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
Assert.AreEqual(data.Length, memoryStream.Position);
}
/// <summary>
/// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
/// expects them to fail with an InvalidProtocolBufferException whose
/// description matches the given one.
/// </summary>
private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
{
CodedInputStream input = new CodedInputStream(data);
var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
Assert.AreEqual(expected.Message, exception.Message);
input = new CodedInputStream(data);
exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
Assert.AreEqual(expected.Message, exception.Message);
// Make sure we get the same error when reading directly from a Stream.
exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
Assert.AreEqual(expected.Message, exception.Message);
}
[Test]
public void ReadVarint()
{
AssertReadVarint(Bytes(0x00), 0);
AssertReadVarint(Bytes(0x01), 1);
AssertReadVarint(Bytes(0x7f), 127);
// 14882
AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
// 11964378330978735131
AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
(0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
// Failures
AssertReadVarintFailure(
InvalidProtocolBufferException.MalformedVarint(),
Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x00));
AssertReadVarintFailure(
InvalidProtocolBufferException.TruncatedMessage(),
Bytes(0x80));
}
/// <summary>
/// Parses the given bytes using ReadRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertReadLittleEndian32(byte[] data, uint value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
input = new CodedInputStream(
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
}
}
/// <summary>
/// Parses the given bytes using ReadRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertReadLittleEndian64(byte[] data, ulong value)
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
input = new CodedInputStream(
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
}
}
[Test]
public void ReadLittleEndian()
{
AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
0x123456789abcdef0L);
AssertReadLittleEndian64(
Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
}
[Test]
public void DecodeZigZag32()
{
Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
}
[Test]
public void DecodeZigZag64()
{
Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
[Test]
public void ReadWholeMessage_VaryingBlockSizes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
byte[] rawBytes = message.ToByteArray();
Assert.AreEqual(rawBytes.Length, message.CalculateSize());
TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
Assert.AreEqual(message, message2);
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
Assert.AreEqual(message, message2);
}
}
[Test]
public void ReadHugeBlob()
{
// Allocate and initialize a 1MB blob.
byte[] blob = new byte[1 << 20];
for (int i = 0; i < blob.Length; i++)
{
blob[i] = (byte) i;
}
// Make a message containing it.
var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
// Serialize and parse it. Make sure to parse from an InputStream, not
// directly from a ByteString, so that CodedInputStream uses buffered
// reading.
TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
Assert.AreEqual(message, message2);
}
[Test]
public void ReadMaliciouslyLargeBlob()
{
MemoryStream ms = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(ms);
uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
output.WriteRawVarint32(tag);
output.WriteRawVarint32(0x7FFFFFFF);
output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms);
Assert.AreEqual(tag, input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
}
internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
{
if (depth == 0)
{
return new TestRecursiveMessage { I = 5 };
}
else
{
return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
}
}
internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
{
if (depth == 0)
{
Assert.IsNull(message.A);
Assert.AreEqual(5, message.I);
}
else
{
Assert.IsNotNull(message.A);
AssertMessageDepth(message.A, depth - 1);
}
}
[Test]
public void MaliciousRecursion()
{
ByteString data64 = MakeRecursiveMessage(64).ToByteString();
ByteString data65 = MakeRecursiveMessage(65).ToByteString();
AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
}
[Test]
public void SizeLimit()
{
// Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
// apply to the latter case.
MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
}
/// <summary>
/// Tests that if we read an string that contains invalid UTF-8, no exception
/// is thrown. Instead, the invalid bytes are replaced with the Unicode
/// "replacement character" U+FFFD.
/// </summary>
[Test]
public void ReadInvalidUtf8()
{
MemoryStream ms = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(ms);
uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
output.WriteRawVarint32(tag);
output.WriteRawVarint32(1);
output.WriteRawBytes(new byte[] {0x80});
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms);
Assert.AreEqual(tag, input.ReadTag());
string text = input.ReadString();
Assert.AreEqual('\ufffd', text[0]);
}
/// <summary>
/// A stream which limits the number of bytes it reads at a time.
/// We use this to make sure that CodedInputStream doesn't screw up when
/// reading in small blocks.
/// </summary>
private sealed class SmallBlockInputStream : MemoryStream
{
private readonly int blockSize;
public SmallBlockInputStream(byte[] data, int blockSize)
: base(data)
{
this.blockSize = blockSize;
}
public override int Read(byte[] buffer, int offset, int count)
{
return base.Read(buffer, offset, Math.Min(count, blockSize));
}
}
[Test]
public void TestNegativeEnum()
{
byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
CodedInputStream input = new CodedInputStream(bytes);
Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
Assert.IsTrue(input.IsAtEnd);
}
//Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
[Test]
public void TestSlowPathAvoidance()
{
using (var ms = new MemoryStream())
{
CodedOutputStream output = new CodedOutputStream(ms);
output.WriteTag(1, WireFormat.WireType.LengthDelimited);
output.WriteBytes(ByteString.CopyFrom(new byte[100]));
output.WriteTag(2, WireFormat.WireType.LengthDelimited);
output.WriteBytes(ByteString.CopyFrom(new byte[100]));
output.Flush();
ms.Position = 0;
CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0);
uint tag = input.ReadTag();
Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
Assert.AreEqual(100, input.ReadBytes().Length);
tag = input.ReadTag();
Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
Assert.AreEqual(100, input.ReadBytes().Length);
}
}
[Test]
public void Tag0Throws()
{
var input = new CodedInputStream(new byte[] { 0 });
Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
}
[Test]
public void SkipGroup()
{
// Create an output stream with a group in:
// Field 1: string "field 1"
// Field 2: group containing:
// Field 1: fixed int32 value 100
// Field 2: string "ignore me"
// Field 3: nested group containing
// Field 1: fixed int64 value 1000
// Field 3: string "field 3"
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.LengthDelimited);
output.WriteString("field 1");
// The outer group...
output.WriteTag(2, WireFormat.WireType.StartGroup);
output.WriteTag(1, WireFormat.WireType.Fixed32);
output.WriteFixed32(100);
output.WriteTag(2, WireFormat.WireType.LengthDelimited);
output.WriteString("ignore me");
// The nested group...
output.WriteTag(3, WireFormat.WireType.StartGroup);
output.WriteTag(1, WireFormat.WireType.Fixed64);
output.WriteFixed64(1000);
// Note: Not sure the field number is relevant for end group...
output.WriteTag(3, WireFormat.WireType.EndGroup);
// End the outer group
output.WriteTag(2, WireFormat.WireType.EndGroup);
output.WriteTag(3, WireFormat.WireType.LengthDelimited);
output.WriteString("field 3");
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
Assert.AreEqual("field 1", input.ReadString());
Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
input.SkipLastField(); // Should consume the whole group, including the nested one.
Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
Assert.AreEqual("field 3", input.ReadString());
}
[Test]
public void EndOfStreamReachedWhileSkippingGroup()
{
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
output.WriteTag(1, WireFormat.WireType.StartGroup);
output.WriteTag(2, WireFormat.WireType.StartGroup);
output.WriteTag(2, WireFormat.WireType.EndGroup);
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
input.ReadTag();
Assert.Throws<InvalidProtocolBufferException>(() => input.SkipLastField());
}
[Test]
public void RecursionLimitAppliedWhileSkippingGroup()
{
var stream = new MemoryStream();
var output = new CodedOutputStream(stream);
for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
{
output.WriteTag(1, WireFormat.WireType.StartGroup);
}
for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
{
output.WriteTag(1, WireFormat.WireType.EndGroup);
}
output.Flush();
stream.Position = 0;
// Now act like a generated client
var input = new CodedInputStream(stream);
Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
Assert.Throws<InvalidProtocolBufferException>(() => input.SkipLastField());
}
[Test]
public void Construction_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
}
[Test]
public void CreateWithLimits_InvalidLimits()
{
var stream = new MemoryStream();
Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Mail.Net.SDP
{
#region usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
#endregion
/// <summary>
/// Session Description Protocol. Defined in RFC 4566.
/// </summary>
public class SDP_Message
{
#region Members
private readonly List<SDP_Attribute> m_pAttributes;
private readonly List<SDP_Media> m_pMedias;
private readonly List<SDP_Time> m_pTimes;
private string m_Origin = "";
private string m_RepeatTimes = "";
private string m_SessionDescription = "";
private string m_SessionName = "";
private string m_Uri = "";
private string m_Version = "0";
#endregion
#region Properties
/// <summary>
/// Gets or sets version of the Session Description Protocol.
/// </summary>
public string Version
{
get { return m_Version; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("Property Version can't be null or empty !");
}
m_Version = value;
}
}
/// <summary>
/// Gets originator and session identifier.
/// </summary>
public string Originator
{
get { return m_Origin; }
set { m_Origin = value; }
}
/// <summary>
/// Gets or sets textual session name.
/// </summary>
public string SessionName
{
get { return m_SessionName; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("Property SessionName can't be null or empty !");
}
m_SessionName = value;
}
}
/// <summary>
/// Gets or sets textual information about the session. This is optional value, null means not specified.
/// </summary>
public string SessionDescription
{
get { return m_SessionDescription; }
set { m_SessionDescription = value; }
}
/// <summary>
/// Gets or sets Uniform Resource Identifier. The URI should be a pointer to additional information
/// about the session. This is optional value, null means not specified.
/// </summary>
public string Uri
{
get { return m_Uri; }
set { m_Uri = value; }
}
/// <summary>
/// Gets or sets connection data. This is optional value if each media part specifies this value,
/// null means not specified.
/// </summary>
public SDP_ConnectionData ConnectionData { get; set; }
/// <summary>
/// Gets start and stop times for a session. If Count = 0, t field not written dot SDP data.
/// </summary>
public List<SDP_Time> Times
{
get { return m_pTimes; }
}
/// <summary>
/// Gets or sets repeat times for a session. This is optional value, null means not specified.
/// </summary>
public string RepeatTimes
{
get { return m_RepeatTimes; }
set { m_RepeatTimes = value; }
}
/// <summary>
/// Gets attributes collection. This is optional value, Count == 0 means not specified.
/// </summary>
public List<SDP_Attribute> Attributes
{
get { return m_pAttributes; }
}
/// <summary>
/// Gets media parts collection.
/// </summary>
public List<SDP_Media> Media
{
get { return m_pMedias; }
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
public SDP_Message()
{
m_pTimes = new List<SDP_Time>();
m_pAttributes = new List<SDP_Attribute>();
m_pMedias = new List<SDP_Media>();
}
#endregion
#region Methods
/// <summary>
/// Parses SDP from raw data.
/// </summary>
/// <param name="data">Raw SDP data.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null reference.</exception>
public static SDP_Message Parse(string data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
SDP_Message sdp = new SDP_Message();
StringReader r = new StringReader(data);
string line = r.ReadLine();
//--- Read global fields ---------------------------------------------
while (line != null)
{
line = line.Trim();
// We reached to media descriptions
if (line.ToLower().StartsWith("m"))
{
/*
m= (media name and transport address)
i=* (media title)
c=* (connection information -- optional if included at session level)
b=* (zero or more bandwidth information lines)
k=* (encryption key)
a=* (zero or more media attribute lines)
*/
SDP_Media media = new SDP_Media();
media.MediaDescription = SDP_MediaDescription.Parse(line);
sdp.Media.Add(media);
line = r.ReadLine();
// Pasrse media fields and attributes
while (line != null)
{
line = line.Trim();
// Next media descrition, just stop active media description parsing,
// fall through main while, allow next while loop to process it.
if (line.ToLower().StartsWith("m"))
{
break;
}
// i media title
else if (line.ToLower().StartsWith("i"))
{
media.Title = line.Split(new[] {'='}, 2)[1].Trim();
}
// c connection information
else if (line.ToLower().StartsWith("c"))
{
media.ConnectionData = SDP_ConnectionData.Parse(line);
}
// a Attributes
else if (line.ToLower().StartsWith("a"))
{
media.Attributes.Add(SDP_Attribute.Parse(line));
}
line = r.ReadLine();
}
break;
}
// v Protocol Version
else if (line.ToLower().StartsWith("v"))
{
sdp.Version = line.Split(new[] {'='}, 2)[1].Trim();
}
// o Origin
else if (line.ToLower().StartsWith("o"))
{
sdp.Originator = line.Split(new[] {'='}, 2)[1].Trim();
}
// s Session Name
else if (line.ToLower().StartsWith("s"))
{
sdp.SessionName = line.Split(new[] {'='}, 2)[1].Trim();
}
// i Session Information
else if (line.ToLower().StartsWith("i"))
{
sdp.SessionDescription = line.Split(new[] {'='}, 2)[1].Trim();
}
// u URI
else if (line.ToLower().StartsWith("u"))
{
sdp.Uri = line.Split(new[] {'='}, 2)[1].Trim();
}
// c Connection Data
else if (line.ToLower().StartsWith("c"))
{
sdp.ConnectionData = SDP_ConnectionData.Parse(line);
}
// t Timing
else if (line.ToLower().StartsWith("t"))
{
sdp.Times.Add(SDP_Time.Parse(line));
}
// a Attributes
else if (line.ToLower().StartsWith("a"))
{
sdp.Attributes.Add(SDP_Attribute.Parse(line));
}
line = r.ReadLine().Trim();
}
return sdp;
}
/// <summary>
/// Stores SDP data to specified file. Note: official suggested file extention is .sdp.
/// </summary>
/// <param name="fileName">File name with path where to store SDP data.</param>
public void ToFile(string fileName)
{
File.WriteAllText(fileName, ToStringData());
}
/// <summary>
/// Returns SDP as string data.
/// </summary>
/// <returns></returns>
public string ToStringData()
{
StringBuilder retVal = new StringBuilder();
// v Protocol Version
retVal.AppendLine("v=" + Version);
// o Origin
if (!string.IsNullOrEmpty(Originator))
{
retVal.AppendLine("o=" + Originator);
}
// s Session Name
if (!string.IsNullOrEmpty(SessionName))
{
retVal.AppendLine("s=" + SessionName);
}
// i Session Information
if (!string.IsNullOrEmpty(SessionDescription))
{
retVal.AppendLine("i=" + SessionDescription);
}
// u URI
if (!string.IsNullOrEmpty(Uri))
{
retVal.AppendLine("u=" + Uri);
}
// c Connection Data
if (ConnectionData != null)
{
retVal.Append(ConnectionData.ToValue());
}
// t Timing
foreach (SDP_Time time in Times)
{
retVal.Append(time.ToValue());
}
// a Attributes
foreach (SDP_Attribute attribute in Attributes)
{
retVal.Append(attribute.ToValue());
}
// m media description(s)
foreach (SDP_Media media in Media)
{
retVal.Append(media.ToValue());
}
return retVal.ToString();
}
#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 webfolio.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;
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Dialogs;
using XenAPI;
using System.Linq;
using System.IO;
using XenAdmin.Core;
using XenAdmin.Diagnostics.Problems;
using XenAdmin.Wizards.PatchingWizard.PlanActions;
namespace XenAdmin.Wizards.PatchingWizard
{
public enum WizardMode { SingleUpdate, AutomatedUpdates, NewVersion }
/// <summary>
/// Remember that equals for patches don't work across connections because
/// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_patch or Host_patch
/// You should do it manually or use delegates.
/// </summary>
public partial class PatchingWizard : XenWizardBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage;
private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage;
private readonly PatchingWizard_ModePage PatchingWizard_ModePage;
private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers;
private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage;
private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage;
private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage;
private readonly PatchingWizard_AutomatedUpdatesPage PatchingWizard_AutomatedUpdatesPage;
public PatchingWizard()
{
InitializeComponent();
PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage();
PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage();
PatchingWizard_ModePage = new PatchingWizard_ModePage();
PatchingWizard_SelectServers = new PatchingWizard_SelectServers();
PatchingWizard_UploadPage = new PatchingWizard_UploadPage();
PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage();
PatchingWizard_FirstPage = new PatchingWizard_FirstPage();
PatchingWizard_AutomatedUpdatesPage = new PatchingWizard_AutomatedUpdatesPage();
AddPage(PatchingWizard_FirstPage);
AddPage(PatchingWizard_SelectPatchPage);
AddPage(PatchingWizard_SelectServers);
AddPage(PatchingWizard_UploadPage);
AddPage(PatchingWizard_PrecheckPage);
AddPage(PatchingWizard_ModePage);
AddPage(PatchingWizard_PatchingPage);
}
protected override void UpdateWizardContent(XenTabPage senderPage)
{
var prevPageType = senderPage.GetType();
if (prevPageType == typeof(PatchingWizard_SelectPatchPage))
{
var updateType = PatchingWizard_SelectPatchPage.SelectedUpdateType;
var selectedPatchFilePath = PatchingWizard_SelectPatchPage.SelectedPatchFilePath;
var alertFromFileOnDisk = PatchingWizard_SelectPatchPage.AlertFromFileOnDisk;
var fileFromDiskHasUpdateXml = PatchingWizard_SelectPatchPage.FileFromDiskHasUpdateXml;
PatchingWizard_SelectServers.WizardMode = WizardMode.SingleUpdate;
PatchingWizard_SelectServers.SelectedUpdateType = updateType;
PatchingWizard_SelectServers.AlertFromFileOnDisk = alertFromFileOnDisk;
PatchingWizard_SelectServers.FileFromDiskHasUpdateXml = fileFromDiskHasUpdateXml;
RemovePage(PatchingWizard_UploadPage);
RemovePage(PatchingWizard_ModePage);
RemovePage(PatchingWizard_PatchingPage);
RemovePage(PatchingWizard_AutomatedUpdatesPage);
AddAfterPage(PatchingWizard_SelectServers, PatchingWizard_UploadPage);
AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_ModePage);
AddAfterPage(PatchingWizard_ModePage, PatchingWizard_PatchingPage);
PatchingWizard_UploadPage.SelectedUpdateType = updateType;
PatchingWizard_UploadPage.SelectedPatchFilePath = selectedPatchFilePath;
PatchingWizard_UploadPage.SelectedUpdateAlert = alertFromFileOnDisk;
PatchingWizard_UploadPage.PatchFromDisk = PatchingWizard_SelectPatchPage.PatchFromDisk;
PatchingWizard_ModePage.SelectedUpdateType = updateType;
PatchingWizard_PrecheckPage.PoolUpdate = null; //reset the PoolUpdate property; it will be updated on leaving the Upload page, if this page is visible
PatchingWizard_PrecheckPage.UpdateAlert = alertFromFileOnDisk;
PatchingWizard_AutomatedUpdatesPage.WizardMode = WizardMode.SingleUpdate;
PatchingWizard_AutomatedUpdatesPage.UpdateAlert = alertFromFileOnDisk;
PatchingWizard_AutomatedUpdatesPage.PatchFromDisk = PatchingWizard_SelectPatchPage.PatchFromDisk;
PatchingWizard_PatchingPage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.SelectedPatchFilePatch = selectedPatchFilePath;
}
else if (prevPageType == typeof(PatchingWizard_SelectServers))
{
var selectedServers = PatchingWizard_SelectServers.SelectedServers;
var selectedPools = PatchingWizard_SelectServers.SelectedPools;
PatchingWizard_PrecheckPage.SelectedServers = selectedServers;
PatchingWizard_ModePage.SelectedPools = selectedPools;
PatchingWizard_ModePage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedPools = selectedPools;
PatchingWizard_UploadPage.SelectedServers = selectedServers;
PatchingWizard_UploadPage.SelectedPools = selectedPools;
PatchingWizard_AutomatedUpdatesPage.SelectedPools = selectedPools;
}
else if (prevPageType == typeof(PatchingWizard_UploadPage))
{
var patch = PatchingWizard_UploadPage.Patch;
var update = PatchingWizard_UploadPage.PoolUpdate;
var suppPackVdis = PatchingWizard_UploadPage.SuppPackVdis;
PatchingWizard_PrecheckPage.Patch = patch;
PatchingWizard_PrecheckPage.PoolUpdate = update;
var srsWithUploadedUpdates = new Dictionary<Pool_update, Dictionary<Host, SR>>();
foreach (var mapping in PatchingWizard_UploadPage.PatchMappings)
{
if (mapping is PoolUpdateMapping pum)
srsWithUploadedUpdates[pum.Pool_update] = pum.SrsWithUploadedUpdatesPerHost;
else if (mapping is SuppPackMapping spm && spm.Pool_update != null)
srsWithUploadedUpdates[spm.Pool_update] = spm.SrsWithUploadedUpdatesPerHost;
}
PatchingWizard_PrecheckPage.SrUploadedUpdates = srsWithUploadedUpdates;
PatchingWizard_ModePage.Patch = patch;
PatchingWizard_ModePage.PoolUpdate = update;
PatchingWizard_PatchingPage.Patch = patch;
PatchingWizard_PatchingPage.PoolUpdate = update;
PatchingWizard_PatchingPage.SuppPackVdis = suppPackVdis;
}
else if (prevPageType == typeof(PatchingWizard_ModePage))
{
PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions;
PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode;
PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile;
}
else if (prevPageType == typeof(PatchingWizard_PrecheckPage))
{
PatchingWizard_PatchingPage.PrecheckProblemsActuallyResolved = PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved;
PatchingWizard_PatchingPage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_ModePage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_AutomatedUpdatesPage.PrecheckProblemsActuallyResolved = PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved;
}
}
protected override void OnCancel(ref bool cancel)
{
base.OnCancel(ref cancel);
if (cancel)
return;
RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES,
Messages.REVERTED_WIZARD_CHANGES,
Problem.GetUnwindChangesActions(PatchingWizard_PrecheckPage.PrecheckProblemsActuallyResolved));
CleanUploadedPatches(true);
RemoveDownloadedPatches();
}
protected override void FinishWizard()
{
CleanUploadedPatches();
RemoveDownloadedPatches();
Updates.RefreshUpdateAlerts(Updates.UpdateType.ServerPatches);
base.FinishWizard();
}
private void CleanUploadedPatches(bool forceCleanSelectedPatch = false)
{
var list = new List<AsyncAction>();
foreach (var mapping in PatchingWizard_UploadPage.PatchMappings)
{
Pool_patch patch = null;
if (mapping is PoolPatchMapping patchMapping)
patch = patchMapping.Pool_patch;
else if (mapping is OtherLegacyMapping legacyMapping)
patch = legacyMapping.Pool_patch;
if (patch != null)
{
// exclude the selected patch; either the user wants to keep it or it has already been cleared in the patching page
if (PatchingWizard_UploadPage.Patch == null ||
!string.Equals(patch.uuid, PatchingWizard_UploadPage.Patch.uuid, StringComparison.OrdinalIgnoreCase) ||
forceCleanSelectedPatch)
{
var action = GetCleanActionForPoolPatch(patch);
if (action != null)
list.Add(action);
}
continue;
}
if (mapping is PoolUpdateMapping updateMapping)
{
var action = GetCleanActionForPoolUpdate(updateMapping.Pool_update);
if (action != null)
list.Add(action);
continue;
}
if (mapping is SuppPackMapping suppPackMapping)
{
if (suppPackMapping.Pool_update!= null)
{
var action = GetCleanActionForPoolUpdate(suppPackMapping.Pool_update);
if (action != null)
list.Add(action);
}
else
list.AddRange(GetRemoveVdiActions(suppPackMapping.SuppPackVdis.Values.ToList()));
}
}
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, list);
}
private AsyncAction GetCleanActionForPoolPatch(Pool_patch patch)
{
if (patch == null || patch.Connection == null || !patch.Connection.IsConnected)
return null;
if (patch.HostsAppliedTo().Count == 0)
return new RemovePatchAction(patch);
return new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref));
}
private AsyncAction GetCleanActionForPoolUpdate(Pool_update update)
{
if (update == null || update.Connection == null || !update.Connection.IsConnected)
return null;
return new DelegatedAsyncAction(update.Connection, Messages.REMOVE_PATCH, "", "", session =>
{
try
{
Pool_update.pool_clean(session, update.opaque_ref);
if (!update.AppliedOnHosts().Any())
Pool_update.destroy(session, update.opaque_ref);
}
catch (Failure f)
{
log.Error("Clean up failed", f);
}
});
}
private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove)
{
var list = new List<AsyncAction>();
if (vdisToRemove != null)
foreach (var vdi in vdisToRemove)
{
if (vdi.Connection != null && vdi.Connection.IsConnected)
list.Add(new DestroyDiskAction(vdi));
}
return list;
}
private void RemoveDownloadedPatches()
{
List<string> listOfDownloadedFiles = new List<string>();
listOfDownloadedFiles.AddRange(PatchingWizard_AutomatedUpdatesPage.AllDownloadedPatches.Values); // AutomatedUpdates or NewVersion
listOfDownloadedFiles.AddRange(PatchingWizard_UploadPage.AllDownloadedPatches.Values); //SingleUpdate
listOfDownloadedFiles.AddRange(PatchingWizard_SelectPatchPage.UnzippedUpdateFiles);
foreach (string downloadedPatch in listOfDownloadedFiles)
{
try
{
if (File.Exists(downloadedPatch))
{
File.Delete(downloadedPatch);
}
}
catch
{
log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch);
}
}
}
private void RunMultipleActions(string title, string startDescription, string endDescription,
List<AsyncAction> subActions)
{
if (subActions != null && subActions.Count > 0)
{
using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription,
endDescription, subActions, false, true))
{
using (var dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks))
dialog.ShowDialog(Program.MainWindow);
}
}
}
}
}
| |
// 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.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using FILETIME = Internal.Cryptography.Pal.Native.FILETIME;
using System.Security.Cryptography;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using System.Security.Cryptography.X509Certificates;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
private SafeCertContextHandle _certContext;
public static ICertificatePal FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle);
if (safeCertContextHandle.IsInvalid)
throw ErrorCode.HRESULT_INVALID_HANDLE.ToCryptographicException();
CRYPTOAPI_BLOB dataBlob;
int cbData = 0;
bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, out dataBlob, ref cbData);
return new CertificatePal(safeCertContextHandle, deleteKeyContainer);
}
/// <summary>
/// Returns the SafeCertContextHandle. Use this instead of FromHandle() when
/// creating another X509Certificate object based on this one to ensure the underlying
/// cert context is not released at the wrong time.
/// </summary>
public static ICertificatePal FromOtherCert(X509Certificate copyFrom)
{
CertificatePal pal = new CertificatePal((CertificatePal)copyFrom.Pal);
return pal;
}
public IntPtr Handle
{
get { return _certContext.DangerousGetHandle(); }
}
public string Issuer
{
get
{
return GetIssuerOrSubject(issuer: true);
}
}
public string Subject
{
get
{
return GetIssuerOrSubject(issuer: false);
}
}
public byte[] Thumbprint
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
byte[] thumbprint = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return thumbprint;
}
}
public string KeyAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
GC.KeepAlive(this);
return keyAlgorithm;
}
}
}
public byte[] KeyAlgorithmParameters
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
int algId;
if (keyAlgorithmOid == Oids.RsaRsa)
algId = AlgId.CALG_RSA_KEYX; // Fast-path for the most common case.
else
algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
unsafe
{
byte* NULL_ASN_TAG = (byte*)0x5;
byte[] keyAlgorithmParameters;
if (algId == AlgId.CALG_DSS_SIGN
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG)
{
//
// DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build
// the certificate chain and propagate the parameters down from the certificate chain.
//
keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain();
}
else
{
keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray();
}
GC.KeepAlive(this);
return keyAlgorithmParameters;
}
}
}
}
private byte[] PropagateKeyAlgorithmParametersFromChain()
{
unsafe
{
SafeX509ChainHandle certChainContext = null;
try
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
{
CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
}
byte[] keyAlgorithmParameters = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return keyAlgorithmParameters;
}
finally
{
if (certChainContext != null)
certChainContext.Dispose();
}
}
}
public byte[] PublicKeyValue
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray();
GC.KeepAlive(this);
return publicKey;
}
}
}
public byte[] SerialNumber
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(this);
return serialNumber;
}
}
}
public string SignatureAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId);
GC.KeepAlive(this);
return signatureAlgorithm;
}
}
}
public DateTime NotAfter
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime();
GC.KeepAlive(this);
return notAfter;
}
}
}
public DateTime NotBefore
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime();
GC.KeepAlive(this);
return notBefore;
}
}
}
public byte[] RawData
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int count = pCertContext->cbCertEncoded;
byte[] rawData = new byte[count];
Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), rawData, 0, count);
GC.KeepAlive(this);
return rawData;
}
}
}
public int Version
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int version = pCertContext->pCertInfo->dwVersion + 1;
GC.KeepAlive(this);
return version;
}
}
}
public bool Archived
{
get
{
int uninteresting = 0;
bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting);
return archivePropertyExists;
}
set
{
unsafe
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null);
CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null;
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
}
}
public string FriendlyName
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData))
return string.Empty;
StringBuilder sb = new StringBuilder((cbData + 1) / 2);
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, sb, ref cbData))
return string.Empty;
return sb.ToString();
}
set
{
string friendlyName = (value == null) ? string.Empty : value;
unsafe
{
IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName);
try
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName);
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
finally
{
Marshal.FreeHGlobal(pFriendlyName);
}
}
}
}
public X500DistinguishedName SubjectName
{
get
{
unsafe
{
byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray();
X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName);
GC.KeepAlive(this);
return subjectName;
}
}
}
public X500DistinguishedName IssuerName
{
get
{
unsafe
{
byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray();
X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName);
GC.KeepAlive(this);
return issuerName;
}
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
unsafe
{
CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo;
int numExtensions = pCertInfo->cExtension;
X509Extension[] extensions = new X509Extension[numExtensions];
for (int i = 0; i < numExtensions; i++)
{
CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i;
string oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId);
Oid oid = new Oid(oidValue);
bool critical = pCertExtension->fCritical != 0;
byte[] rawData = pCertExtension->Value.ToByteArray();
extensions[i] = new X509Extension(oid, rawData, critical);
}
GC.KeepAlive(this);
return extensions;
}
}
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
CertNameType certNameType = MapNameType(nameType);
CertNameFlags certNameFlags = forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStrTypeAndFlags strType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, null, 0);
if (cchCount == 0)
throw Marshal.GetLastWin32Error().ToCryptographicException();
StringBuilder sb = new StringBuilder(cchCount);
if (Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, sb, cchCount) == 0)
throw Marshal.GetLastWin32Error().ToCryptographicException();
return sb.ToString();
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
if (HasPrivateKey)
{
// Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key.
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Private Key]");
}
#if uap
// Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key.
#else
CspKeyContainerInfo cspKeyContainerInfo = null;
try
{
if (HasPrivateKey)
{
CspParameters parameters = GetPrivateKeyCsp();
cspKeyContainerInfo = new CspKeyContainerInfo(parameters);
}
}
// We could not access the key container. Just return.
catch (CryptographicException) { }
// Ephemeral keys will not have container information.
if (cspKeyContainerInfo == null)
return;
sb.Append(Environment.NewLine + " Key Store: ");
sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User");
sb.Append(Environment.NewLine + " Provider Name: ");
sb.Append(cspKeyContainerInfo.ProviderName);
sb.Append(Environment.NewLine + " Provider type: ");
sb.Append(cspKeyContainerInfo.ProviderType);
sb.Append(Environment.NewLine + " Key Spec: ");
sb.Append(cspKeyContainerInfo.KeyNumber);
sb.Append(Environment.NewLine + " Key Container Name: ");
sb.Append(cspKeyContainerInfo.KeyContainerName);
try
{
string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName;
sb.Append(Environment.NewLine + " Unique Key Container Name: ");
sb.Append(uniqueKeyContainer);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
bool b = false;
try
{
b = cspKeyContainerInfo.HardwareDevice;
sb.Append(Environment.NewLine + " Hardware Device: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Removable;
sb.Append(Environment.NewLine + " Removable: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Protected;
sb.Append(Environment.NewLine + " Protected: ");
sb.Append(b);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
#endif // #if uap / #else
}
public void Dispose()
{
SafeCertContextHandle certContext = _certContext;
_certContext = null;
if (certContext != null && !certContext.IsInvalid)
{
certContext.Dispose();
}
}
internal SafeCertContextHandle CertContext
{
get
{
SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle());
GC.KeepAlive(_certContext);
return certContext;
}
}
private static CertNameType MapNameType(X509NameType nameType)
{
switch (nameType)
{
case X509NameType.SimpleName:
return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE;
case X509NameType.EmailName:
return CertNameType.CERT_NAME_EMAIL_TYPE;
case X509NameType.UpnName:
return CertNameType.CERT_NAME_UPN_TYPE;
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
return CertNameType.CERT_NAME_DNS_TYPE;
case X509NameType.UrlName:
return CertNameType.CERT_NAME_URL_TYPE;
default:
throw new ArgumentException(SR.Argument_InvalidNameType);
}
}
private string GetIssuerOrSubject(bool issuer)
{
CertNameFlags flags = issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStringType stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0);
if (cchCount == 0)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
StringBuilder sb = new StringBuilder(cchCount);
cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount);
if (cchCount == 0)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return sb.ToString();
}
private CertificatePal(CertificatePal copyFrom)
{
// Use _certContext (instead of CertContext) to keep the original context handle from being
// finalized until all cert copies are no longer referenced.
_certContext = new SafeCertContextHandle(copyFrom._certContext);
}
private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer)
{
if (deleteKeyContainer)
{
// We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose
// Release() method performs the key container deletion.
SafeCertContextHandle oldCertContext = certContext;
certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle());
GC.KeepAlive(oldCertContext);
}
_certContext = certContext;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics.Containers;
using osu.Game.Overlays.Profile.Header.Components;
using osu.Game.Users.Drawables;
namespace osu.Game.Users
{
public class UserPanel : OsuClickableContainer, IHasContextMenu
{
private const float height = 100;
private const float content_padding = 10;
private const float status_height = 30;
public readonly User User;
[Resolved(canBeNull: true)]
private OsuColour colours { get; set; }
private Container statusBar;
private Box statusBg;
private OsuSpriteText statusMessage;
private Container content;
protected override Container<Drawable> Content => content;
public readonly Bindable<UserStatus> Status = new Bindable<UserStatus>();
public readonly IBindable<UserActivity> Activity = new Bindable<UserActivity>();
public new Action Action;
protected Action ViewProfile;
public UserPanel(User user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
User = user;
Height = height - status_height;
}
[BackgroundDependencyLoader(permitNulls: true)]
private void load(UserProfileOverlay profile)
{
if (colours == null)
throw new InvalidOperationException($"{nameof(colours)} not initialized!");
FillFlowContainer infoContainer;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = 5,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(0.25f),
Radius = 4,
},
Children = new Drawable[]
{
new DelayedLoadUnloadWrapper(() => new UserCoverBackground
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
User = User,
}, 300, 5000)
{
RelativeSizeAxes = Axes.Both,
},
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(0.7f),
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Top = content_padding, Horizontal = content_padding },
Children = new Drawable[]
{
new UpdateableAvatar
{
Size = new Vector2(height - status_height - content_padding * 2),
User = User,
Masking = true,
CornerRadius = 5,
OpenOnClick = { Value = false },
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(0.25f),
Radius = 4,
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Left = height - status_height - content_padding },
Children = new Drawable[]
{
new OsuSpriteText
{
Text = User.Username,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 18, italics: true),
},
infoContainer = new FillFlowContainer
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
AutoSizeAxes = Axes.X,
Height = 20f,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5f, 0f),
Children = new Drawable[]
{
new UpdateableFlag(User.Country)
{
Width = 30f,
RelativeSizeAxes = Axes.Y,
},
},
},
},
},
},
},
statusBar = new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
RelativeSizeAxes = Axes.X,
Alpha = 0f,
Children = new Drawable[]
{
statusBg = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.5f,
},
new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2(5f, 0f),
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Icon = FontAwesome.Regular.Circle,
Shadow = true,
Size = new Vector2(14),
},
statusMessage = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold),
},
},
},
},
},
}
});
if (User.IsSupporter)
{
infoContainer.Add(new SupporterIcon
{
Height = 20f,
SupportLevel = User.SupportLevel
});
}
Status.ValueChanged += status => displayStatus(status.NewValue, Activity.Value);
Activity.ValueChanged += activity => displayStatus(Status.Value, activity.NewValue);
base.Action = ViewProfile = () =>
{
Action?.Invoke();
profile?.ShowUser(User);
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Status.TriggerChange();
}
private void displayStatus(UserStatus status, UserActivity activity = null)
{
const float transition_duration = 500;
if (status == null)
{
statusBar.ResizeHeightTo(0f, transition_duration, Easing.OutQuint);
statusBar.FadeOut(transition_duration, Easing.OutQuint);
this.ResizeHeightTo(height - status_height, transition_duration, Easing.OutQuint);
}
else
{
statusBar.ResizeHeightTo(status_height, transition_duration, Easing.OutQuint);
statusBar.FadeIn(transition_duration, Easing.OutQuint);
this.ResizeHeightTo(height, transition_duration, Easing.OutQuint);
}
if (status is UserStatusOnline && activity != null)
{
statusMessage.Text = activity.Status;
statusBg.FadeColour(activity.GetAppropriateColour(colours), 500, Easing.OutQuint);
}
else
{
statusMessage.Text = status?.Message;
statusBg.FadeColour(status?.GetAppropriateColour(colours) ?? colours.Gray5, 500, Easing.OutQuint);
}
}
public MenuItem[] ContextMenuItems => new MenuItem[]
{
new OsuMenuItem("View Profile", MenuItemType.Highlighted, ViewProfile),
};
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using System;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
public sealed class RegExpConstructor : ScriptFunction {
internal static readonly RegExpConstructor ob = new RegExpConstructor();
private RegExpPrototype originalPrototype;
internal ArrayPrototype arrayPrototype;
private Regex regex;
private Match lastRegexMatch;
internal Object inputString;
private String lastInput;
internal RegExpConstructor()
: base(FunctionPrototype.ob, "RegExp", 2) {
this.originalPrototype = RegExpPrototype.ob;
RegExpPrototype._constructor = this;
this.proto = RegExpPrototype.ob;
this.arrayPrototype = ArrayPrototype.ob;
this.regex = null;
this.lastRegexMatch = null;
this.inputString = "";
this.lastInput = null;
}
internal RegExpConstructor(LenientFunctionPrototype parent,
LenientRegExpPrototype prototypeProp, LenientArrayPrototype arrayPrototype)
: base(parent, "RegExp", 2) {
this.originalPrototype = prototypeProp;
prototypeProp.constructor = this;
this.proto = prototypeProp;
this.arrayPrototype = arrayPrototype;
this.regex = null;
this.lastRegexMatch = null;
this.inputString = "";
this.lastInput = null;
this.noExpando = false;
}
internal override Object Call(Object[] args, Object thisob) {
return this.Invoke(args);
}
internal override Object Construct(Object[] args) {
return this.CreateInstance(args);
}
private RegExpObject ConstructNew(Object[] args) {
String source = args.Length > 0 && args[0] != null ? Convert.ToString(args[0]) : "";
if (args.Length > 0 && args[0] is Regex)
throw new JScriptException(JSError.TypeMismatch);
bool ignoreCase = false;
bool global = false;
bool multiline = false;
if (args.Length >= 2 && args[1] != null) {
String flags = Convert.ToString(args[1]);
for (int i = 0; i < flags.Length; i++) {
switch (flags[i]) {
case 'i':
ignoreCase = true;
continue;
case 'g':
global = true;
continue;
case 'm':
multiline = true;
continue;
}
throw new JScriptException(JSError.RegExpSyntax);
}
}
return new RegExpObject(this.originalPrototype,
source, ignoreCase, global, multiline, this);
}
public Object Construct(String pattern, bool ignoreCase, bool global, bool multiline) {
return new RegExpObject(this.originalPrototype,
pattern, ignoreCase, global, multiline, this);
}
[JSFunctionAttribute(JSFunctionAttributeEnum.HasVarArgs)]
public new RegExpObject CreateInstance(params Object[] args){
RegExpObject regExpObject;
if (args == null || args.Length <= 0 || (regExpObject = args[0] as RegExpObject) == null)
return ConstructNew(args);
if (args.Length > 1 && args[1] != null)
throw new JScriptException(JSError.RegExpSyntax);
return new RegExpObject(this.originalPrototype, regExpObject.source,
regExpObject.ignoreCase, regExpObject.global, regExpObject.multiline, this);
}
[JSFunctionAttribute(JSFunctionAttributeEnum.HasVarArgs)]
public RegExpObject Invoke(params Object[] args){
RegExpObject regExpObject;
if (args == null || args.Length <= 0 || (regExpObject = args[0] as RegExpObject) == null)
return ConstructNew(args);
if (args.Length > 1 && args[1] != null)
throw new JScriptException(JSError.RegExpSyntax);
return regExpObject;
}
private Object GetIndex() {
return this.lastRegexMatch == null ? -1 : this.lastRegexMatch.Index;
}
private Object GetInput() {
return this.inputString;
}
private Object GetLastIndex() {
return this.lastRegexMatch == null ? -1
: this.lastRegexMatch.Length == 0 ? this.lastRegexMatch.Index + 1
: this.lastRegexMatch.Index + this.lastRegexMatch.Length;
}
private Object GetLastMatch() {
return this.lastRegexMatch == null ? "" : this.lastRegexMatch.ToString();
}
private Object GetLastParen() {
if (this.regex == null || this.lastRegexMatch == null)
return "";
String[] groupNames = this.regex.GetGroupNames();
if (groupNames.Length <= 1)
return "";
int lastGroupNumber = this.regex.GroupNumberFromName(
groupNames[groupNames.Length - 1]);
Group group = this.lastRegexMatch.Groups[lastGroupNumber];
return group.Success ? group.ToString() : "";
}
private Object GetLeftContext() {
return this.lastRegexMatch == null || this.lastInput == null ? "" : this.lastInput.Substring(0, this.lastRegexMatch.Index);
}
internal override Object GetMemberValue(String name) {
if (name.Length == 2 && name[0] == '$') {
char ch = name[1];
switch (ch) {
case '1': case '2': case '3':
case '4': case '5': case '6':
case '7': case '8': case '9': {
if (this.lastRegexMatch == null)
return "";
Group group = this.lastRegexMatch.Groups[ch.ToString()];
return group.Success ? group.ToString() : "";
}
case '`':
return this.GetLeftContext();
case '\'':
return this.GetRightContext();
case '&':
return this.GetLastMatch();
case '+':
return this.GetLastParen();
case '_':
return this.GetInput();
}
}
return base.GetMemberValue(name);
}
private Object GetRightContext() {
return this.lastRegexMatch == null || this.lastInput == null
? ""
: this.lastInput.Substring(this.lastRegexMatch.Index + this.lastRegexMatch.Length);
}
private void SetInput(Object value) {
this.inputString = value;
}
internal override void SetMemberValue(String name, Object value) {
if (this.noExpando)
throw new JScriptException(JSError.AssignmentToReadOnly);
if (name.Length == 2 && name[0] == '$') {
switch (name[1]) {
case '1': case '2': case '3':
case '4': case '5': case '6':
case '7': case '8': case '9':
case '`':
case '\'':
case '&':
case '+':
return;
case '_':
this.SetInput(value);
return;
}
}
base.SetMemberValue(name, value);
}
internal int UpdateConstructor(Regex regex, Match match, String input) {
if (!this.noExpando) {
this.regex = regex;
this.lastRegexMatch = match;
this.inputString = input;
this.lastInput = input;
}
return match.Length == 0
? match.Index + 1
: match.Index + match.Length;
}
public Object index {
get { return this.GetIndex(); }
}
public Object input {
get {
return this.GetInput();
}
set {
if (this.noExpando)
throw new JScriptException(JSError.AssignmentToReadOnly);
this.SetInput(value);
}
}
public Object lastIndex {
get { return this.GetLastIndex(); }
}
public Object lastMatch {
get { return this.GetLastMatch(); }
}
public Object lastParen {
get { return this.GetLastParen(); }
}
public Object leftContext {
get { return this.GetLeftContext(); }
}
public Object rightContext {
get { return this.GetRightContext(); }
}
}
}
| |
using Xilium.CefGlue;
namespace NetDimension.NanUI.Browser;
internal sealed class WinFormiumRequestHandler : CefRequestHandler
{
private Formium _owner;
public WinFormiumRequestHandler(Formium owner)
{
_owner = owner;
}
protected override CefResourceRequestHandler GetResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
var e = new GetResourceRequestHandlerEventArgs(browser, frame, request, isNavigation, isDownload, requestInitiator);
_owner.OnGetResourceRequestHandler(e);
disableDefaultHandling = e.DisableDefaultHandling;
return e.Handler;
}
protected override bool OnBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, bool userGesture, bool isRedirect)
{
if (frame.IsMain)
{
//_owner.AttachToChromeWidgetMessageHandler();
var region = _owner.WebView?.DraggableRegion;
if (region != null)
{
region.Dispose();
_owner.WebView.DraggableRegion = null;
}
//_owner.WebView.IsReady = false;
}
_owner.WebView.MessageBridge.OnBeforeBrowse(browser, frame);
var e = new BeforeBrowseEventArgs(browser, frame, request, userGesture, isRedirect);
_owner.InvokeIfRequired(() => _owner.OnBeforeBrowse(e));
return e.Cancelled;
}
protected override bool GetAuthCredentials(CefBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, CefAuthCallback callback)
{
//TODO: A custom dialog should be implemented to get username and password here.
var e = new AuthCredentialsEventArgs(originUrl, isProxy, host, port, realm, scheme, callback);
_owner.InvokeIfRequired(() => _owner.OnGetAuthCredentials(e));
return !e.CancelRequestImmediately;
}
protected override bool OnCertificateError(CefBrowser browser, CefErrorCode certError, string requestUrl, CefSslInfo sslInfo, CefRequestCallback callback)
{
var e = new CertificateErrorEventArgs(certError, requestUrl, sslInfo, callback);
_owner.InvokeIfRequired(() => _owner.OnCertificateError(e));
return !e.CancelRequestImmediately;
}
protected override void OnRenderProcessTerminated(CefBrowser browser, CefTerminationStatus status)
{
var e = new RenderProcessTerminatedEventArgs(browser, status);
_owner.InvokeIfRequired(() => _owner.OnRenderProcessTerminated(e));
_owner.WebView.MessageBridge.OnRenderProcessTerminated(browser);
if (e.ShouldTryResetProcess && status != CefTerminationStatus.Termination)
{
browser.Reload();
//_owner.AttachToChromeWidgetMessageHandler();
}
}
//protected override bool OnSelectClientCertificate(CefBrowser browser, bool isProxy, string host, int port, CefX509Certificate[] certificates, CefSelectClientCertificateCallback callback)
//{
// return base.OnSelectClientCertificate(browser, isProxy, host, port, certificates, callback);
//}
protected override bool OnOpenUrlFromTab(CefBrowser browser, CefFrame frame, string targetUrl, CefWindowOpenDisposition targetDisposition, bool userGesture)
{
return base.OnOpenUrlFromTab(browser, frame, targetUrl, targetDisposition, userGesture);
}
}
public sealed class GetResourceRequestHandlerEventArgs : EventArgs
{
private readonly CefBrowser _browser;
internal GetResourceRequestHandlerEventArgs(CefBrowser browser, CefFrame frame, CefRequest request, bool isNavigation, bool isDownload, string requestInitiator)
{
_browser = browser;
Frame = frame;
Request = request;
IsNavigation = isNavigation;
IsDownload = isDownload;
RequestInitiator = requestInitiator;
}
public bool DisableDefaultHandling { get; set; } = false;
public CefFrame Frame { get; }
public CefRequest Request { get; }
public bool IsNavigation { get; }
public bool IsDownload { get; }
public string RequestInitiator { get; }
public CefResourceRequestHandler Handler { get; set; }
}
public sealed class BeforeBrowseEventArgs : EventArgs
{
internal BeforeBrowseEventArgs(CefBrowser browser, CefFrame frame, CefRequest request, bool userGesture, bool isRedirect)
{
_browser = browser;
Frame = frame;
Request = request;
UserGesture = userGesture;
IsRedirect = isRedirect;
}
private readonly CefBrowser _browser;
public CefFrame Frame { get; }
public CefRequest Request { get; }
public bool UserGesture { get; }
public bool IsRedirect { get; }
public bool Cancelled { get; set; } = false;
}
public sealed class RenderProcessTerminatedEventArgs : EventArgs
{
private readonly CefBrowser _browser;
internal RenderProcessTerminatedEventArgs(CefBrowser browser, CefTerminationStatus status)
{
_browser = browser;
Status = status;
}
public bool ShouldTryResetProcess { get; set; }
public CefTerminationStatus Status { get; }
}
public sealed class CertificateErrorEventArgs : EventArgs
{
private readonly CefRequestCallback _callback;
internal CertificateErrorEventArgs(CefErrorCode certError, string requestUrl, CefSslInfo sslInfo, CefRequestCallback callback)
{
CertError = certError;
RequestUrl = requestUrl;
SslInfo = sslInfo;
_callback = callback;
}
public CefErrorCode CertError { get; }
public string RequestUrl { get; }
public CefSslInfo SslInfo { get; }
public void Continue(bool requestAllowed) => _callback?.Continue(requestAllowed);
public void Cancel() => _callback?.Cancel();
public bool CancelRequestImmediately { get; set; } = false;
}
public sealed class AuthCredentialsEventArgs : EventArgs
{
private readonly CefAuthCallback _callback;
internal AuthCredentialsEventArgs(string originUrl, bool isProxy, string host, int port, string realm, string scheme, CefAuthCallback callback)
{
OriginUrl = originUrl;
IsProxy = isProxy;
Host = host;
Port = port;
Realm = realm;
Scheme = scheme;
_callback = callback;
}
public string OriginUrl { get; }
public bool IsProxy { get; }
public string Host { get; }
public int Port { get; }
public string Realm { get; }
public string Scheme { get; }
public void Continue(string userName, string password) => _callback?.Continue(userName, password);
public void Cancel() => _callback?.Cancel();
public bool CancelRequestImmediately { get; set; } = false;
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Dfm.MarkdownValidators;
using Microsoft.DocAsCode.MarkdownLite;
using Microsoft.DocAsCode.Plugins;
public class DfmEngineBuilder : GfmEngineBuilder
{
private readonly string _baseDir;
private IReadOnlyList<string> _fallbackFolders;
public DfmEngineBuilder(Options options, string baseDir = null, string templateDir = null, IReadOnlyList<string> fallbackFolders = null)
: this(options, baseDir, templateDir, fallbackFolders, null)
{
}
public DfmEngineBuilder(Options options, string baseDir, string templateDir, IReadOnlyList<string> fallbackFolders, ICompositionContainer container) : base(options)
{
_baseDir = baseDir ?? string.Empty;
_fallbackFolders = fallbackFolders ?? new List<string>();
var inlineRules = InlineRules.ToList();
// xref auto link must be before MarkdownAutoLinkInlineRule
var index = inlineRules.FindIndex(s => s is MarkdownAutoLinkInlineRule);
if (index < 0)
{
throw new ArgumentException("MarkdownAutoLinkInlineRule should exist!");
}
inlineRules.Insert(index, new DfmXrefAutoLinkInlineRule());
index = inlineRules.FindLastIndex(s => s is MarkdownLinkInlineRule);
if (index < 0)
{
throw new ArgumentException("MarkdownLinkInlineRule should exist!");
}
inlineRules.Insert(index + 1, new DfmXrefShortcutInlineRule());
inlineRules.Insert(index + 1, new DfmEmailInlineRule());
inlineRules.Insert(index + 1, new DfmFencesInlineRule());
// xref link inline rule must be before MarkdownLinkInlineRule
inlineRules.Insert(index, new DfmIncludeInlineRule());
Replace<MarkdownTextInlineRule, DfmTextInlineRule>(inlineRules);
var blockRules = BlockRules.ToList();
index = blockRules.FindLastIndex(s => s is MarkdownCodeBlockRule);
if (index < 0)
{
throw new ArgumentException("MarkdownNewLineBlockRule should exist!");
}
blockRules.InsertRange(
index + 1,
new IMarkdownRule[]
{
new DfmIncludeBlockRule(),
new DfmVideoBlockRule(),
new DfmYamlHeaderBlockRule(),
new DfmSectionBlockRule(),
new DfmFencesBlockRule(),
new DfmNoteBlockRule()
});
Replace<MarkdownBlockquoteBlockRule, DfmBlockquoteBlockRule>(blockRules);
Replace<MarkdownTableBlockRule, DfmTableBlockRule>(blockRules);
Replace<MarkdownNpTableBlockRule, DfmNpTableBlockRule>(blockRules);
InlineRules = inlineRules.ToImmutableList();
BlockRules = blockRules.ToImmutableList();
Rewriter = InitMarkdownStyle(container, baseDir, templateDir);
TokenAggregators = ImmutableList.Create<IMarkdownTokenAggregator>(
new HeadingIdAggregator(),
new TabGroupAggregator());
}
private static void Replace<TSource, TReplacement>(List<IMarkdownRule> blockRules)
where TSource : IMarkdownRule
where TReplacement : IMarkdownRule, new()
{
var index = blockRules.FindIndex(item => item is TSource);
if (index < 0)
{
throw new ArgumentException($"{typeof(TSource).Name} should exist!");
}
blockRules[index] = new TReplacement();
}
private static Func<IMarkdownRewriteEngine, DfmTabGroupBlockToken, IMarkdownToken> GetTabGroupIdRewriter()
{
var dict = new Dictionary<string, int>();
var selectedTabIds = new HashSet<string>();
return (IMarkdownRewriteEngine engine, DfmTabGroupBlockToken token) =>
{
var newToken = RewriteActiveAndVisible(
RewriteGroupId(token, dict),
selectedTabIds);
if (token == newToken)
{
return null;
}
return newToken;
};
}
private static DfmTabGroupBlockToken RewriteGroupId(DfmTabGroupBlockToken token, Dictionary<string, int> dict)
{
var groupId = token.Id;
while (true)
{
if (!dict.TryGetValue(groupId, out int index))
{
dict.Add(groupId, 1);
break;
}
else
{
dict[groupId]++;
groupId = groupId + "-" + index.ToString();
}
}
if (token.Id == groupId)
{
return token;
}
return new DfmTabGroupBlockToken(token.Rule, token.Context, groupId, token.Items, token.ActiveTabIndex, token.SourceInfo);
}
private static DfmTabGroupBlockToken RewriteActiveAndVisible(DfmTabGroupBlockToken token, HashSet<string> selectedTabIds)
{
var items = token.Items;
int firstVisibleTab = -1;
int active = -1;
for (int i = 0; i < items.Length; i++)
{
var tab = items[i];
var visible = string.IsNullOrEmpty(tab.Condition) || selectedTabIds.Contains(tab.Condition);
if (visible && firstVisibleTab == -1)
{
firstVisibleTab = i;
}
if (active == -1 && visible && selectedTabIds.Contains(tab.Id))
{
active = i;
}
if (tab.Visible != visible)
{
items = items.SetItem(i, new DfmTabItemBlockToken(tab.Rule, tab.Context, tab.Id, tab.Condition, tab.Title, tab.Content, visible, tab.SourceInfo));
}
}
if (active == -1)
{
if (firstVisibleTab != -1)
{
active = firstVisibleTab;
selectedTabIds.Add(items[firstVisibleTab].Id);
}
else
{
active = 0;
Logger.LogWarning("All tabs are hidden in the tab group.", file: token.SourceInfo.File, line: token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.NoVisibleTab);
}
}
return new DfmTabGroupBlockToken(token.Rule, token.Context, token.Id, items, active, token.SourceInfo);
}
private static IMarkdownTokenRewriter InitMarkdownStyle(ICompositionContainer container, string baseDir, string templateDir)
{
try
{
return MarkdownValidatorBuilder.Create(container, baseDir, templateDir).CreateRewriter();
}
catch (Exception ex)
{
Logger.LogWarning($"Fail to init markdown style, details:{Environment.NewLine}{ex.ToString()}");
}
return null;
}
public DfmEngine CreateDfmEngine(object renderer)
{
return new DfmEngine(
CreateParseContext().SetBaseFolder(_baseDir ?? string.Empty).SetFallbackFolders(_fallbackFolders),
MarkdownTokenRewriterFactory.Composite(
MarkdownTokenRewriterFactory.FromLambda(GetTabGroupIdRewriter()),
Rewriter),
renderer,
Options)
{
TokenTreeValidator = TokenTreeValidator,
TokenAggregators = TokenAggregators,
};
}
public override IMarkdownEngine CreateEngine(object renderer)
{
return CreateDfmEngine(renderer);
}
}
}
| |
/*
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.Web;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Diagnostics;
namespace Microsoft.Xrm.Portal.Web
{
/// <summary>
/// Builds out a url.
/// </summary>
public sealed class UrlBuilder : UriBuilder
{
private const string _urlBuilderReadOnly = "UrlBuilder is set to read-only.";
private bool _isReadOnly;
private bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
private QueryStringCollection _queryString;
public QueryStringCollection QueryString
{
get
{
if (_queryString == null)
{
_queryString = new QueryStringCollection(string.Empty);
}
return _queryString;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
_queryString = value;
}
}
public new string Query
{
get
{
return QueryString.ToString();
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
_queryString = value;
}
}
public string PathWithQueryString
{
get
{
return Path + Query;
}
}
public new Uri Uri
{
get
{
// trim the '?' because the base setter adds it
base.Query = Query.TrimStart('?');
return base.Uri;
}
}
#region UriBuilder Methods
public new string Fragment
{
get
{
return base.Fragment;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Fragment = value;
}
}
public new string Host
{
get
{
return base.Host;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Host = value;
}
}
public new string Password
{
get
{
return base.Password;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Password = value;
}
}
public new string Path
{
get
{
return base.Path;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Path = value;
}
}
public new int Port
{
get
{
return base.Port;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Port = value;
}
}
public new string Scheme
{
get
{
return base.Scheme;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.Scheme = value;
}
}
public new string UserName
{
get
{
return base.UserName;
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException(_urlBuilderReadOnly);
}
base.UserName = value;
}
}
#endregion
#region Constructors
public UrlBuilder()
{
}
public UrlBuilder(string uri)
: base(ValidateUri(uri))
{
// initialize the QueryString
Query = uri;
// special handling for tilde based paths
if (uri.StartsWith("~/"))
{
// tilde paths will have an extra leading '/'
Path = Path.TrimStart('/');
}
}
public UrlBuilder(UrlBuilder url)
: base(url.Uri)
{
}
public UrlBuilder(Uri uri)
: base(uri)
{
// initialize the QueryString
Query = uri.Query;
}
public UrlBuilder(string schemeName, string hostName)
: base(schemeName, hostName)
{
}
public UrlBuilder(string scheme, string host, int portNumber)
: base(scheme, host, portNumber)
{
}
public UrlBuilder(string scheme, string host, int port, string pathValue)
: base(scheme, host, port, pathValue)
{
}
public UrlBuilder(string scheme, string host, int port, string path, string extraValue)
: base(scheme, host, port, path, extraValue)
{
Query = extraValue;
}
public UrlBuilder(System.Web.UI.Page page)
: base(page.Request.Url.AbsoluteUri)
{
Query = page.Request.Url.Query;
}
public UrlBuilder(HttpContext context)
: base(context.Request.Url.AbsoluteUri)
{
Query = context.Request.Url.Query;
}
public UrlBuilder(HttpRequest request)
: base(request.Url.AbsoluteUri)
{
Query = request.Url.Query;
}
#endregion
public static implicit operator UrlBuilder(string url)
{
return new UrlBuilder(url);
}
public static implicit operator string(UrlBuilder url)
{
if (url == null)
{
return null;
}
return url.ToString();
}
/// <summary>
/// The name of the aspx page.
/// </summary>
public string PageName
{
get
{
string path = base.Path;
return path.Substring(path.LastIndexOf("/") + 1);
}
set
{
if (IsReadOnly)
{
throw new NotSupportedException("UrlBuilder is set to read-only.");
}
string path = base.Path;
path = path.Substring(0, path.LastIndexOf("/"));
base.Path = string.Concat(path, "/", value);
}
}
public void Redirect()
{
_Redirect(true);
}
public void Redirect(bool endResponse)
{
_Redirect(endResponse);
}
private void _Redirect(bool endResponse)
{
string uri = this.ToString();
Tracing.FrameworkInformation("UrlBuilder", "Redirect", "Redirecting to: " + uri);
HttpContext.Current.Response.Redirect(uri, endResponse);
}
public UrlBuilder Clone()
{
return new UrlBuilder(this.ToString());
}
public void EnableReadOnly()
{
this.QueryString.EnableReadOnly();
_isReadOnly = true;
}
public new string ToString()
{
base.Query = Query.TrimStart('?'); // trim the '?' because the base setter adds it
if (!Path.StartsWith("~/"))
{
return Uri.AbsoluteUri;
}
// we allow the Path to store a ~ based path which should be removed when calling ToString()
UrlBuilder temp = new UrlBuilder(this);
temp.Path = temp.Path.Remove(0, 2);
return temp.Uri.AbsoluteUri;
}
/// <summary>
/// Prepares a raw string URL to be valid for the base UriBuilder contstructor.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
private static string ValidateUri(string uri)
{
// the Uri object requires a hostname so prepend a hostname if it is missing
if (uri.StartsWith("/") || uri.StartsWith("~/"))
{
// tilde based paths are allowed but we need to first add a leading '/'
if (uri.StartsWith("~/"))
{
uri = "/" + uri;
}
// a host name is required by the UriBuilder base class
if (HttpContext.Current != null)
{
var httpHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
if (httpHost == null)
{
// fail back on SERVER_NAME in case HTTP_HOST was not provided
// ezGDS fix - possibly related to their F5 configuration, but a safe assumption
// because if this is null, the next line will throw an error anyways
httpHost = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
}
var url = HttpContext.Current.Request.Url;
var hostAndPort = httpHost.Contains(":") ? httpHost : httpHost + ":" + url.Port;
// include the current protocol (scheme) value and port
uri = "{0}://{1}{2}".FormatWith(
url.Scheme,
hostAndPort,
uri);
}
else
{
uri = "localhost" + uri;
}
}
return uri;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.