context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']"
[global::Android.Runtime.Register ("org/apache/cordova/CordovaWebViewClient", DoNotGenerateAcw=true)]
public partial class CordovaWebViewClient : global::Android.Webkit.WebViewClient {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/CordovaWebViewClient", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CordovaWebViewClient); }
}
protected CordovaWebViewClient (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lorg_apache_cordova_CordovaInterface_Lorg_apache_cordova_CordovaWebView_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/constructor[@name='CordovaWebViewClient' and count(parameter)=2 and parameter[1][@type='org.apache.cordova.CordovaInterface'] and parameter[2][@type='org.apache.cordova.CordovaWebView']]"
[Register (".ctor", "(Lorg/apache/cordova/CordovaInterface;Lorg/apache/cordova/CordovaWebView;)V", "")]
public CordovaWebViewClient (global::Org.Apache.Cordova.ICordovaInterface p0, global::Org.Apache.Cordova.CordovaWebView p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (CordovaWebViewClient)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/CordovaInterface;Lorg/apache/cordova/CordovaWebView;)V", new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/CordovaInterface;Lorg/apache/cordova/CordovaWebView;)V", new JValue (p0), new JValue (p1));
return;
}
if (id_ctor_Lorg_apache_cordova_CordovaInterface_Lorg_apache_cordova_CordovaWebView_ == IntPtr.Zero)
id_ctor_Lorg_apache_cordova_CordovaInterface_Lorg_apache_cordova_CordovaWebView_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/CordovaInterface;Lorg/apache/cordova/CordovaWebView;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_CordovaInterface_Lorg_apache_cordova_CordovaWebView_, new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_CordovaInterface_Lorg_apache_cordova_CordovaWebView_, new JValue (p0), new JValue (p1));
}
static IntPtr id_ctor_Lorg_apache_cordova_CordovaInterface_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/constructor[@name='CordovaWebViewClient' and count(parameter)=1 and parameter[1][@type='org.apache.cordova.CordovaInterface']]"
[Register (".ctor", "(Lorg/apache/cordova/CordovaInterface;)V", "")]
public CordovaWebViewClient (global::Org.Apache.Cordova.ICordovaInterface p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (CordovaWebViewClient)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/apache/cordova/CordovaInterface;)V", new JValue (p0)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/apache/cordova/CordovaInterface;)V", new JValue (p0));
return;
}
if (id_ctor_Lorg_apache_cordova_CordovaInterface_ == IntPtr.Zero)
id_ctor_Lorg_apache_cordova_CordovaInterface_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/apache/cordova/CordovaInterface;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_apache_cordova_CordovaInterface_, new JValue (p0)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_apache_cordova_CordovaInterface_, new JValue (p0));
}
static Delegate cb_clearAuthenticationTokens;
#pragma warning disable 0169
static Delegate GetClearAuthenticationTokensHandler ()
{
if (cb_clearAuthenticationTokens == null)
cb_clearAuthenticationTokens = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ClearAuthenticationTokens);
return cb_clearAuthenticationTokens;
}
static void n_ClearAuthenticationTokens (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CordovaWebViewClient __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebViewClient> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ClearAuthenticationTokens ();
}
#pragma warning restore 0169
static IntPtr id_clearAuthenticationTokens;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/method[@name='clearAuthenticationTokens' and count(parameter)=0]"
[Register ("clearAuthenticationTokens", "()V", "GetClearAuthenticationTokensHandler")]
public virtual void ClearAuthenticationTokens ()
{
if (id_clearAuthenticationTokens == IntPtr.Zero)
id_clearAuthenticationTokens = JNIEnv.GetMethodID (class_ref, "clearAuthenticationTokens", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_clearAuthenticationTokens);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "clearAuthenticationTokens", "()V"));
}
static Delegate cb_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetGetAuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == null)
cb_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_GetAuthenticationToken_Ljava_lang_String_Ljava_lang_String_);
return cb_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
}
static IntPtr n_GetAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Apache.Cordova.CordovaWebViewClient __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebViewClient> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetAuthenticationToken (p0, p1));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/method[@name='getAuthenticationToken' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]"
[Register ("getAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;", "GetGetAuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual global::Org.Apache.Cordova.AuthenticationToken GetAuthenticationToken (string p0, string p1)
{
if (id_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "getAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
global::Org.Apache.Cordova.AuthenticationToken __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.AuthenticationToken> (JNIEnv.CallObjectMethod (Handle, id_getAuthenticationToken_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.AuthenticationToken> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;"), new JValue (native_p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
return __ret;
}
static Delegate cb_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetRemoveAuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == null)
cb_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_RemoveAuthenticationToken_Ljava_lang_String_Ljava_lang_String_);
return cb_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
}
static IntPtr n_RemoveAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Apache.Cordova.CordovaWebViewClient __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebViewClient> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.RemoveAuthenticationToken (p0, p1));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/method[@name='removeAuthenticationToken' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]"
[Register ("removeAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;", "GetRemoveAuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual global::Org.Apache.Cordova.AuthenticationToken RemoveAuthenticationToken (string p0, string p1)
{
if (id_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "removeAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
global::Org.Apache.Cordova.AuthenticationToken __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.AuthenticationToken> (JNIEnv.CallObjectMethod (Handle, id_removeAuthenticationToken_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.AuthenticationToken> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "removeAuthenticationToken", "(Ljava/lang/String;Ljava/lang/String;)Lorg/apache/cordova/AuthenticationToken;"), new JValue (native_p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
return __ret;
}
static Delegate cb_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSetAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == null)
cb_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_SetAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_);
return cb_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
}
static void n_SetAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2)
{
global::Org.Apache.Cordova.CordovaWebViewClient __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebViewClient> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Apache.Cordova.AuthenticationToken p0 = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.AuthenticationToken> (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
__this.SetAuthenticationToken (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/method[@name='setAuthenticationToken' and count(parameter)=3 and parameter[1][@type='org.apache.cordova.AuthenticationToken'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]"
[Register ("setAuthenticationToken", "(Lorg/apache/cordova/AuthenticationToken;Ljava/lang/String;Ljava/lang/String;)V", "GetSetAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual void SetAuthenticationToken (global::Org.Apache.Cordova.AuthenticationToken p0, string p1, string p2)
{
if (id_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setAuthenticationToken", "(Lorg/apache/cordova/AuthenticationToken;Ljava/lang/String;Ljava/lang/String;)V");
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setAuthenticationToken_Lorg_apache_cordova_AuthenticationToken_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setAuthenticationToken", "(Lorg/apache/cordova/AuthenticationToken;Ljava/lang/String;Ljava/lang/String;)V"), new JValue (p0), new JValue (native_p1), new JValue (native_p2));
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
}
static Delegate cb_setWebView_Lorg_apache_cordova_CordovaWebView_;
#pragma warning disable 0169
static Delegate GetSetWebView_Lorg_apache_cordova_CordovaWebView_Handler ()
{
if (cb_setWebView_Lorg_apache_cordova_CordovaWebView_ == null)
cb_setWebView_Lorg_apache_cordova_CordovaWebView_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetWebView_Lorg_apache_cordova_CordovaWebView_);
return cb_setWebView_Lorg_apache_cordova_CordovaWebView_;
}
static void n_SetWebView_Lorg_apache_cordova_CordovaWebView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CordovaWebViewClient __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebViewClient> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Apache.Cordova.CordovaWebView p0 = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaWebView> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.SetWebView (p0);
}
#pragma warning restore 0169
static IntPtr id_setWebView_Lorg_apache_cordova_CordovaWebView_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaWebViewClient']/method[@name='setWebView' and count(parameter)=1 and parameter[1][@type='org.apache.cordova.CordovaWebView']]"
[Register ("setWebView", "(Lorg/apache/cordova/CordovaWebView;)V", "GetSetWebView_Lorg_apache_cordova_CordovaWebView_Handler")]
public virtual void SetWebView (global::Org.Apache.Cordova.CordovaWebView p0)
{
if (id_setWebView_Lorg_apache_cordova_CordovaWebView_ == IntPtr.Zero)
id_setWebView_Lorg_apache_cordova_CordovaWebView_ = JNIEnv.GetMethodID (class_ref, "setWebView", "(Lorg/apache/cordova/CordovaWebView;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setWebView_Lorg_apache_cordova_CordovaWebView_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setWebView", "(Lorg/apache/cordova/CordovaWebView;)V"), new JValue (p0));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Console;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Services.UserAccountService
{
public class UserAccountService : UserAccountServiceBase, IUserAccountService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly UUID UUID_GRID_GOD = new UUID("6571e388-6218-4574-87db-f9379718315e");
private static UserAccountService m_RootInstance;
/// <summary>
/// Should we create default entries (minimum body parts/clothing, avatar wearable entries) for a new avatar?
/// </summary>
private bool m_CreateDefaultAvatarEntries;
protected IGridService m_GridService;
protected IAuthenticationService m_AuthenticationService;
protected IGridUserService m_GridUserService;
protected IInventoryService m_InventoryService;
protected IAvatarService m_AvatarService;
public UserAccountService(IConfigSource config)
: base(config)
{
IConfig userConfig = config.Configs["UserAccountService"];
if (userConfig == null)
throw new Exception("No UserAccountService configuration");
string gridServiceDll = userConfig.GetString("GridService", string.Empty);
if (gridServiceDll != string.Empty)
m_GridService = LoadPlugin<IGridService>(gridServiceDll, new Object[] { config });
string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty);
if (authServiceDll != string.Empty)
m_AuthenticationService = LoadPlugin<IAuthenticationService>(authServiceDll, new Object[] { config });
string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty);
if (presenceServiceDll != string.Empty)
m_GridUserService = LoadPlugin<IGridUserService>(presenceServiceDll, new Object[] { config });
string invServiceDll = userConfig.GetString("InventoryService", string.Empty);
if (invServiceDll != string.Empty)
m_InventoryService = LoadPlugin<IInventoryService>(invServiceDll, new Object[] { config });
string avatarServiceDll = userConfig.GetString("AvatarService", string.Empty);
if (avatarServiceDll != string.Empty)
m_AvatarService = LoadPlugin<IAvatarService>(avatarServiceDll, new Object[] { config });
m_CreateDefaultAvatarEntries = userConfig.GetBoolean("CreateDefaultAvatarEntries", false);
// create a system grid god account
UserAccount ggod = GetUserAccount(UUID.Zero, UUID_GRID_GOD);
if(ggod == null)
{
UserAccountData d = new UserAccountData();
d.FirstName = "GRID";
d.LastName = "SERVICES";
d.PrincipalID = UUID_GRID_GOD;
d.ScopeID = UUID.Zero;
d.Data = new Dictionary<string, string>();
d.Data["Email"] = string.Empty;
d.Data["Created"] = Util.UnixTimeSinceEpoch().ToString();
d.Data["UserLevel"] = "240";
d.Data["UserFlags"] = "0";
d.Data["ServiceURLs"] = string.Empty;
m_Database.Store(d);
}
if (m_RootInstance == null)
{
m_RootInstance = this;
// In case there are several instances of this class in the same process,
// the console commands are only registered for the root instance
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Users", false,
"create user",
"create user [<first> [<last> [<pass> [<email> [<user id> [<model>]]]]]]",
"Create a new user", HandleCreateUser);
MainConsole.Instance.Commands.AddCommand("Users", false,
"reset user password",
"reset user password [<first> [<last> [<password>]]]",
"Reset a user password", HandleResetUserPassword);
MainConsole.Instance.Commands.AddCommand("Users", false,
"reset user email",
"reset user email [<first> [<last> [<email>]]]",
"Reset a user email address", HandleResetUserEmail);
MainConsole.Instance.Commands.AddCommand("Users", false,
"set user level",
"set user level [<first> [<last> [<level>]]]",
"Set user level. If >= 200 and 'allow_grid_gods = true' in OpenSim.ini, "
+ "this account will be treated as god-moded. "
+ "It will also affect the 'login level' command. ",
HandleSetUserLevel);
MainConsole.Instance.Commands.AddCommand("Users", false,
"show account",
"show account <first> <last>",
"Show account details for the given user", HandleShowAccount);
}
}
}
#region IUserAccountService
public UserAccount GetUserAccount(UUID scopeID, string firstName,
string lastName)
{
// m_log.DebugFormat(
// "[USER ACCOUNT SERVICE]: Retrieving account by username for {0} {1}, scope {2}",
// firstName, lastName, scopeID);
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "FirstName", "LastName" },
new string[] { scopeID.ToString(), firstName, lastName });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "FirstName", "LastName" },
new string[] { UUID.Zero.ToString(), firstName, lastName });
}
}
else
{
d = m_Database.Get(
new string[] { "FirstName", "LastName" },
new string[] { firstName, lastName });
}
if (d.Length < 1)
return null;
return MakeUserAccount(d[0]);
}
private UserAccount MakeUserAccount(UserAccountData d)
{
UserAccount u = new UserAccount();
u.FirstName = d.FirstName;
u.LastName = d.LastName;
u.PrincipalID = d.PrincipalID;
u.ScopeID = d.ScopeID;
if (d.Data.ContainsKey("Email") && d.Data["Email"] != null)
u.Email = d.Data["Email"].ToString();
else
u.Email = string.Empty;
u.Created = Convert.ToInt32(d.Data["Created"].ToString());
if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null)
u.UserTitle = d.Data["UserTitle"].ToString();
else
u.UserTitle = string.Empty;
if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null)
Int32.TryParse(d.Data["UserLevel"], out u.UserLevel);
if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null)
Int32.TryParse(d.Data["UserFlags"], out u.UserFlags);
if (d.Data.ContainsKey("UserCountry") && d.Data["UserCountry"] != null)
u.UserCountry = d.Data["UserCountry"].ToString();
else
u.UserCountry = string.Empty;
if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null)
{
string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' });
u.ServiceURLs = new Dictionary<string, object>();
foreach (string url in URLs)
{
string[] parts = url.Split(new char[] { '=' });
if (parts.Length != 2)
continue;
string name = System.Web.HttpUtility.UrlDecode(parts[0]);
string val = System.Web.HttpUtility.UrlDecode(parts[1]);
u.ServiceURLs[name] = val;
}
}
else
u.ServiceURLs = new Dictionary<string, object>();
return u;
}
public UserAccount GetUserAccount(UUID scopeID, string email)
{
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "Email" },
new string[] { scopeID.ToString(), email });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "Email" },
new string[] { UUID.Zero.ToString(), email });
}
}
else
{
d = m_Database.Get(
new string[] { "Email" },
new string[] { email });
}
if (d.Length < 1)
return null;
return MakeUserAccount(d[0]);
}
public UserAccount GetUserAccount(UUID scopeID, UUID principalID)
{
UserAccountData[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new string[] { "ScopeID", "PrincipalID" },
new string[] { scopeID.ToString(), principalID.ToString() });
if (d.Length < 1)
{
d = m_Database.Get(
new string[] { "ScopeID", "PrincipalID" },
new string[] { UUID.Zero.ToString(), principalID.ToString() });
}
}
else
{
d = m_Database.Get(
new string[] { "PrincipalID" },
new string[] { principalID.ToString() });
}
if (d.Length < 1)
{
return null;
}
return MakeUserAccount(d[0]);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, List<string> IDs)
{
// do it one at a time db access should be fast, so no need to break its api
List<UserAccount> accs = new List<UserAccount>();
UUID uuid = UUID.Zero;
foreach(string id in IDs)
{
if (UUID.TryParse(id, out uuid) && uuid != UUID.Zero)
accs.Add(GetUserAccount(scopeID, uuid));
}
return accs;
}
public void InvalidateCache(UUID userID)
{
}
public bool StoreUserAccount(UserAccount data)
{
// m_log.DebugFormat(
// "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}",
// data.FirstName, data.LastName, data.PrincipalID, data.ScopeID);
UserAccountData d = new UserAccountData();
d.FirstName = data.FirstName;
d.LastName = data.LastName;
d.PrincipalID = data.PrincipalID;
d.ScopeID = data.ScopeID;
d.Data = new Dictionary<string, string>();
d.Data["Email"] = data.Email;
d.Data["Created"] = data.Created.ToString();
d.Data["UserLevel"] = data.UserLevel.ToString();
d.Data["UserFlags"] = data.UserFlags.ToString();
if (data.UserTitle != null)
d.Data["UserTitle"] = data.UserTitle.ToString();
List<string> parts = new List<string>();
foreach (KeyValuePair<string, object> kvp in data.ServiceURLs)
{
string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
parts.Add(key + "=" + val);
}
d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());
return m_Database.Store(d);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
UserAccountData[] d = m_Database.GetUsers(scopeID, query.Trim());
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>();
foreach (UserAccountData data in d)
ret.Add(MakeUserAccount(data));
return ret;
}
public List<UserAccount> GetUserAccountsWhere(UUID scopeID, string where)
{
UserAccountData[] d = m_Database.GetUsersWhere(scopeID, where);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>();
foreach (UserAccountData data in d)
ret.Add(MakeUserAccount(data));
return ret;
}
#endregion
#region Console commands
/// <summary>
/// Handle the create user command from the console.
/// </summary>
/// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email, userID, model name </param>
protected void HandleCreateUser(string module, string[] cmdparams)
{
string firstName;
string lastName;
string password;
string email;
string rawPrincipalId;
string model;
List<char> excluded = new List<char>(new char[]{' '});
if (cmdparams.Length < 3)
firstName = MainConsole.Instance.CmdPrompt("First name", "Default", excluded);
else firstName = cmdparams[2];
if (cmdparams.Length < 4)
lastName = MainConsole.Instance.CmdPrompt("Last name", "User", excluded);
else lastName = cmdparams[3];
if (cmdparams.Length < 5)
password = MainConsole.Instance.PasswdPrompt("Password");
else password = cmdparams[4];
if (cmdparams.Length < 6)
email = MainConsole.Instance.CmdPrompt("Email", "");
else email = cmdparams[5];
if (cmdparams.Length < 7)
rawPrincipalId = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString());
else
rawPrincipalId = cmdparams[6];
if (cmdparams.Length < 8)
model = MainConsole.Instance.CmdPrompt("Model name","");
else
model = cmdparams[7];
UUID principalId = UUID.Zero;
if (!UUID.TryParse(rawPrincipalId, out principalId))
throw new Exception(string.Format("ID {0} is not a valid UUID", rawPrincipalId));
CreateUser(UUID.Zero, principalId, firstName, lastName, password, email, model);
}
protected void HandleShowAccount(string module, string[] cmdparams)
{
if (cmdparams.Length != 4)
{
MainConsole.Instance.Output("Usage: show account <first-name> <last-name>");
return;
}
string firstName = cmdparams[2];
string lastName = cmdparams[3];
UserAccount ua = GetUserAccount(UUID.Zero, firstName, lastName);
if (ua == null)
{
MainConsole.Instance.OutputFormat("No user named {0} {1}", firstName, lastName);
return;
}
MainConsole.Instance.OutputFormat("Name: {0}", ua.Name);
MainConsole.Instance.OutputFormat("ID: {0}", ua.PrincipalID);
MainConsole.Instance.OutputFormat("Title: {0}", ua.UserTitle);
MainConsole.Instance.OutputFormat("E-mail: {0}", ua.Email);
MainConsole.Instance.OutputFormat("Created: {0}", Utils.UnixTimeToDateTime(ua.Created));
MainConsole.Instance.OutputFormat("Level: {0}", ua.UserLevel);
MainConsole.Instance.OutputFormat("Flags: {0}", ua.UserFlags);
foreach (KeyValuePair<string, Object> kvp in ua.ServiceURLs)
MainConsole.Instance.OutputFormat("{0}: {1}", kvp.Key, kvp.Value);
}
protected void HandleResetUserPassword(string module, string[] cmdparams)
{
string firstName;
string lastName;
string newPassword;
if (cmdparams.Length < 4)
firstName = MainConsole.Instance.CmdPrompt("First name");
else firstName = cmdparams[3];
if (cmdparams.Length < 5)
lastName = MainConsole.Instance.CmdPrompt("Last name");
else lastName = cmdparams[4];
if (cmdparams.Length < 6)
newPassword = MainConsole.Instance.PasswdPrompt("New password");
else newPassword = cmdparams[5];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
MainConsole.Instance.OutputFormat("No such user as {0} {1}", firstName, lastName);
return;
}
bool success = false;
if (m_AuthenticationService != null)
success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword);
if (!success)
MainConsole.Instance.OutputFormat("Unable to reset password for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.OutputFormat("Password reset for user {0} {1}", firstName, lastName);
}
protected void HandleResetUserEmail(string module, string[] cmdparams)
{
string firstName;
string lastName;
string newEmail;
if (cmdparams.Length < 4)
firstName = MainConsole.Instance.CmdPrompt("First name");
else firstName = cmdparams[3];
if (cmdparams.Length < 5)
lastName = MainConsole.Instance.CmdPrompt("Last name");
else lastName = cmdparams[4];
if (cmdparams.Length < 6)
newEmail = MainConsole.Instance.PasswdPrompt("New Email");
else newEmail = cmdparams[5];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
MainConsole.Instance.OutputFormat("No such user as {0} {1}", firstName, lastName);
return;
}
bool success = false;
account.Email = newEmail;
success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.OutputFormat("Unable to set Email for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.OutputFormat("User Email set for user {0} {1} to {2}", firstName, lastName, account.Email);
}
protected void HandleSetUserLevel(string module, string[] cmdparams)
{
string firstName;
string lastName;
string rawLevel;
int level;
if (cmdparams.Length < 4)
firstName = MainConsole.Instance.CmdPrompt("First name");
else firstName = cmdparams[3];
if (cmdparams.Length < 5)
lastName = MainConsole.Instance.CmdPrompt("Last name");
else lastName = cmdparams[4];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null) {
MainConsole.Instance.OutputFormat("No such user");
return;
}
if (cmdparams.Length < 6)
rawLevel = MainConsole.Instance.CmdPrompt("User level");
else rawLevel = cmdparams[5];
if(int.TryParse(rawLevel, out level) == false) {
MainConsole.Instance.OutputFormat("Invalid user level");
return;
}
account.UserLevel = level;
bool success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.OutputFormat("Unable to set user level for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.OutputFormat("User level set for user {0} {1} to {2}", firstName, lastName, level);
}
#endregion
/// <summary>
/// Create a user
/// </summary>
/// <param name="scopeID">Allows hosting of multiple grids in a single database. Normally left as UUID.Zero</param>
/// <param name="principalID">ID of the user</param>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="password"></param>
/// <param name="email"></param>
/// <param name="model"></param>
public UserAccount CreateUser(UUID scopeID, UUID principalID, string firstName, string lastName, string password, string email, string model = "")
{
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (null == account)
{
account = new UserAccount(UUID.Zero, principalID, firstName, lastName, email);
if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
{
account.ServiceURLs = new Dictionary<string, object>();
account.ServiceURLs["HomeURI"] = string.Empty;
account.ServiceURLs["InventoryServerURI"] = string.Empty;
account.ServiceURLs["AssetServerURI"] = string.Empty;
}
if (StoreUserAccount(account))
{
bool success;
if (m_AuthenticationService != null)
{
success = m_AuthenticationService.SetPassword(account.PrincipalID, password);
if (!success)
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
firstName, lastName);
}
GridRegion home = null;
if (m_GridService != null)
{
List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero);
if (defaultRegions != null && defaultRegions.Count >= 1)
home = defaultRegions[0];
if (m_GridUserService != null && home != null)
m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
else
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
firstName, lastName);
}
else
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
firstName, lastName);
}
if (m_InventoryService != null)
{
success = m_InventoryService.CreateUserInventory(account.PrincipalID);
if (!success)
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
firstName, lastName);
}
else
{
m_log.DebugFormat(
"[USER ACCOUNT SERVICE]: Created user inventory for {0} {1}", firstName, lastName);
}
if (m_CreateDefaultAvatarEntries)
{
if (String.IsNullOrEmpty(model))
CreateDefaultAppearanceEntries(account.PrincipalID);
else
EstablishAppearance(account.PrincipalID, model);
}
}
m_log.InfoFormat(
"[USER ACCOUNT SERVICE]: Account {0} {1} {2} created successfully",
firstName, lastName, account.PrincipalID);
}
else
{
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0} {1}", firstName, lastName);
}
}
else
{
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName);
}
return account;
}
protected void CreateDefaultAppearanceEntries(UUID principalID)
{
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default appearance items for {0}", principalID);
InventoryFolderBase bodyPartsFolder = m_InventoryService.GetFolderForType(principalID, FolderType.BodyPart);
// Get Current Outfit folder
InventoryFolderBase currentOutfitFolder = m_InventoryService.GetFolderForType(principalID, FolderType.CurrentOutfit);
InventoryItemBase eyes = new InventoryItemBase(UUID.Random(), principalID);
eyes.AssetID = AvatarWearable.DEFAULT_EYES_ASSET;
eyes.Name = "Default Eyes";
eyes.CreatorId = principalID.ToString();
eyes.AssetType = (int)AssetType.Bodypart;
eyes.InvType = (int)InventoryType.Wearable;
eyes.Folder = bodyPartsFolder.ID;
eyes.BasePermissions = (uint)PermissionMask.All;
eyes.CurrentPermissions = (uint)PermissionMask.All;
eyes.EveryOnePermissions = (uint)PermissionMask.All;
eyes.GroupPermissions = (uint)PermissionMask.All;
eyes.NextPermissions = (uint)PermissionMask.All;
eyes.Flags = (uint)WearableType.Eyes;
m_InventoryService.AddItem(eyes);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Eyes, eyes.Name, eyes.ID, principalID, currentOutfitFolder.ID);
InventoryItemBase shape = new InventoryItemBase(UUID.Random(), principalID);
shape.AssetID = AvatarWearable.DEFAULT_BODY_ASSET;
shape.Name = "Default Shape";
shape.CreatorId = principalID.ToString();
shape.AssetType = (int)AssetType.Bodypart;
shape.InvType = (int)InventoryType.Wearable;
shape.Folder = bodyPartsFolder.ID;
shape.BasePermissions = (uint)PermissionMask.All;
shape.CurrentPermissions = (uint)PermissionMask.All;
shape.EveryOnePermissions = (uint)PermissionMask.All;
shape.GroupPermissions = (uint)PermissionMask.All;
shape.NextPermissions = (uint)PermissionMask.All;
shape.Flags = (uint)WearableType.Shape;
m_InventoryService.AddItem(shape);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Shape, shape.Name, shape.ID, principalID, currentOutfitFolder.ID);
InventoryItemBase skin = new InventoryItemBase(UUID.Random(), principalID);
skin.AssetID = AvatarWearable.DEFAULT_SKIN_ASSET;
skin.Name = "Default Skin";
skin.CreatorId = principalID.ToString();
skin.AssetType = (int)AssetType.Bodypart;
skin.InvType = (int)InventoryType.Wearable;
skin.Folder = bodyPartsFolder.ID;
skin.BasePermissions = (uint)PermissionMask.All;
skin.CurrentPermissions = (uint)PermissionMask.All;
skin.EveryOnePermissions = (uint)PermissionMask.All;
skin.GroupPermissions = (uint)PermissionMask.All;
skin.NextPermissions = (uint)PermissionMask.All;
skin.Flags = (uint)WearableType.Skin;
m_InventoryService.AddItem(skin);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Skin, skin.Name, skin.ID, principalID, currentOutfitFolder.ID);
InventoryItemBase hair = new InventoryItemBase(UUID.Random(), principalID);
hair.AssetID = AvatarWearable.DEFAULT_HAIR_ASSET;
hair.Name = "Default Hair";
hair.CreatorId = principalID.ToString();
hair.AssetType = (int)AssetType.Bodypart;
hair.InvType = (int)InventoryType.Wearable;
hair.Folder = bodyPartsFolder.ID;
hair.BasePermissions = (uint)PermissionMask.All;
hair.CurrentPermissions = (uint)PermissionMask.All;
hair.EveryOnePermissions = (uint)PermissionMask.All;
hair.GroupPermissions = (uint)PermissionMask.All;
hair.NextPermissions = (uint)PermissionMask.All;
hair.Flags = (uint)WearableType.Hair;
m_InventoryService.AddItem(hair);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Hair, hair.Name, hair.ID, principalID, currentOutfitFolder.ID);
InventoryFolderBase clothingFolder = m_InventoryService.GetFolderForType(principalID, FolderType.Clothing);
InventoryItemBase shirt = new InventoryItemBase(UUID.Random(), principalID);
shirt.AssetID = AvatarWearable.DEFAULT_SHIRT_ASSET;
shirt.Name = "Default Shirt";
shirt.CreatorId = principalID.ToString();
shirt.AssetType = (int)AssetType.Clothing;
shirt.InvType = (int)InventoryType.Wearable;
shirt.Folder = clothingFolder.ID;
shirt.BasePermissions = (uint)PermissionMask.All;
shirt.CurrentPermissions = (uint)PermissionMask.All;
shirt.EveryOnePermissions = (uint)PermissionMask.All;
shirt.GroupPermissions = (uint)PermissionMask.All;
shirt.NextPermissions = (uint)PermissionMask.All;
shirt.Flags = (uint)WearableType.Shirt;
m_InventoryService.AddItem(shirt);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Shirt, shirt.Name, shirt.ID, principalID, currentOutfitFolder.ID);
InventoryItemBase pants = new InventoryItemBase(UUID.Random(), principalID);
pants.AssetID = AvatarWearable.DEFAULT_PANTS_ASSET;
pants.Name = "Default Pants";
pants.CreatorId = principalID.ToString();
pants.AssetType = (int)AssetType.Clothing;
pants.InvType = (int)InventoryType.Wearable;
pants.Folder = clothingFolder.ID;
pants.BasePermissions = (uint)PermissionMask.All;
pants.CurrentPermissions = (uint)PermissionMask.All;
pants.EveryOnePermissions = (uint)PermissionMask.All;
pants.GroupPermissions = (uint)PermissionMask.All;
pants.NextPermissions = (uint)PermissionMask.All;
pants.Flags = (uint)WearableType.Pants;
m_InventoryService.AddItem(pants);
CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Pants, pants.Name, pants.ID, principalID, currentOutfitFolder.ID);
if (m_AvatarService != null)
{
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default avatar entries for {0}", principalID);
AvatarWearable[] wearables = new AvatarWearable[6];
wearables[AvatarWearable.EYES] = new AvatarWearable(eyes.ID, eyes.AssetID);
wearables[AvatarWearable.BODY] = new AvatarWearable(shape.ID, shape.AssetID);
wearables[AvatarWearable.SKIN] = new AvatarWearable(skin.ID, skin.AssetID);
wearables[AvatarWearable.HAIR] = new AvatarWearable(hair.ID, hair.AssetID);
wearables[AvatarWearable.SHIRT] = new AvatarWearable(shirt.ID, shirt.AssetID);
wearables[AvatarWearable.PANTS] = new AvatarWearable(pants.ID, pants.AssetID);
AvatarAppearance ap = new AvatarAppearance();
// this loop works, but is questionable
for (int i = 0; i < 6; i++)
{
ap.SetWearable(i, wearables[i]);
}
m_AvatarService.SetAppearance(principalID, ap);
}
}
protected void EstablishAppearance(UUID destinationAgent, string model)
{
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Establishing new appearance for {0} - {1}",
destinationAgent.ToString(), model);
string[] modelSpecifiers = model.Split();
if (modelSpecifiers.Length != 2)
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Invalid model name \'{0}\'. Falling back to Ruth for {1}",
model, destinationAgent);
CreateDefaultAppearanceEntries(destinationAgent);
return;
}
// Does the source model exist?
UserAccount modelAccount = GetUserAccount(UUID.Zero, modelSpecifiers[0], modelSpecifiers[1]);
if (modelAccount == null)
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Requested model \'{0}\' not found. Falling back to Ruth for {1}",
model, destinationAgent);
CreateDefaultAppearanceEntries(destinationAgent);
return;
}
// Does the source model have an established appearance herself?
AvatarAppearance modelAppearance = m_AvatarService.GetAppearance(modelAccount.PrincipalID);
if (modelAppearance == null)
{
m_log.WarnFormat("USER ACCOUNT SERVICE]: Requested model \'{0}\' does not have an established appearance. Falling back to Ruth for {1}",
model, destinationAgent);
CreateDefaultAppearanceEntries(destinationAgent);
return;
}
try
{
CopyWearablesAndAttachments(destinationAgent, modelAccount.PrincipalID, modelAppearance);
m_AvatarService.SetAppearance(destinationAgent, modelAppearance);
}
catch (Exception e)
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Error transferring appearance for {0} : {1}",
destinationAgent, e.Message);
}
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Finished establishing appearance for {0}",
destinationAgent.ToString());
}
/// <summary>
/// This method is called by EstablishAppearance to do a copy all inventory items
/// worn or attached to the Clothing inventory folder of the receiving avatar.
/// In parallel the avatar wearables and attachments are updated.
/// </summary>
private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
{
// Get Clothing folder of receiver
InventoryFolderBase destinationFolder = m_InventoryService.GetFolderForType(destination, FolderType.Clothing);
// Get Current Outfit folder
InventoryFolderBase currentOutfitFolder = m_InventoryService.GetFolderForType(destination, FolderType.CurrentOutfit);
if (destinationFolder == null)
throw new Exception("Cannot locate folder(s)");
// Missing destination folder? This should *never* be the case
if (destinationFolder.Type != (short)FolderType.Clothing)
{
destinationFolder = new InventoryFolderBase();
destinationFolder.ID = UUID.Random();
destinationFolder.Name = "Clothing";
destinationFolder.Owner = destination;
destinationFolder.Type = (short)AssetType.Clothing;
destinationFolder.ParentID = m_InventoryService.GetRootFolder(destination).ID;
destinationFolder.Version = 1;
m_InventoryService.AddFolder(destinationFolder); // store base record
m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Created folder for destination {0}", source);
}
// Wearables
AvatarWearable[] wearables = avatarAppearance.Wearables;
AvatarWearable wearable;
for (int i = 0; i < wearables.Length; i++)
{
wearable = wearables[i];
m_log.DebugFormat("[XXX]: Getting item {0} from avie {1}", wearable[0].ItemID, source);
if (wearable[0].ItemID != UUID.Zero)
{
// Get inventory item and copy it
InventoryItemBase item = m_InventoryService.GetItem(source, wearable[0].ItemID);
if (item != null)
{
InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
destinationItem.Name = item.Name;
destinationItem.Owner = destination;
destinationItem.Description = item.Description;
destinationItem.InvType = item.InvType;
destinationItem.CreatorId = item.CreatorId;
destinationItem.CreatorData = item.CreatorData;
destinationItem.NextPermissions = item.NextPermissions;
destinationItem.CurrentPermissions = item.CurrentPermissions;
destinationItem.BasePermissions = item.BasePermissions;
destinationItem.EveryOnePermissions = item.EveryOnePermissions;
destinationItem.GroupPermissions = item.GroupPermissions;
destinationItem.AssetType = item.AssetType;
destinationItem.AssetID = item.AssetID;
destinationItem.GroupID = item.GroupID;
destinationItem.GroupOwned = item.GroupOwned;
destinationItem.SalePrice = item.SalePrice;
destinationItem.SaleType = item.SaleType;
destinationItem.Flags = item.Flags;
destinationItem.CreationDate = item.CreationDate;
destinationItem.Folder = destinationFolder.ID;
ApplyNextOwnerPermissions(destinationItem);
m_InventoryService.AddItem(destinationItem);
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
// Wear item
AvatarWearable newWearable = new AvatarWearable();
newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
avatarAppearance.SetWearable(i, newWearable);
// Add to Current Outfit
CreateCurrentOutfitLink((int)InventoryType.Wearable, item.Flags, item.Name, destinationItem.ID, destination, currentOutfitFolder.ID);
}
else
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
}
}
}
// Attachments
List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();
foreach (AvatarAttachment attachment in attachments)
{
int attachpoint = attachment.AttachPoint;
UUID itemID = attachment.ItemID;
if (itemID != UUID.Zero)
{
// Get inventory item and copy it
InventoryItemBase item = m_InventoryService.GetItem(source, itemID);
if (item != null)
{
InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
destinationItem.Name = item.Name;
destinationItem.Owner = destination;
destinationItem.Description = item.Description;
destinationItem.InvType = item.InvType;
destinationItem.CreatorId = item.CreatorId;
destinationItem.CreatorData = item.CreatorData;
destinationItem.NextPermissions = item.NextPermissions;
destinationItem.CurrentPermissions = item.CurrentPermissions;
destinationItem.BasePermissions = item.BasePermissions;
destinationItem.EveryOnePermissions = item.EveryOnePermissions;
destinationItem.GroupPermissions = item.GroupPermissions;
destinationItem.AssetType = item.AssetType;
destinationItem.AssetID = item.AssetID;
destinationItem.GroupID = item.GroupID;
destinationItem.GroupOwned = item.GroupOwned;
destinationItem.SalePrice = item.SalePrice;
destinationItem.SaleType = item.SaleType;
destinationItem.Flags = item.Flags;
destinationItem.CreationDate = item.CreationDate;
destinationItem.Folder = destinationFolder.ID;
ApplyNextOwnerPermissions(destinationItem);
m_InventoryService.AddItem(destinationItem);
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
// Attach item
avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
m_log.DebugFormat("[USER ACCOUNT SERVICE]: Attached {0}", destinationItem.ID);
// Add to Current Outfit
CreateCurrentOutfitLink(destinationItem.InvType, item.Flags, item.Name, destinationItem.ID, destination, currentOutfitFolder.ID);
}
else
{
m_log.WarnFormat("[USER ACCOUNT SERVICE]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
}
}
}
}
protected void CreateCurrentOutfitLink(int invType, uint itemType, string name, UUID itemID, UUID userID, UUID currentOutfitFolderUUID)
{
UUID LinkInvItem = UUID.Random();
InventoryItemBase itembase = new InventoryItemBase(LinkInvItem, userID)
{
AssetID = itemID,
AssetType = (int)AssetType.Link,
CreatorId = userID.ToString(),
InvType = invType,
Description = "",
//Folder = m_InventoryService.GetFolderForType(userID, FolderType.CurrentOutfit).ID,
Folder = currentOutfitFolderUUID,
Flags = itemType,
Name = name,
BasePermissions = (uint)PermissionMask.Copy,
CurrentPermissions = (uint)PermissionMask.Copy,
EveryOnePermissions = (uint)PermissionMask.Copy,
GroupPermissions = (uint)PermissionMask.Copy,
NextPermissions = (uint)PermissionMask.Copy
};
m_InventoryService.AddItem(itembase);
}
/// <summary>
/// Apply next owner permissions.
/// </summary>
private void ApplyNextOwnerPermissions(InventoryItemBase item)
{
if (item.InvType == (int)InventoryType.Object)
{
uint perms = item.CurrentPermissions;
item.CurrentPermissions = perms;
}
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryOnePermissions &= item.NextPermissions;
}
}
}
| |
using System;
using System.Globalization;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using GitHub.Authentication;
using GitHub.Extensions;
using GitHub.Extensions.Reactive;
using GitHub.Info;
using GitHub.Models;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.Validation;
using NLog;
using NullGuard;
using ReactiveUI;
namespace GitHub.ViewModels
{
public abstract class LoginTabViewModel : ReactiveObject
{
static readonly Logger log = LogManager.GetCurrentClassLogger();
protected LoginTabViewModel(IRepositoryHosts repositoryHosts, IVisualStudioBrowser browser)
{
RepositoryHosts = repositoryHosts;
UsernameOrEmailValidator = ReactivePropertyValidator.For(this, x => x.UsernameOrEmail)
.IfNullOrEmpty("Please enter your username or email address")
.IfMatch(@"\s", "Username or email address must not have spaces");
PasswordValidator = ReactivePropertyValidator.For(this, x => x.Password)
.IfNullOrEmpty("Please enter your password");
canLogin = this.WhenAny(
x => x.UsernameOrEmailValidator.ValidationResult.IsValid,
x => x.PasswordValidator.ValidationResult.IsValid,
(x, y) => x.Value && y.Value).ToProperty(this, x => x.CanLogin);
Login = ReactiveCommand.CreateAsyncObservable(this.WhenAny(x => x.CanLogin, x => x.Value), LogIn);
Login.ThrownExceptions.Subscribe(ex =>
{
if (ex.IsCriticalException()) return;
log.Info(string.Format(CultureInfo.InvariantCulture, "Error logging into '{0}' as '{1}'", BaseUri,
UsernameOrEmail), ex);
if (ex is Octokit.ForbiddenException)
{
ShowLogInFailedError = true;
LoginFailedMessage = "Make sure to use your password and not a Personal Access token to log in.";
}
else
{
ShowConnectingToHostFailed = true;
}
});
isLoggingIn = Login.IsExecuting.ToProperty(this, x => x.IsLoggingIn);
Reset = ReactiveCommand.CreateAsyncTask(_ => Clear());
NavigateForgotPassword = ReactiveCommand.CreateAsyncObservable(_ =>
{
browser.OpenUrl(new Uri(BaseUri, GitHubUrls.ForgotPasswordPath));
return Observable.Return(Unit.Default);
});
SignUp = ReactiveCommand.CreateAsyncObservable(_ =>
{
browser.OpenUrl(GitHubUrls.Plans);
return Observable.Return(Unit.Default);
});
}
protected IRepositoryHosts RepositoryHosts { get; }
protected abstract Uri BaseUri { get; }
public IReactiveCommand<Unit> SignUp { get; }
public IReactiveCommand<AuthenticationResult> Login { get; }
public IReactiveCommand<Unit> Reset { get; }
public IReactiveCommand<Unit> NavigateForgotPassword { get; }
string loginFailedMessage = "Check your username and password, then try again";
public string LoginFailedMessage
{
get { return loginFailedMessage; }
set { this.RaiseAndSetIfChanged(ref loginFailedMessage, value); }
}
string usernameOrEmail;
[AllowNull]
public string UsernameOrEmail
{
[return: AllowNull]
get
{ return usernameOrEmail; }
set { this.RaiseAndSetIfChanged(ref usernameOrEmail, value); }
}
ReactivePropertyValidator usernameOrEmailValidator;
public ReactivePropertyValidator UsernameOrEmailValidator
{
get { return usernameOrEmailValidator; }
private set { this.RaiseAndSetIfChanged(ref usernameOrEmailValidator, value); }
}
string password;
[AllowNull]
public string Password
{
[return: AllowNull]
get
{ return password; }
set { this.RaiseAndSetIfChanged(ref password, value); }
}
ReactivePropertyValidator passwordValidator;
public ReactivePropertyValidator PasswordValidator
{
get { return passwordValidator; }
private set { this.RaiseAndSetIfChanged(ref passwordValidator, value); }
}
readonly ObservableAsPropertyHelper<bool> isLoggingIn;
public bool IsLoggingIn
{
get { return isLoggingIn.Value; }
}
protected ObservableAsPropertyHelper<bool> canLogin;
public bool CanLogin
{
get { return canLogin.Value; }
}
bool showLogInFailedError;
public bool ShowLogInFailedError
{
get { return showLogInFailedError; }
protected set { this.RaiseAndSetIfChanged(ref showLogInFailedError, value); }
}
bool showConnectingToHostFailed;
public bool ShowConnectingToHostFailed
{
get { return showConnectingToHostFailed; }
set { this.RaiseAndSetIfChanged(ref showConnectingToHostFailed, value); }
}
protected abstract IObservable<AuthenticationResult> LogIn(object args);
protected IObservable<AuthenticationResult> LogInToHost(HostAddress hostAddress)
{
return Observable.Defer(() =>
{
ShowLogInFailedError = false;
ShowConnectingToHostFailed = false;
return hostAddress != null ?
RepositoryHosts.LogIn(hostAddress, UsernameOrEmail, Password)
: Observable.Return(AuthenticationResult.CredentialFailure);
})
.ObserveOn(RxApp.MainThreadScheduler)
.Do(authResult => {
switch (authResult)
{
case AuthenticationResult.CredentialFailure:
ShowLogInFailedError = true;
break;
case AuthenticationResult.VerificationFailure:
break;
case AuthenticationResult.EnterpriseServerNotFound:
ShowConnectingToHostFailed = true;
break;
}
})
.SelectMany(authResult =>
{
switch (authResult)
{
case AuthenticationResult.CredentialFailure:
case AuthenticationResult.EnterpriseServerNotFound:
case AuthenticationResult.VerificationFailure:
Password = "";
return Observable.FromAsync(PasswordValidator.ResetAsync)
.Select(_ => AuthenticationResult.CredentialFailure);
case AuthenticationResult.Success:
return Reset.ExecuteAsync()
.ContinueAfter(() => Observable.Return(AuthenticationResult.Success));
default:
return Observable.Throw<AuthenticationResult>(
new InvalidOperationException("Unknown EnterpriseLoginResult: " + authResult));
}
});
}
async Task Clear()
{
UsernameOrEmail = null;
Password = null;
await UsernameOrEmailValidator.ResetAsync();
await PasswordValidator.ResetAsync();
await ResetValidation();
ShowLogInFailedError = false;
}
protected virtual Task ResetValidation()
{
// noop
return Task.FromResult(0);
}
}
}
| |
//
// TextLayoutBackendHandler.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Lytico (http://limada.sourceforge.net)
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.CairoBackend;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Xwt.GtkBackend
{
public class GtkTextLayoutBackendHandler: TextLayoutBackendHandler
{
static Cairo.Context SharedContext;
public double Heigth = -1;
internal class PangoBackend : IDisposable
{
Pango.Layout layout;
public Pango.Layout Layout {
get {
if (hasUnassignedAttributes) {
attributes.AssignTo (layout);
hasUnassignedAttributes = false;
}
return layout;
}
set {
layout = value;
}
}
FastPangoAttrList attributes;
bool hasUnassignedAttributes = false;
public FastPangoAttrList Attributes {
get {
if (attributes == null)
attributes = new FastPangoAttrList ();
hasUnassignedAttributes = true;
return attributes;
}
private set {
attributes = value;
}
}
string text = String.Empty;
public string Text {
get {
return text;
}
set {
text = value ?? String.Empty;;
indexer = null;
if (attributes != null) {
attributes.Dispose ();
attributes = null;
}
}
}
TextIndexer indexer;
public TextIndexer TextIndexer {
get {
if (indexer == null)
indexer = new TextIndexer (Text);
return indexer;
}
}
public void ClearAttributes ()
{
if (attributes != null) {
attributes.Dispose ();
attributes = new FastPangoAttrList ();
hasUnassignedAttributes = true;
}
}
public void Dispose ()
{
if (layout != null) {
layout.Dispose ();
layout = null;
}
if (attributes != null) {
attributes.Dispose ();
attributes = null;
}
}
}
static GtkTextLayoutBackendHandler ()
{
using (Cairo.Surface sf = new Cairo.ImageSurface (Cairo.Format.ARGB32, 1, 1)) {
SharedContext = new Cairo.Context (sf);
}
}
public static void DisposeResources ()
{
((IDisposable)SharedContext).Dispose ();
}
public override object Create ()
{
return new PangoBackend {
Layout = Pango.CairoHelper.CreateLayout (SharedContext)
};
}
public override void SetText (object backend, string text)
{
var tl = (PangoBackend) backend;
text = text ?? String.Empty;
tl.Layout.SetText (text);
tl.Text = text;
}
public override void SetFont (object backend, Xwt.Drawing.Font font)
{
var tl = (PangoBackend)backend;
tl.Layout.FontDescription = (Pango.FontDescription)ApplicationContext.Toolkit.GetSafeBackend (font);
}
public override void SetWidth (object backend, double value)
{
var tl = (PangoBackend) backend;
tl.Layout.Width = (int) (value * Pango.Scale.PangoScale);
}
public override void SetHeight (object backend, double value)
{
this.Heigth = value;
}
public override void SetTrimming (object backend, TextTrimming textTrimming)
{
var tl = (PangoBackend)backend;
if (textTrimming == TextTrimming.WordElipsis)
tl.Layout.Ellipsize = Pango.EllipsizeMode.End;
if (textTrimming == TextTrimming.Word)
tl.Layout.Ellipsize = Pango.EllipsizeMode.None;
}
public override Size GetSize (object backend)
{
var tl = (PangoBackend)backend;
int w, h;
tl.Layout.GetPixelSize (out w, out h);
return new Size ((double)w, (double)h);
}
public override void AddAttribute (object backend, TextAttribute attribute)
{
var tl = (PangoBackend) backend;
tl.Attributes.AddAttribute (tl.TextIndexer, attribute);
}
public override void ClearAttributes (object backend)
{
var tl = (PangoBackend) backend;
tl.ClearAttributes ();
}
public override int GetIndexFromCoordinates (object backend, double x, double y)
{
var tl = (PangoBackend) backend;
int index, trailing;
tl.Layout.XyToIndex ((int)x, (int)y, out index, out trailing);
return tl.TextIndexer.ByteIndexToIndex (index);
}
public override Point GetCoordinateFromIndex (object backend, int index)
{
var tl = (PangoBackend) backend;
var pos = tl.Layout.IndexToPos (tl.TextIndexer.IndexToByteIndex (index));
return new Point (pos.X / Pango.Scale.PangoScale, pos.Y / Pango.Scale.PangoScale);
}
public override double GetBaseline (object backend)
{
var tl = (PangoBackend) backend;
// Just get the first line
using (var iter = tl.Layout.Iter)
return Pango.Units.ToPixels (iter.Baseline);
}
public override double GetMeanline (object backend)
{
var tl = (PangoBackend)backend;
var baseline = 0;
using (var iter = tl.Layout.Iter)
baseline = iter.Baseline;
var font = tl.Layout.Context.LoadFont (tl.Layout.FontDescription);
return Pango.Units.ToPixels (baseline - font.GetMetrics (Pango.Language.Default).StrikethroughPosition);
}
public override void Dispose (object backend)
{
var tl = (IDisposable) backend;
tl.Dispose ();
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// AreaCodeInfo
/// </summary>
[DataContract]
public partial class AreaCodeInfo : IEquatable<AreaCodeInfo>
{
/// <summary>
/// Initializes a new instance of the <see cref="AreaCodeInfo" /> class.
/// </summary>
/// <param name="CompanyName">CompanyName.</param>
/// <param name="Ocn">Ocn.</param>
/// <param name="OcnCategory">OcnCategory.</param>
/// <param name="Npa">Npa.</param>
/// <param name="Nxx">Nxx.</param>
/// <param name="StartRange">StartRange.</param>
/// <param name="EndRange">EndRange.</param>
/// <param name="Lata">Lata.</param>
/// <param name="AreaName4">AreaName4.</param>
public AreaCodeInfo(string CompanyName = null, string Ocn = null, string OcnCategory = null, string Npa = null, string Nxx = null, string StartRange = null, string EndRange = null, string Lata = null, string AreaName4 = null)
{
this.CompanyName = CompanyName;
this.Ocn = Ocn;
this.OcnCategory = OcnCategory;
this.Npa = Npa;
this.Nxx = Nxx;
this.StartRange = StartRange;
this.EndRange = EndRange;
this.Lata = Lata;
this.AreaName4 = AreaName4;
}
/// <summary>
/// Gets or Sets CompanyName
/// </summary>
[DataMember(Name="companyName", EmitDefaultValue=false)]
public string CompanyName { get; set; }
/// <summary>
/// Gets or Sets Ocn
/// </summary>
[DataMember(Name="ocn", EmitDefaultValue=false)]
public string Ocn { get; set; }
/// <summary>
/// Gets or Sets OcnCategory
/// </summary>
[DataMember(Name="ocnCategory", EmitDefaultValue=false)]
public string OcnCategory { get; set; }
/// <summary>
/// Gets or Sets Npa
/// </summary>
[DataMember(Name="npa", EmitDefaultValue=false)]
public string Npa { get; set; }
/// <summary>
/// Gets or Sets Nxx
/// </summary>
[DataMember(Name="nxx", EmitDefaultValue=false)]
public string Nxx { get; set; }
/// <summary>
/// Gets or Sets StartRange
/// </summary>
[DataMember(Name="startRange", EmitDefaultValue=false)]
public string StartRange { get; set; }
/// <summary>
/// Gets or Sets EndRange
/// </summary>
[DataMember(Name="endRange", EmitDefaultValue=false)]
public string EndRange { get; set; }
/// <summary>
/// Gets or Sets Lata
/// </summary>
[DataMember(Name="lata", EmitDefaultValue=false)]
public string Lata { get; set; }
/// <summary>
/// Gets or Sets AreaName4
/// </summary>
[DataMember(Name="areaName4", EmitDefaultValue=false)]
public string AreaName4 { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AreaCodeInfo {\n");
sb.Append(" CompanyName: ").Append(CompanyName).Append("\n");
sb.Append(" Ocn: ").Append(Ocn).Append("\n");
sb.Append(" OcnCategory: ").Append(OcnCategory).Append("\n");
sb.Append(" Npa: ").Append(Npa).Append("\n");
sb.Append(" Nxx: ").Append(Nxx).Append("\n");
sb.Append(" StartRange: ").Append(StartRange).Append("\n");
sb.Append(" EndRange: ").Append(EndRange).Append("\n");
sb.Append(" Lata: ").Append(Lata).Append("\n");
sb.Append(" AreaName4: ").Append(AreaName4).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AreaCodeInfo);
}
/// <summary>
/// Returns true if AreaCodeInfo instances are equal
/// </summary>
/// <param name="other">Instance of AreaCodeInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AreaCodeInfo other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CompanyName == other.CompanyName ||
this.CompanyName != null &&
this.CompanyName.Equals(other.CompanyName)
) &&
(
this.Ocn == other.Ocn ||
this.Ocn != null &&
this.Ocn.Equals(other.Ocn)
) &&
(
this.OcnCategory == other.OcnCategory ||
this.OcnCategory != null &&
this.OcnCategory.Equals(other.OcnCategory)
) &&
(
this.Npa == other.Npa ||
this.Npa != null &&
this.Npa.Equals(other.Npa)
) &&
(
this.Nxx == other.Nxx ||
this.Nxx != null &&
this.Nxx.Equals(other.Nxx)
) &&
(
this.StartRange == other.StartRange ||
this.StartRange != null &&
this.StartRange.Equals(other.StartRange)
) &&
(
this.EndRange == other.EndRange ||
this.EndRange != null &&
this.EndRange.Equals(other.EndRange)
) &&
(
this.Lata == other.Lata ||
this.Lata != null &&
this.Lata.Equals(other.Lata)
) &&
(
this.AreaName4 == other.AreaName4 ||
this.AreaName4 != null &&
this.AreaName4.Equals(other.AreaName4)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CompanyName != null)
hash = hash * 59 + this.CompanyName.GetHashCode();
if (this.Ocn != null)
hash = hash * 59 + this.Ocn.GetHashCode();
if (this.OcnCategory != null)
hash = hash * 59 + this.OcnCategory.GetHashCode();
if (this.Npa != null)
hash = hash * 59 + this.Npa.GetHashCode();
if (this.Nxx != null)
hash = hash * 59 + this.Nxx.GetHashCode();
if (this.StartRange != null)
hash = hash * 59 + this.StartRange.GetHashCode();
if (this.EndRange != null)
hash = hash * 59 + this.EndRange.GetHashCode();
if (this.Lata != null)
hash = hash * 59 + this.Lata.GetHashCode();
if (this.AreaName4 != null)
hash = hash * 59 + this.AreaName4.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Utility;
using System;
namespace NodaTime.Calendars
{
/// <summary>
/// Implementation of the algorithms described in
/// https://www.cs.tau.ac.il/~nachum/calendar-book/papers/calendar.ps, using scriptural
/// month numbering.
/// </summary>
internal static class HebrewScripturalCalculator
{
internal const int MaxYear = 9999;
internal const int MinYear = 1;
// Use the bottom two bits of the day value to indicate Heshvan/Kislev.
// Using the top bits causes issues for negative day values (only relevant for
// invalid years, but still problematic in general).
private const int IsHeshvanLongCacheBit = 1 << 0;
private const int IsKislevShortCacheBit = 1 << 1;
// Number of bits to shift the elapsed days in order to get the cache value.
private const int ElapsedDaysCacheShift = 2;
// Cache of when each year starts (in terms of absolute days). This is the heart of
// the algorithm, so just caching this is highly effective.
// Each entry additionally encodes the length of Heshvan and Kislev. We could encode
// more information too, but those are the tricky bits.
private static readonly YearStartCacheEntry[] YearCache = YearStartCacheEntry.CreateCache();
internal static bool IsLeapYear(int year) => ((year * 7) + 1) % 19 < 7;
internal static YearMonthDay GetYearMonthDay(int year, int dayOfYear)
{
unchecked
{
// Work out everything about the year in one go.
int cache = GetOrPopulateCache(year);
int heshvanLength = (cache & IsHeshvanLongCacheBit) != 0 ? 30 : 29;
int kislevLength = (cache & IsKislevShortCacheBit) != 0 ? 29 : 30;
bool isLeap = IsLeapYear(year);
int firstAdarLength = isLeap ? 30 : 29;
if (dayOfYear < 31)
{
// Tishri
return new YearMonthDay(year, 7, dayOfYear);
}
if (dayOfYear < 31 + heshvanLength)
{
// Heshvan
return new YearMonthDay(year, 8, dayOfYear - 30);
}
// Now "day of year without Heshvan"...
dayOfYear -= heshvanLength;
if (dayOfYear < 31 + kislevLength)
{
// Kislev
return new YearMonthDay(year, 9, dayOfYear - 30);
}
// Now "day of year without Heshvan or Kislev"...
dayOfYear -= kislevLength;
if (dayOfYear < 31 + 29)
{
// Tevet
return new YearMonthDay(year, 10, dayOfYear - 30);
}
if (dayOfYear < 31 + 29 + 30)
{
// Shevat
return new YearMonthDay(year, 11, dayOfYear - (30 + 29));
}
if (dayOfYear < 31 + 29 + 30 + firstAdarLength)
{
// Adar / Adar I
return new YearMonthDay(year, 12, dayOfYear - (30 + 29 + 30));
}
// Now "day of year without first month of Adar"
dayOfYear -= firstAdarLength;
if (isLeap)
{
if (dayOfYear < 31 + 29 + 30 + 29)
{
return new YearMonthDay(year, 13, dayOfYear - (30 + 29 + 30));
}
// Now "day of year without any Adar"
dayOfYear -= 29;
}
// We could definitely do a binary search from here, but it would only
// a few comparisons at most, and simplicity trumps optimization.
if (dayOfYear < 31 + 29 + 30 + 30)
{
// Nisan
return new YearMonthDay(year, 1, dayOfYear - (30 + 29 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29)
{
// Iyar
return new YearMonthDay(year, 2, dayOfYear - (30 + 29 + 30 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30)
{
// Sivan
return new YearMonthDay(year, 3, dayOfYear - (30 + 29 + 30 + 30 + 29));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30 + 29)
{
// Tamuz
return new YearMonthDay(year, 4, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30));
}
if (dayOfYear < 31 + 29 + 30 + 30 + 29 + 30 + 29 + 30)
{
// Av
return new YearMonthDay(year, 5, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30 + 29));
}
// Elul
return new YearMonthDay(year, 6, dayOfYear - (30 + 29 + 30 + 30 + 29 + 30 + 29 + 30));
}
}
internal static int GetDaysFromStartOfYearToStartOfMonth(int year, int month)
{
// Work out everything about the year in one go. (Admittedly we don't always need it all... but for
// anything other than Tishri and Heshvan, we at least need the length of Heshvan...)
unchecked
{
int cache = GetOrPopulateCache(year);
int heshvanLength = (cache & IsHeshvanLongCacheBit) != 0 ? 30 : 29;
int kislevLength = (cache & IsKislevShortCacheBit) != 0 ? 29 : 30;
bool isLeap = IsLeapYear(year);
int firstAdarLength = isLeap ? 30 : 29;
int secondAdarLength = isLeap ? 29 : 0;
return month switch
{
// Note: this could be made slightly faster (at least in terms of the apparent IL) by
// putting all the additions of compile-time constants in one place. Indeed, we could
// go further by only using isLeap at most once per case. However, this code is clearer
// and there's no evidence that this is a bottleneck.
// Nisan
1 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength,
// Iyar
2 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + 30,
// Sivan
3 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29),
// Tamuz
4 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30),
// Av
5 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30 + 29),
// Elul
6 => 30 + heshvanLength + kislevLength + (29 + 30) + firstAdarLength + secondAdarLength + (30 + 29 + 30 + 29 + 30),
// Tishri
7 => 0,
// Heshvan
8 => 30,
// Kislev
9 => 30 + heshvanLength,
// Tevet
10 => 30 + heshvanLength + kislevLength,
// Shevat
11 => 30 + heshvanLength + kislevLength + 29,
// Adar / Adar I
12 => 30 + heshvanLength + kislevLength + 29 + 30,
// Adar II
13 => 30 + heshvanLength + kislevLength + 29 + 30 + firstAdarLength,
_ => Preconditions.ThrowArgumentOutOfRangeExceptionWithReturn(nameof(month), month, 1, 13)
};
}
}
internal static int DaysInMonth(int year, int month) => month switch
{
// It's slightly annoying that we have to express these 5 cases
// separately, but there's no language support for multiple individual
// cases right now.
// We want: (2, 4, 6, 10, 13) => 29,
2 => 29,
4 => 29,
6 => 29,
10 => 29,
13 => 29,
8 => IsHeshvanLong(year) ? 30 : 29,
9 => IsKislevShort(year) ? 29 : 30,
12 => IsLeapYear(year) ? 30 : 29,
_ => 30 // 1, 3, 5, 7, 11
};
private static bool IsHeshvanLong(int year)
{
int cache = GetOrPopulateCache(year);
return (cache & IsHeshvanLongCacheBit) != 0;
}
private static bool IsKislevShort(int year)
{
int cache = GetOrPopulateCache(year);
return (cache & IsKislevShortCacheBit) != 0;
}
/// <summary>
/// Elapsed days since the Hebrew epoch at the start of the given Hebrew year.
/// This is *inclusive* of the first day of the year, so ElapsedDays(1) returns 1.
/// </summary>
internal static int ElapsedDays(int year)
{
int cache = GetOrPopulateCache(year);
return cache >> ElapsedDaysCacheShift;
}
private static int ElapsedDaysNoCache(int year)
{
int monthsElapsed = (235 * ((year - 1) / 19)) // Months in complete cycles so far
+ (12 * ((year - 1) % 19)) // Regular months in this cycle
+ ((((year - 1) % 19) * 7 + 1) / 19); // Leap months this cycle
// Second option in the paper, which keeps values smaller
int partsElapsed = 204 + (793 * (monthsElapsed % 1080));
int hoursElapsed = 5 + (12 * monthsElapsed) + (793 * (monthsElapsed / 1080)) + (partsElapsed / 1080);
int day = 1 + (29 * monthsElapsed) + (hoursElapsed / 24);
int parts = ((hoursElapsed % 24) * 1080) + (partsElapsed % 1080);
bool postponeRoshHaShanah = (parts >= 19440) ||
(day % 7 == 2 && parts >= 9924 && !IsLeapYear(year)) ||
(day % 7 == 1 && parts >= 16789 && IsLeapYear(year - 1));
int alternativeDay = postponeRoshHaShanah ? 1 + day : day;
int alternativeDayMod7 = alternativeDay % 7;
return (alternativeDayMod7 == 0 || alternativeDayMod7 == 3 || alternativeDayMod7 == 5)
? alternativeDay + 1 : alternativeDay;
}
/// <summary>
/// Returns the cached "elapsed day at start of year / IsHeshvanLong / IsKislevShort" combination,
/// populating the cache if necessary. Bits 2-24 are the "elapsed days start of year"; bit 0 is
/// "is Heshvan long"; bit 1 is "is Kislev short". If the year is out of the range for the cache,
/// the value is populated but not cached.
/// </summary>
/// <param name="year"></param>
private static int GetOrPopulateCache(int year)
{
if (year < MinYear || year > MaxYear)
{
return ComputeCacheEntry(year);
}
int cacheIndex = YearStartCacheEntry.GetCacheIndex(year);
YearStartCacheEntry cacheEntry = YearCache[cacheIndex];
if (!cacheEntry.IsValidForYear(year))
{
int days = ComputeCacheEntry(year);
cacheEntry = new YearStartCacheEntry(year, days);
YearCache[cacheIndex] = cacheEntry;
}
return cacheEntry.StartOfYearDays;
}
/// <summary>
/// Computes the cache entry value for the given year, but without populating the cache.
/// </summary>
private static int ComputeCacheEntry(int year)
{
int days = ElapsedDaysNoCache(year);
// We want the elapsed days for the next year as well. Check the cache if possible.
int nextYear = year + 1;
int nextYearDays;
if (nextYear <= MaxYear)
{
int cacheIndex = YearStartCacheEntry.GetCacheIndex(nextYear);
YearStartCacheEntry cacheEntry = YearCache[cacheIndex];
nextYearDays = cacheEntry.IsValidForYear(nextYear)
? cacheEntry.StartOfYearDays >> ElapsedDaysCacheShift
: ElapsedDaysNoCache(nextYear);
}
else
{
nextYearDays = ElapsedDaysNoCache(year + 1);
}
int daysInYear = nextYearDays - days;
bool isHeshvanLong = daysInYear % 10 == 5;
bool isKislevShort = daysInYear % 10 == 3;
return (days << ElapsedDaysCacheShift)
| (isHeshvanLong ? IsHeshvanLongCacheBit : 0)
| (isKislevShort ? IsKislevShortCacheBit : 0);
}
internal static int DaysInYear(int year) => ElapsedDays(year + 1) - ElapsedDays(year);
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
#if !READ_ONLY
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageWriter : BinaryStreamWriter {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly TextMap text_map;
readonly internal Disposable<Stream> stream;
readonly string runtime_version;
ImageDebugHeader debug_header;
ByteBuffer win32_resources;
ResourceDirectory win32_resources_directory;
const uint pe_header_size = 0x98u;
const uint section_header_size = 0x28u;
const uint file_alignment = 0x200;
const uint section_alignment = 0x2000;
const ulong image_base = 0x00400000;
internal const RVA text_rva = 0x2000;
readonly bool pe64;
readonly bool has_reloc;
internal Section text;
internal Section rsrc;
internal Section reloc;
ushort sections;
ImageWriter (ModuleDefinition module, string runtime_version, MetadataBuilder metadata, Disposable<Stream> stream, bool metadataOnly = false)
: base (stream.value)
{
this.module = module;
this.runtime_version = runtime_version;
this.text_map = metadata.text_map;
this.stream = stream;
this.metadata = metadata;
if (metadataOnly)
return;
this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64 || module.Architecture == TargetArchitecture.ARM64;
this.has_reloc = module.Architecture == TargetArchitecture.I386;
this.GetDebugHeader ();
this.GetWin32Resources ();
this.BuildTextMap ();
this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
}
void GetDebugHeader ()
{
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
debug_header = symbol_writer.GetDebugHeader ();
if (module.HasDebugHeader) {
var header = module.GetDebugHeader ();
var deterministic = header.GetDeterministicEntry ();
if (deterministic == null)
return;
debug_header = debug_header.AddDeterministicEntry ();
}
}
void GetWin32Resources ()
{
if (module.Win32Resources != null)
{
win32_resources = new ByteBuffer(module.Win32Resources);
return;
}
if (module.Win32ResourceDirectory != null && module.Win32ResourceDirectory.Entries.Count > 0)
{
win32_resources_directory = module.Win32ResourceDirectory;
return;
}
if (!module.HasImage)
return;
DataDirectory win32_resources_data_directory = module.Image.Win32Resources;
var size = win32_resources_data_directory.Size;
if (size > 0) {
win32_resources = module.Image.GetReaderAt (win32_resources_data_directory.VirtualAddress, size, (s, reader) => new ByteBuffer (reader.ReadBytes ((int) s)));
}
}
public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
{
var writer = new ImageWriter (module, module.runtime_version, metadata, stream);
writer.BuildSections ();
return writer;
}
public static ImageWriter CreateDebugWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
{
var writer = new ImageWriter (module, "PDB v1.0", metadata, stream, metadataOnly: true);
var length = metadata.text_map.GetLength ();
writer.text = new Section { SizeOfRawData = length, VirtualSize = length };
return writer;
}
void BuildSections ()
{
if (win32_resources != null || win32_resources_directory != null)
sections++;
text = CreateSection (".text", text_map.GetLength (), null);
var previous = text;
if (win32_resources != null) {
rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
PatchWin32Resources (win32_resources);
previous = rsrc;
} else if (win32_resources_directory != null && win32_resources_directory.Entries.Count > 0) {
rsrc = CreateSection(".rsrc", previous);
WriteWin32ResourcesDirectory(win32_resources_directory);
SetSectionSize(rsrc, (uint) win32_resources.length);
previous = rsrc;
}
if (has_reloc)
reloc = CreateSection (".reloc", 12u, previous);
}
Section CreateSection (string name, uint size, Section previous)
{
var ret = CreateSection(name, previous);
SetSectionSize(ret, size);
return ret;
}
void SetSectionSize(Section ret, uint size)
{
ret.VirtualSize = size;
ret.SizeOfRawData = Align(size, file_alignment);
}
Section CreateSection(string name, Section previous)
{
return new Section
{
Name = name,
VirtualAddress = previous != null
? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
: text_rva,
PointerToRawData = previous != null
? previous.PointerToRawData + previous.SizeOfRawData
: Align (GetHeaderSize (), file_alignment)
};
}
static uint Align (uint value, uint align)
{
align--;
return (value + align) & ~align;
}
void WriteDOSHeader ()
{
Write (new byte [] {
// dos header start
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// lfanew
0x80, 0x00, 0x00, 0x00,
// dos header end
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
});
}
ushort SizeOfOptionalHeader ()
{
return (ushort) (!pe64 ? 0xe0 : 0xf0);
}
void WritePEFileHeader ()
{
WriteUInt32 (0x00004550); // Magic
WriteUInt16 ((ushort) module.Architecture); // Machine
WriteUInt16 (sections); // NumberOfSections
WriteUInt32 (metadata.timestamp);
WriteUInt32 (0); // PointerToSymbolTable
WriteUInt32 (0); // NumberOfSymbols
WriteUInt16 (SizeOfOptionalHeader ()); // SizeOfOptionalHeader
// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
characteristics |= 0x2000;
WriteUInt16 (characteristics); // Characteristics
}
Section LastSection ()
{
if (reloc != null)
return reloc;
if (rsrc != null)
return rsrc;
return text;
}
void WriteOptionalHeaders ()
{
WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic
WriteByte (8); // LMajor
WriteByte (0); // LMinor
WriteUInt32 (text.SizeOfRawData); // CodeSize
WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0)
+ (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize
WriteUInt32 (0); // UninitializedDataSize
var startub_stub = text_map.GetRange (TextSegment.StartupStub);
WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA
WriteUInt32 (text_rva); // BaseOfCode
if (!pe64) {
WriteUInt32 (0); // BaseOfData
WriteUInt32 ((uint) image_base); // ImageBase
} else {
WriteUInt64 (image_base); // ImageBase
}
WriteUInt32 (section_alignment); // SectionAlignment
WriteUInt32 (file_alignment); // FileAlignment
WriteUInt16 (4); // OSMajor
WriteUInt16 (0); // OSMinor
WriteUInt16 (0); // UserMajor
WriteUInt16 (0); // UserMinor
WriteUInt16 (4); // SubSysMajor
WriteUInt16 (0); // SubSysMinor
WriteUInt32 (0); // Reserved
var last_section = LastSection();
WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize
WriteUInt32 (text.PointerToRawData); // HeaderSize
WriteUInt32 (0); // Checksum
WriteUInt16 (GetSubSystem ()); // SubSystem
WriteUInt16 ((ushort) module.Characteristics); // DLLFlags
const ulong stack_reserve = 0x100000;
const ulong stack_commit = 0x1000;
const ulong heap_reserve = 0x100000;
const ulong heap_commit = 0x1000;
if (!pe64) {
WriteUInt32 ((uint) stack_reserve);
WriteUInt32 ((uint) stack_commit);
WriteUInt32 ((uint) heap_reserve);
WriteUInt32 ((uint) heap_commit);
} else {
WriteUInt64 (stack_reserve);
WriteUInt64 (stack_commit);
WriteUInt64 (heap_reserve);
WriteUInt64 (heap_commit);
}
WriteUInt32 (0); // LoaderFlags
WriteUInt32 (16); // NumberOfDataDir
WriteZeroDataDirectory (); // ExportTable
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable
if (rsrc != null) { // ResourceTable
WriteUInt32 (rsrc.VirtualAddress);
WriteUInt32 (rsrc.VirtualSize);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // ExceptionTable
WriteZeroDataDirectory (); // CertificateTable
WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable
WriteUInt32 (reloc != null ? reloc.VirtualSize : 0);
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
WriteUInt32 ((uint) (debug_header.Entries.Length * ImageDebugDirectory.Size));
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // Copyright
WriteZeroDataDirectory (); // GlobalPtr
WriteZeroDataDirectory (); // TLSTable
WriteZeroDataDirectory (); // LoadConfigTable
WriteZeroDataDirectory (); // BoundImport
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT
WriteZeroDataDirectory (); // DelayImportDesc
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader
WriteZeroDataDirectory (); // Reserved
}
void WriteZeroDataDirectory ()
{
WriteUInt32 (0);
WriteUInt32 (0);
}
ushort GetSubSystem ()
{
switch (module.Kind) {
case ModuleKind.Console:
case ModuleKind.Dll:
case ModuleKind.NetModule:
return 0x3;
case ModuleKind.Windows:
return 0x2;
default:
throw new ArgumentOutOfRangeException ();
}
}
void WriteSectionHeaders ()
{
WriteSection (text, 0x60000020);
if (rsrc != null)
WriteSection (rsrc, 0x40000040);
if (reloc != null)
WriteSection (reloc, 0x42000040);
}
void WriteSection (Section section, uint characteristics)
{
var name = new byte [8];
var sect_name = section.Name;
for (int i = 0; i < sect_name.Length; i++)
name [i] = (byte) sect_name [i];
WriteBytes (name);
WriteUInt32 (section.VirtualSize);
WriteUInt32 (section.VirtualAddress);
WriteUInt32 (section.SizeOfRawData);
WriteUInt32 (section.PointerToRawData);
WriteUInt32 (0); // PointerToRelocations
WriteUInt32 (0); // PointerToLineNumbers
WriteUInt16 (0); // NumberOfRelocations
WriteUInt16 (0); // NumberOfLineNumbers
WriteUInt32 (characteristics);
}
void MoveTo (uint pointer)
{
BaseStream.Seek (pointer, SeekOrigin.Begin);
}
void MoveToRVA (Section section, RVA rva)
{
BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
}
void MoveToRVA (TextSegment segment)
{
MoveToRVA (text, text_map.GetRVA (segment));
}
void WriteRVA (RVA rva)
{
if (!pe64)
WriteUInt32 (rva);
else
WriteUInt64 (rva);
}
void PrepareSection (Section section)
{
MoveTo (section.PointerToRawData);
const int buffer_size = 4096;
if (section.SizeOfRawData <= buffer_size) {
Write (new byte [section.SizeOfRawData]);
MoveTo (section.PointerToRawData);
return;
}
var written = 0;
var buffer = new byte [buffer_size];
while (written != section.SizeOfRawData) {
var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size);
Write (buffer, 0, write_size);
written += write_size;
}
MoveTo (section.PointerToRawData);
}
void WriteText ()
{
PrepareSection (text);
// ImportAddressTable
if (has_reloc) {
WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
WriteRVA (0);
}
// CLIHeader
WriteUInt32 (0x48);
WriteUInt16 (2);
WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
WriteUInt32 (GetMetadataLength ());
WriteUInt32 ((uint) module.Attributes);
WriteUInt32 (metadata.entry_point.ToUInt32 ());
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
WriteZeroDataDirectory (); // CodeManagerTable
WriteZeroDataDirectory (); // VTableFixups
WriteZeroDataDirectory (); // ExportAddressTableJumps
WriteZeroDataDirectory (); // ManagedNativeHeader
// Code
MoveToRVA (TextSegment.Code);
WriteBuffer (metadata.code);
// Resources
MoveToRVA (TextSegment.Resources);
WriteBuffer (metadata.resources);
// Data
if (metadata.data.length > 0) {
MoveToRVA (TextSegment.Data);
WriteBuffer (metadata.data);
}
// StrongNameSignature
// stays blank
// MetadataHeader
MoveToRVA (TextSegment.MetadataHeader);
WriteMetadataHeader ();
WriteMetadata ();
// DebugDirectory
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
MoveToRVA (TextSegment.DebugDirectory);
WriteDebugDirectory ();
}
if (!has_reloc)
return;
// ImportDirectory
MoveToRVA (TextSegment.ImportDirectory);
WriteImportDirectory ();
// StartupStub
MoveToRVA (TextSegment.StartupStub);
WriteStartupStub ();
}
uint GetMetadataLength ()
{
return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
}
public void WriteMetadataHeader ()
{
WriteUInt32 (0x424a5342); // Signature
WriteUInt16 (1); // MajorVersion
WriteUInt16 (1); // MinorVersion
WriteUInt32 (0); // Reserved
var version = GetZeroTerminatedString (runtime_version);
WriteUInt32 ((uint) version.Length);
WriteBytes (version);
WriteUInt16 (0); // Flags
WriteUInt16 (GetStreamCount ());
uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
WriteStreamHeader (ref offset, TextSegment.PdbHeap, "#Pdb");
}
ushort GetStreamCount ()
{
return (ushort) (
1 // #~
+ 1 // #Strings
+ (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US
+ (metadata.guid_heap.IsEmpty ? 0 : 1) // GUID
+ (metadata.blob_heap.IsEmpty ? 0 : 1)
+ (metadata.pdb_heap == null ? 0 : 1)); // #Blob
}
void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
{
var length = (uint) text_map.GetLength (heap);
if (length == 0)
return;
WriteUInt32 (offset);
WriteUInt32 (length);
WriteBytes (GetZeroTerminatedString (name));
offset += length;
}
static int GetZeroTerminatedStringLength (string @string)
{
return (@string.Length + 1 + 3) & ~3;
}
static byte [] GetZeroTerminatedString (string @string)
{
return GetString (@string, GetZeroTerminatedStringLength (@string));
}
static byte [] GetSimpleString (string @string)
{
return GetString (@string, @string.Length);
}
static byte [] GetString (string @string, int length)
{
var bytes = new byte [length];
for (int i = 0; i < @string.Length; i++)
bytes [i] = (byte) @string [i];
return bytes;
}
public void WriteMetadata ()
{
WriteHeap (TextSegment.TableHeap, metadata.table_heap);
WriteHeap (TextSegment.StringHeap, metadata.string_heap);
WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
WriteHeap (TextSegment.GuidHeap, metadata.guid_heap);
WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
WriteHeap (TextSegment.PdbHeap, metadata.pdb_heap);
}
void WriteHeap (TextSegment heap, HeapBuffer buffer)
{
if (buffer == null || buffer.IsEmpty)
return;
MoveToRVA (heap);
WriteBuffer (buffer);
}
void WriteDebugDirectory ()
{
var data_start = (int) BaseStream.Position + (debug_header.Entries.Length * ImageDebugDirectory.Size);
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
var directory = entry.Directory;
WriteInt32 (directory.Characteristics);
WriteInt32 (directory.TimeDateStamp);
WriteInt16 (directory.MajorVersion);
WriteInt16 (directory.MinorVersion);
WriteInt32 ((int) directory.Type);
WriteInt32 (directory.SizeOfData);
WriteInt32 (directory.AddressOfRawData);
WriteInt32 (data_start);
data_start += entry.Data.Length;
}
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
WriteBytes (entry.Data);
}
}
void WriteImportDirectory ()
{
WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable
WriteUInt32 (0); // DateTimeStamp
WriteUInt32 (0); // ForwarderChain
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
Advance (20);
// ImportLookupTable
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
// ImportHintNameTable
MoveToRVA (TextSegment.ImportHintNameTable);
WriteUInt16 (0); // Hint
WriteBytes (GetRuntimeMain ());
WriteByte (0);
WriteBytes (GetSimpleString ("mscoree.dll"));
WriteUInt16 (0);
}
byte [] GetRuntimeMain ()
{
return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
? GetSimpleString ("_CorDllMain")
: GetSimpleString ("_CorExeMain");
}
void WriteStartupStub ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt16 (0x25ff);
WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
return;
default:
throw new NotSupportedException ();
}
}
void WriteRsrc ()
{
PrepareSection (rsrc);
WriteBuffer (win32_resources);
}
void WriteReloc ()
{
PrepareSection (reloc);
var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
var page_rva = reloc_rva & ~0xfffu;
WriteUInt32 (page_rva); // PageRVA
WriteUInt32 (0x000c); // Block Size
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt32 (0x3000 + reloc_rva - page_rva);
break;
default:
throw new NotSupportedException();
}
}
public void WriteImage ()
{
WriteDOSHeader ();
WritePEFileHeader ();
WriteOptionalHeaders ();
WriteSectionHeaders ();
WriteText ();
if (rsrc != null)
WriteRsrc ();
if (reloc != null)
WriteReloc ();
Flush ();
}
void BuildTextMap ()
{
var map = text_map;
map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
map.AddMap (TextSegment.Data, metadata.data.length, 4);
if (metadata.data.length > 0)
metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
BuildMetadataTextMap ();
int debug_dir_len = 0;
if (debug_header != null && debug_header.HasEntries) {
var directories_len = debug_header.Entries.Length * ImageDebugDirectory.Size;
var data_address = (int) map.GetNextRVA (TextSegment.BlobHeap) + directories_len;
var data_len = 0;
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
var directory = entry.Directory;
directory.AddressOfRawData = entry.Data.Length == 0 ? 0 : data_address;
entry.Directory = directory;
data_len += entry.Data.Length;
data_address += data_len;
}
debug_dir_len = directories_len + data_len;
}
map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
if (!has_reloc) {
var start = map.GetNextRVA (TextSegment.DebugDirectory);
map.AddMap (TextSegment.ImportDirectory, new Range (start, 0));
map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0));
map.AddMap (TextSegment.StartupStub, new Range (start, 0));
return;
}
RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
RVA import_hnt_rva = import_dir_rva + 48u;
import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
RVA startup_stub_rva = import_dir_rva + import_dir_len;
startup_stub_rva = module.Architecture == TargetArchitecture.IA64
? (startup_stub_rva + 15u) & ~15u
: 2 + ((startup_stub_rva + 3u) & ~3u);
map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
}
public void BuildMetadataTextMap ()
{
var map = text_map;
map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength (module.RuntimeVersion));
map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
map.AddMap (TextSegment.GuidHeap, metadata.guid_heap.length, 4);
map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
map.AddMap (TextSegment.PdbHeap, metadata.pdb_heap == null ? 0 : metadata.pdb_heap.length, 4);
}
uint GetStartupStubLength ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 6;
default:
throw new NotSupportedException ();
}
}
int GetMetadataHeaderLength (string runtimeVersion)
{
return
// MetadataHeader
20 + GetZeroTerminatedStringLength (runtimeVersion)
// #~ header
+ 12
// #Strings header
+ 20
// #US header
+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
// #GUID header
+ 16
// #Blob header
+ (metadata.blob_heap.IsEmpty ? 0 : 16)
//
+ (metadata.pdb_heap == null ? 0 : 16);
}
int GetStrongNameLength ()
{
if (module.Assembly == null)
return 0;
var public_key = module.Assembly.Name.PublicKey;
if (public_key.IsNullOrEmpty ())
return 0;
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = public_key.Length;
if (size > 32)
return size - 32;
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
return 128; // default strongname signature size
}
public DataDirectory GetStrongNameSignatureDirectory ()
{
return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
}
public uint GetHeaderSize ()
{
return pe_header_size + SizeOfOptionalHeader () + (sections * section_header_size);
}
void PatchWin32Resources (ByteBuffer resources)
{
PatchResourceDirectoryTable (resources);
}
void PatchResourceDirectoryTable (ByteBuffer resources)
{
resources.Advance (12);
var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
for (int i = 0; i < entries; i++)
PatchResourceDirectoryEntry (resources);
}
void PatchResourceDirectoryEntry (ByteBuffer resources)
{
resources.Advance (4);
var child = resources.ReadUInt32 ();
var position = resources.position;
resources.position = (int) child & 0x7fffffff;
if ((child & 0x80000000) != 0)
PatchResourceDirectoryTable (resources);
else
PatchResourceDataEntry (resources);
resources.position = position;
}
void PatchResourceDataEntry (ByteBuffer resources)
{
var rva = resources.ReadUInt32 ();
resources.position -= 4;
resources.WriteUInt32 (rva - module.Image.Win32Resources.VirtualAddress + rsrc.VirtualAddress);
}
private static int GetDirectoryLength(ResourceDirectory dir)
{
int length = 16 + dir.Entries.Count * 8;
foreach (ResourceEntry entry in dir.Entries)
length += GetDirectoryLength(entry);
return length;
}
private static int GetDirectoryLength(ResourceEntry entry)
{
if (entry.Data != null)
return 16;
return GetDirectoryLength(entry.Directory);
}
private void WriteWin32ResourcesDirectory(ResourceDirectory directory)
{
win32_resources = new ByteBuffer();
if (directory.Entries.Count != 0)
{
int stringTableOffset = GetDirectoryLength(directory);
Dictionary<string, int> strings = new Dictionary<string, int>();
ByteBuffer stringTable = new ByteBuffer(16);
int offset = 16 + directory.Entries.Count * 8;
for (int pass = 0; pass < 3; pass++)
Write(directory, pass, 0, ref offset, strings, ref stringTableOffset, stringTable);
// the pecoff spec says that the string table is between the directory entries and the data entries,
// but the windows linker puts them after the data entries, so we do too.
stringTable.Align(4);
offset += stringTable.length;
WriteResourceDataEntries(directory, ref offset);
win32_resources.WriteBytes(stringTable);
WriteData(directory);
}
}
private void WriteResourceDataEntries(ResourceDirectory directory, ref int offset)
{
foreach (ResourceEntry entry in directory.Entries)
{
if (entry.Data != null)
{
win32_resources.WriteUInt32((uint) (rsrc.VirtualAddress + offset));
win32_resources.WriteInt32(entry.Data.Length);
win32_resources.WriteUInt32(entry.CodePage);
win32_resources.WriteUInt32(entry.Reserved);
offset += (entry.Data.Length + 3) & ~3;
}
else
{
WriteResourceDataEntries(entry.Directory, ref offset);
}
}
}
private void WriteData(ResourceDirectory directory)
{
foreach (ResourceEntry entry in directory.Entries)
{
if (entry.Data != null)
{
win32_resources.WriteBytes(entry.Data);
win32_resources.Align(4);
}
else
{
WriteData(entry.Directory);
}
}
}
private void Write(ResourceDirectory directory, int writeDepth, int currentDepth, ref int offset, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
if (currentDepth == writeDepth)
{
ushort namedEntries = directory.SortEntries();
// directory header
win32_resources.WriteUInt32(directory.Characteristics);
win32_resources.WriteUInt32(directory.TimeDateStamp);
win32_resources.WriteUInt16(directory.MajorVersion);
win32_resources.WriteUInt16(directory.MinVersion);
win32_resources.WriteUInt16(namedEntries);
win32_resources.WriteUInt16((ushort)(directory.Entries.Count - namedEntries));
foreach (ResourceEntry entry in directory.Entries)
{
WriteEntry(entry, ref offset, strings, ref stringTableOffset, stringTable);
}
}
else
{
foreach (ResourceEntry entry in directory.Entries)
{
Write(entry.Directory, writeDepth, currentDepth + 1, ref offset, strings, ref stringTableOffset, stringTable);
}
}
}
private void WriteEntry(ResourceEntry entry, ref int offset, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
WriteNameOrOrdinal(entry, strings, ref stringTableOffset, stringTable);
if (entry.Data == null)
{
win32_resources.WriteUInt32(0x80000000U | (uint)offset);
offset += entry.Directory.Entries.Count * 8;
}
else
{
win32_resources.WriteUInt32((uint)offset);
}
offset += 16;
}
private void WriteNameOrOrdinal(ResourceEntry entry, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
if (entry.Name == null)
{
win32_resources.WriteUInt32(entry.Id);
}
else
{
int stringOffset;
if (!strings.TryGetValue(entry.Name, out stringOffset))
{
stringOffset = stringTableOffset;
strings.Add(entry.Name, stringOffset);
stringTableOffset += entry.Name.Length * 2 + 2;
stringTable.WriteUInt16((ushort)entry.Name.Length);
foreach (char c in entry.Name)
stringTable.WriteInt16((short)c);
}
win32_resources.WriteUInt32(0x80000000U | (uint)stringOffset);
}
}
}
}
#endif
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Sends log messages by email using SMTP protocol.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" />
/// <p>
/// Mail target works best when used with BufferingWrapper target
/// which lets you send multiple log messages in single mail
/// </p>
/// <p>
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" />
/// <p>
/// To set up the buffered mail target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" />
/// </example>
[Target("Mail")]
public class MailTarget : TargetWithLayoutHeaderAndFooter
{
private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent.";
/// <summary>
/// Initializes a new instance of the <see cref="MailTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")]
public MailTarget()
{
this.Body = "${message}${newline}";
this.Subject = "Message from NLog on ${machinename}";
this.Encoding = Encoding.UTF8;
this.SmtpPort = 25;
this.SmtpAuthentication = SmtpAuthenticationMode.None;
this.Timeout = 10000;
}
/// <summary>
/// Gets or sets sender's email address (e.g. joe@domain.com).
/// </summary>
/// <docgen category='Message Options' order='10' />
[RequiredParameter]
public Layout From { get; set; }
/// <summary>
/// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='11' />
[RequiredParameter]
public Layout To { get; set; }
/// <summary>
/// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='12' />
public Layout CC { get; set; }
/// <summary>
/// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='13' />
public Layout Bcc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to add new lines between log entries.
/// </summary>
/// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value>
/// <docgen category='Layout Options' order='99' />
public bool AddNewLines { get; set; }
/// <summary>
/// Gets or sets the mail subject.
/// </summary>
/// <docgen category='Message Options' order='5' />
[DefaultValue("Message from NLog on ${machinename}")]
[RequiredParameter]
public Layout Subject { get; set; }
/// <summary>
/// Gets or sets mail message body (repeated for each log message send in one mail).
/// </summary>
/// <remarks>Alias for the <c>Layout</c> property.</remarks>
/// <docgen category='Message Options' order='6' />
[DefaultValue("${message}${newline}")]
public Layout Body
{
get { return this.Layout; }
set { this.Layout = value; }
}
/// <summary>
/// Gets or sets encoding to be used for sending e-mail.
/// </summary>
/// <docgen category='Layout Options' order='20' />
[DefaultValue("UTF8")]
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to send message as HTML instead of plain text.
/// </summary>
/// <docgen category='Layout Options' order='11' />
[DefaultValue(false)]
public bool Html { get; set; }
/// <summary>
/// Gets or sets SMTP Server to be used for sending.
/// </summary>
/// <docgen category='SMTP Options' order='10' />
public Layout SmtpServer { get; set; }
/// <summary>
/// Gets or sets SMTP Authentication mode.
/// </summary>
/// <docgen category='SMTP Options' order='11' />
[DefaultValue("None")]
public SmtpAuthenticationMode SmtpAuthentication { get; set; }
/// <summary>
/// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='12' />
public Layout SmtpUserName { get; set; }
/// <summary>
/// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='13' />
public Layout SmtpPassword { get; set; }
/// <summary>
/// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server.
/// </summary>
/// <docgen category='SMTP Options' order='14' />
[DefaultValue(false)]
public bool EnableSsl { get; set; }
/// <summary>
/// Gets or sets the port number that SMTP Server is listening on.
/// </summary>
/// <docgen category='SMTP Options' order='15' />
[DefaultValue(25)]
public int SmtpPort { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used.
/// </summary>
/// <docgen category='SMTP Options' order='16' />
[DefaultValue(false)]
public bool UseSystemNetMailSettings { get; set; }
/// <summary>
/// Gets or sets the priority used for sending mails.
/// </summary>
public Layout Priority { get; set; }
/// <summary>
/// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags.
/// </summary>
/// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks>
[DefaultValue(false)]
public bool ReplaceNewlineWithBrTagInHtml { get; set; }
/// <summary>
/// Gets or sets a value indicating the SMTP client timeout.
/// </summary>
/// <remarks>Warning: zero is not infinit waiting</remarks>
[DefaultValue(10000)]
public int Timeout { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")]
internal virtual ISmtpClient CreateSmtpClient()
{
return new MySmtpClient();
}
/// <summary>
/// Renders the logging event message and adds it to the internal ArrayList of log messages.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.Write(new[] { logEvent });
}
/// <summary>
/// Renders an array logging events.
/// </summary>
/// <param name="logEvents">Array of logging events.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
foreach (var bucket in logEvents.BucketSort(c => this.GetSmtpSettingsKey(c.LogEvent)))
{
var eventInfos = bucket.Value;
this.ProcessSingleMailMessage(eventInfos);
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
CheckRequiredParameters();
base.InitializeTarget();
}
/// <summary>
/// Create mail and send with SMTP
/// </summary>
/// <param name="events">event printed in the body of the event</param>
private void ProcessSingleMailMessage([NotNull] List<AsyncLogEventInfo> events)
{
try
{
if (events.Count == 0)
{
throw new NLogRuntimeException("We need at least one event.");
}
LogEventInfo firstEvent = events[0].LogEvent;
LogEventInfo lastEvent = events[events.Count - 1].LogEvent;
// unbuffered case, create a local buffer, append header, body and footer
var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent);
using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString()))
{
using (ISmtpClient client = this.CreateSmtpClient())
{
if (!UseSystemNetMailSettings)
ConfigureMailClient(lastEvent, client);
InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl);
InternalLogger.Trace(" Subject: '{0}'", msg.Subject);
InternalLogger.Trace(" From: '{0}'", msg.From.ToString());
client.Send(msg);
foreach (var ev in events)
{
ev.Continuation(null);
}
}
}
}
catch (Exception exception)
{
//always log
InternalLogger.Error(exception.ToString());
if (exception.MustBeRethrown())
{
throw;
}
foreach (var ev in events)
{
ev.Continuation(exception);
}
}
}
/// <summary>
/// Create buffer for body
/// </summary>
/// <param name="events">all events</param>
/// <param name="firstEvent">first event for header</param>
/// <param name="lastEvent">last event for footer</param>
/// <returns></returns>
private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent)
{
var bodyBuffer = new StringBuilder();
if (this.Header != null)
{
bodyBuffer.Append(this.Header.Render(firstEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
foreach (AsyncLogEventInfo eventInfo in events)
{
bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
if (this.Footer != null)
{
bodyBuffer.Append(this.Footer.Render(lastEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
return bodyBuffer;
}
/// <summary>
/// Set propertes of <paramref name="client"/>
/// </summary>
/// <param name="lastEvent">last event for username/password</param>
/// <param name="client">client to set properties on</param>
private void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client)
{
CheckRequiredParameters();
var renderedSmtpServer = this.SmtpServer.Render(lastEvent);
if (string.IsNullOrEmpty(renderedSmtpServer))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
client.Host = renderedSmtpServer;
client.Port = this.SmtpPort;
client.EnableSsl = this.EnableSsl;
client.Timeout = this.Timeout;
if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
{
InternalLogger.Trace(" Using NTLM authentication.");
client.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
{
string username = this.SmtpUserName.Render(lastEvent);
string password = this.SmtpPassword.Render(lastEvent);
InternalLogger.Trace(" Using basic authentication: Username='{0}' Password='{1}'", username, new string('*', password.Length));
client.Credentials = new NetworkCredential(username, password);
}
}
private void CheckRequiredParameters()
{
if (!this.UseSystemNetMailSettings && this.SmtpServer == null)
{
throw new NLogConfigurationException(
string.Format("The MailTarget's '{0}' property is not set - but needed because useSystemNetMailSettings=false. The email message will not be sent.", "SmtpServer"));
}
}
/// <summary>
/// Create key for grouping. Needed for multiple events in one mailmessage
/// </summary>
/// <param name="logEvent">event for rendering layouts </param>
///<returns>string to group on</returns>
private string GetSmtpSettingsKey(LogEventInfo logEvent)
{
var sb = new StringBuilder();
AppendLayout(sb, logEvent, this.From);
AppendLayout(sb, logEvent, this.To);
AppendLayout(sb, logEvent, this.CC);
AppendLayout(sb, logEvent, this.Bcc);
AppendLayout(sb, logEvent, this.SmtpServer);
AppendLayout(sb, logEvent, this.SmtpPassword);
AppendLayout(sb, logEvent, this.SmtpUserName);
return sb.ToString();
}
/// <summary>
/// Append rendered layout to the stringbuilder
/// </summary>
/// <param name="sb">append to this</param>
/// <param name="logEvent">event for rendering <paramref name="layout"/></param>
/// <param name="layout">append if not <c>null</c></param>
private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout)
{
sb.Append("|");
if (layout != null)
sb.Append(layout.Render(logEvent));
}
/// <summary>
/// Create the mailmessage with the addresses, properties and body.
/// </summary>
private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body)
{
var msg = new MailMessage();
var renderedFrom = this.From == null ? null : this.From.Render(lastEvent);
if (string.IsNullOrEmpty(renderedFrom))
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
}
msg.From = new MailAddress(renderedFrom);
var addedTo = AddAddresses(msg.To, this.To, lastEvent);
var addedCc = AddAddresses(msg.CC, this.CC, lastEvent);
var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent);
if (!addedTo && !addedCc && !addedBcc)
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc");
}
msg.Subject = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim();
msg.BodyEncoding = this.Encoding;
msg.IsBodyHtml = this.Html;
if (this.Priority != null)
{
var renderedPriority = this.Priority.Render(lastEvent);
try
{
msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true);
}
catch
{
InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.");
msg.Priority = MailPriority.Normal;
}
}
msg.Body = body;
if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null)
msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>");
return msg;
}
/// <summary>
/// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/>
/// </summary>
/// <param name="mailAddressCollection">Addresses appended to this list</param>
/// <param name="layout">layout with addresses, ; separated</param>
/// <param name="logEvent">event for rendering the <paramref name="layout"/></param>
/// <returns>added a address?</returns>
private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent)
{
var added = false;
if (layout != null)
{
foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
mailAddressCollection.Add(mail);
added = true;
}
}
return added;
}
}
}
#endif
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace Northwind
{
/// <summary>
/// Strongly-typed collection for the Order class.
/// </summary>
[Serializable]
public partial class OrderCollection : ActiveList<Order, OrderCollection>
{
public OrderCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>OrderCollection</returns>
public OrderCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Order o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Orders table.
/// </summary>
[Serializable]
public partial class Order : ActiveRecord<Order>, IActiveRecord
{
#region .ctors and Default Settings
public Order()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Order(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Order(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Order(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Orders", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = true;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = true;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
colvarOrderID.DefaultSetting = @"";
colvarOrderID.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = true;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "Customers";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 0;
colvarEmployeeID.AutoIncrement = false;
colvarEmployeeID.IsNullable = true;
colvarEmployeeID.IsPrimaryKey = false;
colvarEmployeeID.IsForeignKey = true;
colvarEmployeeID.IsReadOnly = false;
colvarEmployeeID.DefaultSetting = @"";
colvarEmployeeID.ForeignKeyTableName = "Employees";
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema);
colvarOrderDate.ColumnName = "OrderDate";
colvarOrderDate.DataType = DbType.DateTime;
colvarOrderDate.MaxLength = 0;
colvarOrderDate.AutoIncrement = false;
colvarOrderDate.IsNullable = true;
colvarOrderDate.IsPrimaryKey = false;
colvarOrderDate.IsForeignKey = false;
colvarOrderDate.IsReadOnly = false;
colvarOrderDate.DefaultSetting = @"";
colvarOrderDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderDate);
TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema);
colvarRequiredDate.ColumnName = "RequiredDate";
colvarRequiredDate.DataType = DbType.DateTime;
colvarRequiredDate.MaxLength = 0;
colvarRequiredDate.AutoIncrement = false;
colvarRequiredDate.IsNullable = true;
colvarRequiredDate.IsPrimaryKey = false;
colvarRequiredDate.IsForeignKey = false;
colvarRequiredDate.IsReadOnly = false;
colvarRequiredDate.DefaultSetting = @"";
colvarRequiredDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarRequiredDate);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
colvarShippedDate.DefaultSetting = @"";
colvarShippedDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarShipVia = new TableSchema.TableColumn(schema);
colvarShipVia.ColumnName = "ShipVia";
colvarShipVia.DataType = DbType.Int32;
colvarShipVia.MaxLength = 0;
colvarShipVia.AutoIncrement = false;
colvarShipVia.IsNullable = true;
colvarShipVia.IsPrimaryKey = false;
colvarShipVia.IsForeignKey = true;
colvarShipVia.IsReadOnly = false;
colvarShipVia.DefaultSetting = @"";
colvarShipVia.ForeignKeyTableName = "Shippers";
schema.Columns.Add(colvarShipVia);
TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema);
colvarFreight.ColumnName = "Freight";
colvarFreight.DataType = DbType.Currency;
colvarFreight.MaxLength = 0;
colvarFreight.AutoIncrement = false;
colvarFreight.IsNullable = true;
colvarFreight.IsPrimaryKey = false;
colvarFreight.IsForeignKey = false;
colvarFreight.IsReadOnly = false;
colvarFreight.DefaultSetting = @"((0))";
colvarFreight.ForeignKeyTableName = "";
schema.Columns.Add(colvarFreight);
TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema);
colvarShipName.ColumnName = "ShipName";
colvarShipName.DataType = DbType.String;
colvarShipName.MaxLength = 40;
colvarShipName.AutoIncrement = false;
colvarShipName.IsNullable = true;
colvarShipName.IsPrimaryKey = false;
colvarShipName.IsForeignKey = false;
colvarShipName.IsReadOnly = false;
colvarShipName.DefaultSetting = @"";
colvarShipName.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipName);
TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema);
colvarShipAddress.ColumnName = "ShipAddress";
colvarShipAddress.DataType = DbType.String;
colvarShipAddress.MaxLength = 60;
colvarShipAddress.AutoIncrement = false;
colvarShipAddress.IsNullable = true;
colvarShipAddress.IsPrimaryKey = false;
colvarShipAddress.IsForeignKey = false;
colvarShipAddress.IsReadOnly = false;
colvarShipAddress.DefaultSetting = @"";
colvarShipAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipAddress);
TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema);
colvarShipCity.ColumnName = "ShipCity";
colvarShipCity.DataType = DbType.String;
colvarShipCity.MaxLength = 15;
colvarShipCity.AutoIncrement = false;
colvarShipCity.IsNullable = true;
colvarShipCity.IsPrimaryKey = false;
colvarShipCity.IsForeignKey = false;
colvarShipCity.IsReadOnly = false;
colvarShipCity.DefaultSetting = @"";
colvarShipCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCity);
TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema);
colvarShipRegion.ColumnName = "ShipRegion";
colvarShipRegion.DataType = DbType.String;
colvarShipRegion.MaxLength = 15;
colvarShipRegion.AutoIncrement = false;
colvarShipRegion.IsNullable = true;
colvarShipRegion.IsPrimaryKey = false;
colvarShipRegion.IsForeignKey = false;
colvarShipRegion.IsReadOnly = false;
colvarShipRegion.DefaultSetting = @"";
colvarShipRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipRegion);
TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema);
colvarShipPostalCode.ColumnName = "ShipPostalCode";
colvarShipPostalCode.DataType = DbType.String;
colvarShipPostalCode.MaxLength = 10;
colvarShipPostalCode.AutoIncrement = false;
colvarShipPostalCode.IsNullable = true;
colvarShipPostalCode.IsPrimaryKey = false;
colvarShipPostalCode.IsForeignKey = false;
colvarShipPostalCode.IsReadOnly = false;
colvarShipPostalCode.DefaultSetting = @"";
colvarShipPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipPostalCode);
TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema);
colvarShipCountry.ColumnName = "ShipCountry";
colvarShipCountry.DataType = DbType.String;
colvarShipCountry.MaxLength = 15;
colvarShipCountry.AutoIncrement = false;
colvarShipCountry.IsNullable = true;
colvarShipCountry.IsPrimaryKey = false;
colvarShipCountry.IsForeignKey = false;
colvarShipCountry.IsReadOnly = false;
colvarShipCountry.DefaultSetting = @"";
colvarShipCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCountry);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Orders",schema);
}
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get { return GetColumnValue<int>(Columns.OrderID); }
set { SetColumnValue(Columns.OrderID, value); }
}
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int? EmployeeID
{
get { return GetColumnValue<int?>(Columns.EmployeeID); }
set { SetColumnValue(Columns.EmployeeID, value); }
}
[XmlAttribute("OrderDate")]
[Bindable(true)]
public DateTime? OrderDate
{
get { return GetColumnValue<DateTime?>(Columns.OrderDate); }
set { SetColumnValue(Columns.OrderDate, value); }
}
[XmlAttribute("RequiredDate")]
[Bindable(true)]
public DateTime? RequiredDate
{
get { return GetColumnValue<DateTime?>(Columns.RequiredDate); }
set { SetColumnValue(Columns.RequiredDate, value); }
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get { return GetColumnValue<DateTime?>(Columns.ShippedDate); }
set { SetColumnValue(Columns.ShippedDate, value); }
}
[XmlAttribute("ShipVia")]
[Bindable(true)]
public int? ShipVia
{
get { return GetColumnValue<int?>(Columns.ShipVia); }
set { SetColumnValue(Columns.ShipVia, value); }
}
[XmlAttribute("Freight")]
[Bindable(true)]
public decimal? Freight
{
get { return GetColumnValue<decimal?>(Columns.Freight); }
set { SetColumnValue(Columns.Freight, value); }
}
[XmlAttribute("ShipName")]
[Bindable(true)]
public string ShipName
{
get { return GetColumnValue<string>(Columns.ShipName); }
set { SetColumnValue(Columns.ShipName, value); }
}
[XmlAttribute("ShipAddress")]
[Bindable(true)]
public string ShipAddress
{
get { return GetColumnValue<string>(Columns.ShipAddress); }
set { SetColumnValue(Columns.ShipAddress, value); }
}
[XmlAttribute("ShipCity")]
[Bindable(true)]
public string ShipCity
{
get { return GetColumnValue<string>(Columns.ShipCity); }
set { SetColumnValue(Columns.ShipCity, value); }
}
[XmlAttribute("ShipRegion")]
[Bindable(true)]
public string ShipRegion
{
get { return GetColumnValue<string>(Columns.ShipRegion); }
set { SetColumnValue(Columns.ShipRegion, value); }
}
[XmlAttribute("ShipPostalCode")]
[Bindable(true)]
public string ShipPostalCode
{
get { return GetColumnValue<string>(Columns.ShipPostalCode); }
set { SetColumnValue(Columns.ShipPostalCode, value); }
}
[XmlAttribute("ShipCountry")]
[Bindable(true)]
public string ShipCountry
{
get { return GetColumnValue<string>(Columns.ShipCountry); }
set { SetColumnValue(Columns.ShipCountry, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.OrderDetailCollection OrderDetails()
{
return new Northwind.OrderDetailCollection().Where(OrderDetail.Columns.OrderID, OrderID).Load();
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a Customer ActiveRecord object related to this Order
///
/// </summary>
public Northwind.Customer Customer
{
get { return Northwind.Customer.FetchByID(this.CustomerID); }
set { SetColumnValue("CustomerID", value.CustomerID); }
}
/// <summary>
/// Returns a Employee ActiveRecord object related to this Order
///
/// </summary>
public Northwind.Employee Employee
{
get { return Northwind.Employee.FetchByID(this.EmployeeID); }
set { SetColumnValue("EmployeeID", value.EmployeeID); }
}
/// <summary>
/// Returns a Shipper ActiveRecord object related to this Order
///
/// </summary>
public Northwind.Shipper Shipper
{
get { return Northwind.Shipper.FetchByID(this.ShipVia); }
set { SetColumnValue("ShipVia", value.ShipperID); }
}
#endregion
#region Many To Many Helpers
public Northwind.ProductCollection GetProductCollection() { return Order.GetProductCollection(this.OrderID); }
public static Northwind.ProductCollection GetProductCollection(int varOrderID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[Products] INNER JOIN [Order Details] ON [Products].[ProductID] = [Order Details].[ProductID] WHERE [Order Details].[OrderID] = @OrderID", Order.Schema.Provider.Name);
cmd.AddParameter("@OrderID", varOrderID, DbType.Int32);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
ProductCollection coll = new ProductCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveProductMap(int varOrderID, ProductCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[OrderID] = @OrderID", Order.Schema.Provider.Name);
cmdDel.AddParameter("@OrderID", varOrderID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (Product item in items)
{
OrderDetail varOrderDetail = new OrderDetail();
varOrderDetail.SetColumnValue("OrderID", varOrderID);
varOrderDetail.SetColumnValue("ProductID", item.GetPrimaryKeyValue());
varOrderDetail.Save();
}
}
public static void SaveProductMap(int varOrderID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[OrderID] = @OrderID", Order.Schema.Provider.Name);
cmdDel.AddParameter("@OrderID", varOrderID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
OrderDetail varOrderDetail = new OrderDetail();
varOrderDetail.SetColumnValue("OrderID", varOrderID);
varOrderDetail.SetColumnValue("ProductID", l.Value);
varOrderDetail.Save();
}
}
}
public static void SaveProductMap(int varOrderID , int[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[OrderID] = @OrderID", Order.Schema.Provider.Name);
cmdDel.AddParameter("@OrderID", varOrderID, DbType.Int32);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (int item in itemList)
{
OrderDetail varOrderDetail = new OrderDetail();
varOrderDetail.SetColumnValue("OrderID", varOrderID);
varOrderDetail.SetColumnValue("ProductID", item);
varOrderDetail.Save();
}
}
public static void DeleteProductMap(int varOrderID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[OrderID] = @OrderID", Order.Schema.Provider.Name);
cmdDel.AddParameter("@OrderID", varOrderID, DbType.Int32);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerID,int? varEmployeeID,DateTime? varOrderDate,DateTime? varRequiredDate,DateTime? varShippedDate,int? varShipVia,decimal? varFreight,string varShipName,string varShipAddress,string varShipCity,string varShipRegion,string varShipPostalCode,string varShipCountry)
{
Order item = new Order();
item.CustomerID = varCustomerID;
item.EmployeeID = varEmployeeID;
item.OrderDate = varOrderDate;
item.RequiredDate = varRequiredDate;
item.ShippedDate = varShippedDate;
item.ShipVia = varShipVia;
item.Freight = varFreight;
item.ShipName = varShipName;
item.ShipAddress = varShipAddress;
item.ShipCity = varShipCity;
item.ShipRegion = varShipRegion;
item.ShipPostalCode = varShipPostalCode;
item.ShipCountry = varShipCountry;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varOrderID,string varCustomerID,int? varEmployeeID,DateTime? varOrderDate,DateTime? varRequiredDate,DateTime? varShippedDate,int? varShipVia,decimal? varFreight,string varShipName,string varShipAddress,string varShipCity,string varShipRegion,string varShipPostalCode,string varShipCountry)
{
Order item = new Order();
item.OrderID = varOrderID;
item.CustomerID = varCustomerID;
item.EmployeeID = varEmployeeID;
item.OrderDate = varOrderDate;
item.RequiredDate = varRequiredDate;
item.ShippedDate = varShippedDate;
item.ShipVia = varShipVia;
item.Freight = varFreight;
item.ShipName = varShipName;
item.ShipAddress = varShipAddress;
item.ShipCity = varShipCity;
item.ShipRegion = varShipRegion;
item.ShipPostalCode = varShipPostalCode;
item.ShipCountry = varShipCountry;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn OrderIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EmployeeIDColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn OrderDateColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn RequiredDateColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ShippedDateColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn ShipViaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FreightColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ShipNameColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ShipAddressColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ShipCityColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn ShipRegionColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn ShipPostalCodeColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ShipCountryColumn
{
get { return Schema.Columns[13]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string CustomerID = @"CustomerID";
public static string EmployeeID = @"EmployeeID";
public static string OrderDate = @"OrderDate";
public static string RequiredDate = @"RequiredDate";
public static string ShippedDate = @"ShippedDate";
public static string ShipVia = @"ShipVia";
public static string Freight = @"Freight";
public static string ShipName = @"ShipName";
public static string ShipAddress = @"ShipAddress";
public static string ShipCity = @"ShipCity";
public static string ShipRegion = @"ShipRegion";
public static string ShipPostalCode = @"ShipPostalCode";
public static string ShipCountry = @"ShipCountry";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public partial class CCDrawingPrimitives
{
static CCDrawManager drawManager;
static CCPrimitiveBatch batch;
public static float PointSize { get; set; }
public static CCColor4B DrawColor { get; set; }
public static float LineWidth { get; set; }
internal static void Initialize(GraphicsDevice graphics, CCDrawManager drawManager)
{
batch = new CCPrimitiveBatch(drawManager);
CCDrawingPrimitives.drawManager = drawManager;
DrawColor = CCColor4B.White;
LineWidth = 1;
PointSize = 1.0f;
}
public static void Begin()
{
batch.Begin();
}
public static void End()
{
batch.End();
// Restore original values
DrawColor = CCColor4B.White;
LineWidth = 1;
PointSize = 1.0f;
}
public static void PushMatrix()
{
drawManager.PushMatrix();
}
public static void PopMatrix()
{
drawManager.PopMatrix();
}
public static void Translate(float x, float y, int z)
{
drawManager.Translate(x, y, z);
}
public static void DrawPoint(CCPoint point)
{
DrawPoint(point, PointSize, DrawColor);
}
public static void DrawPoint(CCPoint point, float size)
{
DrawPoint(point, size, DrawColor);
}
public static void DrawPoint(CCPoint p, float size, CCColor4B color)
{
var verts = new CCPoint[4];
float hs = size / 2.0f;
verts[0] = p + new CCPoint(-hs, -hs);
verts[1] = p + new CCPoint(hs, -hs);
verts[2] = p + new CCPoint(hs, hs);
verts[3] = p + new CCPoint(-hs, hs);
DrawPoly(verts, 4, false, true, color);
}
public static void DrawPoints(CCPoint[] points, float size, CCColor4B color)
{
DrawPoints(points, points.Length, size, color);
}
public static void DrawPoints(CCPoint[] points, float size)
{
DrawPoints(points, points.Length, size, DrawColor);
}
public static void DrawPoints(CCPoint[] points)
{
DrawPoints(points, points.Length, PointSize, DrawColor);
}
public static void DrawPoints(CCPoint[] points, int numberOfPoints, float size, CCColor4B color)
{
for (int i = 0; i < numberOfPoints; i++)
{
DrawPoint(points[i], size, color);
}
}
public static void DrawLine(CCPoint origin, CCPoint destination, CCColor4B color)
{
var a = origin;
var b = destination;
var n = CCPoint.Normalize(CCPoint.PerpendicularCCW(a - b));
var lww = LineWidth * 0.5f;
var nw = n * lww;
var v0 = b - nw;
var v1 = b + nw;
var v2 = a - nw;
var v3 = a + nw;
// Triangles from beginning to end
batch.AddVertex(v1, color, PrimitiveType.TriangleList);
batch.AddVertex(v2, color, PrimitiveType.TriangleList);
batch.AddVertex(v0, color, PrimitiveType.TriangleList);
batch.AddVertex(v1, color, PrimitiveType.TriangleList);
batch.AddVertex(v2, color, PrimitiveType.TriangleList);
batch.AddVertex(v3, color, PrimitiveType.TriangleList);
}
public static void DrawLine(CCPoint origin, CCPoint destination)
{
DrawLine(origin, destination, DrawColor);
}
public static void DrawRect(CCRect rect, CCColor4B color)
{
float x1 = rect.MinX;
float y1 = rect.MinY;
float x2 = rect.MaxX;
float y2 = rect.MaxY;
DrawLine(new CCPoint(x1, y1), new CCPoint(x2, y1), color);
DrawLine(new CCPoint(x2, y1), new CCPoint(x2, y2), color);
DrawLine(new CCPoint(x2, y2), new CCPoint(x1, y2), color);
DrawLine(new CCPoint(x1, y2), new CCPoint(x1, y1), color);
}
/// <summary>
/// draws a poligon given a pointer to CCPoint coordiantes and the number of vertices measured in points.
/// The polygon can be closed or open
/// </summary>
public static void DrawPoly(CCPoint[] vertices, int numOfVertices, bool closePolygon)
{
DrawPoly(vertices, numOfVertices, closePolygon, false, DrawColor);
}
/// <summary>
/// draws a poligon given a pointer to CCPoint coordiantes and the number of vertices measured in points.
/// The polygon can be closed or open
/// </summary>
public static void DrawPoly(CCPoint[] vertices, CCColor4B color, bool closePolygon = false)
{
DrawPoly(vertices, vertices.Length, closePolygon, false, color);
}
/// <summary>
/// draws a poligon given a pointer to CCPoint coordiantes and the number of vertices measured in points.
/// The polygon can be closed or open
/// </summary>
public static void DrawPoly(CCPoint[] vertices, bool closePolygon = false)
{
DrawPoly(vertices, vertices.Length, closePolygon, false, DrawColor);
}
/// <summary>
/// draws a poligon given a pointer to CCPoint coordiantes and the number of vertices measured in points.
/// The polygon can be closed or open
/// </summary>
public static void DrawPoly(CCPoint[] vertices, int numOfVertices, bool closePolygon, CCColor4B color)
{
DrawPoly(vertices, numOfVertices, closePolygon, false, color);
}
/// <summary>
/// draws a polygon given a pointer to CCPoint coordiantes and the number of vertices measured in points.
/// The polygon can be closed or open and optionally filled with current GL color
/// </summary>
public static void DrawPoly(CCPoint[] vertices, int numOfVertices, bool closePolygon, bool fill, CCColor4B color)
{
if (fill)
{
for (int i = 1; i < numOfVertices - 1; i++)
{
batch.AddVertex(new CCVector2(vertices[0].X, vertices[0].Y), color, PrimitiveType.TriangleList);
batch.AddVertex(new CCVector2(vertices[i].X, vertices[i].Y), color, PrimitiveType.TriangleList);
batch.AddVertex(new CCVector2(vertices[i + 1].X, vertices[i + 1].Y), color, PrimitiveType.TriangleList);
}
}
else
{
for (int i = 0; i < numOfVertices - 1; i++)
{
DrawLine(vertices[i], vertices[i + 1], color);
}
if (closePolygon)
{
DrawLine(vertices[numOfVertices - 1], vertices[0], color);
}
}
}
public static void DrawSolidPoly(CCPoint[] vertices, CCColor4B color)
{
DrawSolidPoly(vertices, vertices.Length, color, false);
}
public static void DrawSolidPoly(CCPoint[] vertices, int count, CCColor4B color)
{
DrawSolidPoly(vertices, count, color, false);
}
public static void DrawSolidPoly(CCPoint[] vertices, int count, CCColor4B color, bool outline)
{
if (count == 2)
{
DrawPoly(vertices, count, false, color);
return;
}
var colorFill = color * (outline ? 0.5f : 1.0f);
for (int i = 1; i < count - 1; i++)
{
batch.AddVertex(new CCVector2(vertices[0].X, vertices[0].Y), colorFill, PrimitiveType.TriangleList);
batch.AddVertex(new CCVector2(vertices[i].X, vertices[i].Y), colorFill, PrimitiveType.TriangleList);
batch.AddVertex(new CCVector2(vertices[i + 1].X, vertices[i + 1].Y), colorFill, PrimitiveType.TriangleList);
}
if (outline)
{
DrawPoly(vertices, count, true, color);
}
}
public static void DrawSolidRect(CCPoint origin, CCPoint destination, CCColor4B color)
{
CCPoint[] vertices =
{
origin,
new CCPoint(destination.X, origin.Y),
destination,
new CCPoint(origin.X, destination.Y),
};
DrawSolidPoly(vertices, 4, color);
}
/// <summary>
///
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="angle">The amount of the circle to draw, in radiians</param>
/// <param name="segments"></param>
/// <param name="drawLineToCenter"></param>
/// <param name="color"></param>
public static void DrawCircle(CCPoint center, float radius, float angle, int segments, bool drawLineToCenter, CCColor4B color, float scaleX = 1.0f, float scaleY = 1.0f)
{
float increment = MathHelper.Pi * 2.0f / segments;
double theta = angle;
var vertices = new CCPoint[segments * 2];
for (int i = 0, s=0; i < segments; i++, s += 2)
{
vertices[s] = center + new CCPoint((float) Math.Cos(theta) * scaleX, (float) Math.Sin(theta) * scaleY) * radius;
vertices[s + 1] = center + new CCPoint((float) Math.Cos(theta + increment) * scaleX, (float) Math.Sin(theta + increment) * scaleY) * radius;
theta += increment;
}
DrawPoly(vertices, color);
if (drawLineToCenter)
{
DrawLine(center, vertices[vertices.Length-1], color);
}
}
/// <summary>
///
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="angle">The amount of the circle to draw, in radiians</param>
/// <param name="segments"></param>
/// <param name="drawLineToCenter"></param>
/// <param name="color"></param>
public static void DrawCircle(CCPoint center, float radius, float angle, int segments, bool drawLineToCenter, float scaleX = 1.0f, float scaleY = 1.0f)
{
DrawCircle(center, radius, angle, segments, drawLineToCenter, DrawColor, scaleX, scaleY);
}
public static void DrawSolidCircle(CCPoint center, float radius, float angle, int segments, float scaleX = 1.0f, float scaleY = 1.0f)
{
DrawSolidCircle(center, radius, angle, segments, DrawColor, scaleX, scaleY);
}
/// <summary>
///
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="angle">The amount of the circle to draw, in radiians</param>
/// <param name="segments"></param>
/// <param name="color"></param>
public static void DrawSolidCircle(CCPoint center, float radius, float angle, int segments, CCColor4B color, float scaleX = 1.0f, float scaleY = 1.0f)
{
float increment = MathHelper.Pi * 2.0f / segments;
double theta = angle;
var vertices = new CCPoint[segments * 2];
for (int i = 0, s=0; i < segments; i++, s += 2)
{
vertices[s] = center + new CCPoint((float) Math.Cos(theta) * scaleX, (float) Math.Sin(theta) * scaleY) * radius;
vertices[s + 1] = center + new CCPoint((float) Math.Cos(theta + increment) * scaleX, (float) Math.Sin(theta + increment) * scaleY) * radius;
theta += increment;
}
DrawSolidPoly(vertices, color);
}
public static void DrawArc (CCRect rect, int startAngle, int sweepAngle)
{
DrawEllipticalArc(rect, startAngle, sweepAngle, false, DrawColor);
}
public static void DrawArc (CCRect rect, int startAngle, int sweepAngle, CCColor4B color)
{
DrawEllipticalArc(rect, startAngle, sweepAngle, false, color);
}
public static void DrawArc (int x, int y, int width, int height, int startAngle, int sweepAngle)
{
DrawEllipticalArc(x,y,width,height,startAngle,sweepAngle,false, DrawColor);
}
public static void DrawArc (int x, int y, int width, int height, int startAngle, int sweepAngle, CCColor4B color)
{
DrawEllipticalArc(x,y,width,height,startAngle,sweepAngle,false, color);
}
public static void DrawEllipse (CCRect rect)
{
DrawEllipticalArc(rect, 0, 360, false, DrawColor);
}
public static void DrawEllipse (CCRect rect, CCColor4B color)
{
DrawEllipticalArc(rect, 0, 360, false, color);
}
public static void DrawEllips (int x, int y, int width, int height)
{
DrawEllipticalArc(x,y,width,height,0,360,false, DrawColor);
}
public static void DrawEllips (int x, int y, int width, int height, CCColor4B color)
{
DrawEllipticalArc(x,y,width,height,0,360,false, color);
}
public static void DrawPie (CCRect rect, int startAngle, int sweepAngle)
{
DrawEllipticalArc(rect, startAngle, sweepAngle, true, DrawColor);
}
public static void DrawPie (CCRect rect, int startAngle, int sweepAngle, CCColor4B color)
{
DrawEllipticalArc(rect, startAngle, sweepAngle, true, color);
}
public static void DrawPie (int x, int y, int width, int height, int startAngle, int sweepAngle)
{
DrawEllipticalArc(x,y,width,height,startAngle,sweepAngle,true, DrawColor);
}
public static void DrawPie (int x, int y, int width, int height, int startAngle, int sweepAngle, CCColor4B color)
{
DrawEllipticalArc(x,y,width,height,startAngle,sweepAngle,true, color);
}
public static void DrawQuadBezier(CCPoint origin, CCPoint control, CCPoint destination, int segments)
{
DrawQuadBezier(origin, control, destination, segments, DrawColor);
}
public static void DrawQuadBezier(CCPoint origin, CCPoint control, CCPoint destination, int segments, CCColor4B color)
{
float t = 0;
float increment = 1.0f / segments;
var vertices = new CCPoint[segments];
vertices[0] = origin;
for (int i = 1; i < segments; ++i, t+= increment)
{
vertices[i].X = CCSplineMath.QuadBezier(origin.X, control.X, destination.X, t);
vertices[i].Y = CCSplineMath.QuadBezier(origin.Y, control.Y, destination.Y, t);
}
vertices[segments-1] = destination;
DrawPoly(vertices, color);
}
public static void DrawCubicBezier(CCPoint origin, CCPoint control1, CCPoint control2, CCPoint destination, int segments)
{
DrawCubicBezier(origin, control1, control2, destination, segments, DrawColor);
}
/// <summary>
/// draws a cubic bezier path
/// @since v0.8
/// </summary>
public static void DrawCubicBezier(CCPoint origin, CCPoint control1, CCPoint control2, CCPoint destination, int segments, CCColor4B color)
{
float t = 0;
float increment = 1.0f / segments;
var vertices = new CCPoint[segments];
vertices[0] = origin;
for (int i = 1; i < segments; ++i, t+= increment)
{
vertices[i].X = CCSplineMath.CubicBezier(origin.X, control1.X, control2.X, destination.X, t);
vertices[i].Y = CCSplineMath.CubicBezier(origin.Y, control1.Y, control2.Y, destination.Y, t);
}
vertices[segments - 1] = destination;
DrawPoly(vertices, color);
}
public static void DrawCatmullRom(List<CCPoint> points, int segments)
{
DrawCardinalSpline(points, 0.5f, segments);
}
public static void DrawCardinalSpline(List<CCPoint> config, float tension, int segments)
{
int p;
float lt;
float deltaT = 1.0f / config.Count;
int count = config.Count;
var vertices = new CCPoint[segments + 1];
for (int i = 0; i < segments + 1; i++)
{
float dt = (float) i / segments;
// border
if (dt == 1)
{
p = count - 1;
lt = 1;
}
else
{
p = (int) (dt / deltaT);
lt = (dt - deltaT * p) / deltaT;
}
// Interpolate
int c = config.Count - 1;
CCPoint pp0 = config[Math.Min(c, Math.Max(p - 1, 0))];
CCPoint pp1 = config[Math.Min(c, Math.Max(p + 0, 0))];
CCPoint pp2 = config[Math.Min(c, Math.Max(p + 1, 0))];
CCPoint pp3 = config[Math.Min(c, Math.Max(p + 2, 0))];
vertices[i] = CCSplineMath.CCCardinalSplineAt(pp0, pp1, pp2, pp3, tension, lt);
}
DrawPoly(vertices, DrawColor);
}
public void DrawTriangleList (CCV3F_C4B[] verts)
{
for (int x = 0; x < verts.Length; x++)
{
batch.AddVertex(verts[x].Vertices, verts[x].Colors, PrimitiveType.TriangleList);
}
}
public void DrawLineList (CCV3F_C4B[] verts)
{
for (int x = 0; x < verts.Length; x++)
{
batch.AddVertex(verts[x].Vertices, verts[x].Colors, PrimitiveType.LineList);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Data.Tables.Models;
using Azure.Data.Tables.Sas;
namespace Azure.Data.Tables
{
/// <summary>
/// The <see cref="TableServiceClient"/> provides synchronous and asynchronous methods to perform table level operations with Azure Tables hosted in either Azure storage accounts or Azure Cosmos DB table API.
/// </summary>
public class TableServiceClient
{
private readonly ClientDiagnostics _diagnostics;
private readonly TableRestClient _tableOperations;
private readonly ServiceRestClient _serviceOperations;
private readonly ServiceRestClient _secondaryServiceOperations;
private readonly OdataMetadataFormat _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata;
private readonly string _version;
internal readonly bool _isPremiumEndpoint;
private readonly QueryOptions _defaultQueryOptions = new QueryOptions() { Format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata };
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified <see cref="Uri" /> containing a shared access signature (SAS)
/// token credential. See <see cref="TableClient.GetSasBuilder(TableSasPermissions, DateTimeOffset)" /> for creating a SAS token.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
public TableServiceClient(Uri endpoint)
: this(endpoint, options: null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified connection string.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
public TableServiceClient(string connectionString)
: this(connectionString, options: null)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified <see cref="Uri" /> containing a shared access signature (SAS)
/// token credential. See <see cref="TableClient.GetSasBuilder(TableSasPermissions, DateTimeOffset)" /> for creating a SAS token.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(Uri endpoint, TableClientOptions options = null)
: this(endpoint, default(TableSharedKeyPipelinePolicy), options)
{
if (endpoint.Scheme != "https")
{
throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified table service <see cref="Uri" /> and <see cref="TableSharedKeyCredential" />.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared key credential used to sign requests.</param>
public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential)
: this(endpoint, new TableSharedKeyPipelinePolicy(credential), null)
{
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified table service <see cref="Uri" /> and <see cref="TableSharedKeyCredential" />.
/// </summary>
/// <param name="endpoint">
/// A <see cref="Uri"/> referencing the table service account.
/// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
/// </param>
/// <param name="credential">The shared key credential used to sign requests.</param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential, TableClientOptions options = null)
: this(endpoint, new TableSharedKeyPipelinePolicy(credential), options)
{
Argument.AssertNotNull(credential, nameof(credential));
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified connection string.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
/// </param>
public TableServiceClient(string connectionString, TableClientOptions options = null)
{
Argument.AssertNotNull(connectionString, nameof(connectionString));
TableConnectionString connString = TableConnectionString.Parse(connectionString);
options ??= new TableClientOptions();
var endpointString = connString.TableStorageUri.PrimaryUri.AbsoluteUri;
var secondaryEndpoint = connString.TableStorageUri.SecondaryUri?.AbsoluteUri;
TableSharedKeyPipelinePolicy policy = connString.Credentials switch
{
TableSharedKeyCredential credential => new TableSharedKeyPipelinePolicy(credential),
_ => default
};
HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy);
_version = options.VersionString;
_diagnostics = new ClientDiagnostics(options);
_tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString, _version);
_serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString, _version);
_secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint, _version);
_isPremiumEndpoint = IsPremiumEndpoint(connString.TableStorageUri.PrimaryUri);
}
internal TableServiceClient(Uri endpoint, TableSharedKeyPipelinePolicy policy, TableClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
options ??= new TableClientOptions();
var endpointString = endpoint.AbsoluteUri;
string secondaryEndpoint = TableConnectionString.GetSecondaryUriFromPrimary(endpoint)?.AbsoluteUri;
HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy);
_version = options.VersionString;
_diagnostics = new ClientDiagnostics(options);
_tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString, _version);
_serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString, _version);
_secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint, _version);
_isPremiumEndpoint = IsPremiumEndpoint(endpoint);
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/>
/// class for mocking.
/// </summary>
internal TableServiceClient(TableRestClient internalClient)
{
_tableOperations = internalClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="TableServiceClient"/>
/// class for mocking.
/// </summary>
protected TableServiceClient()
{ }
/// <summary>
/// Gets a <see cref="TableSasBuilder"/> instance scoped to the current account.
/// </summary>
/// <param name="permissions"><see cref="TableAccountSasPermissions"/> containing the allowed permissions.</param>
/// <param name="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param>
/// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param>
/// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns>
public virtual TableAccountSasBuilder GetSasBuilder(TableAccountSasPermissions permissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn)
{
return new TableAccountSasBuilder(permissions, resourceTypes, expiresOn) { Version = _version };
}
/// <summary>
/// Gets a <see cref="TableAccountSasBuilder"/> instance scoped to the current table.
/// </summary>
/// <param name="rawPermissions">The permissions associated with the shared access signature. This string should contain one or more of the following permission characters in this order: "racwdl".</param>
/// <param name="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param>
/// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param>
/// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns>
public virtual TableAccountSasBuilder GetSasBuilder(string rawPermissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn)
{
return new TableAccountSasBuilder(rawPermissions, resourceTypes, expiresOn) { Version = _version };
}
/// <summary>
/// Gets an instance of a <see cref="TableClient"/> configured with the current <see cref="TableServiceClient"/> options, affinitized to the specified <paramref name="tableName"/>.
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public virtual TableClient GetTableClient(string tableName)
{
Argument.AssertNotNull(tableName, nameof(tableName));
return new TableClient(tableName, _tableOperations, _version, _diagnostics, _isPremiumEndpoint);
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">Returns only tables that satisfy the specified filter.</param>
/// <param name="maxPerPage">
/// The maximum number of tables that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AsyncPageable{T}"/> containing a collection of <see cref="TableItem"/>s.</returns>
public virtual AsyncPageable<TableItem> GetTablesAsync(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
return PageableHelpers.CreateAsyncEnumerable(
async pageSizeHint =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = await _tableOperations.QueryAsync(
null,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
async (nextLink, pageSizeHint) =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = await _tableOperations.QueryAsync(
nextTableName: nextLink,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
maxPerPage);
}
/// <summary>
/// Gets a list of tables from the storage account.
/// </summary>
/// <param name="filter">Returns only tables that satisfy the specified filter.</param>
/// <param name="maxPerPage">
/// The maximum number tables that will be returned per page.
/// Note: This value does not limit the total number of results if the result is fully enumerated.
/// </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="Pageable{T}"/> containing a collection of <see cref="TableItem"/>.</returns>
public virtual Pageable<TableItem> GetTables(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default)
{
return PageableHelpers.CreateEnumerable(
pageSizeHint =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = _tableOperations.Query(
null,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
(nextLink, pageSizeHint) =>
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}");
scope.Start();
try
{
var response = _tableOperations.Query(
nextTableName: nextLink,
new QueryOptions() { Filter = filter, Select = null, Top = pageSizeHint, Format = _format },
cancellationToken);
return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
},
maxPerPage);
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns>
public virtual Response<TableItem> CreateTable(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}");
scope.Start();
try
{
var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns>
public virtual async Task<Response<TableItem>> CreateTableAsync(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}");
scope.Start();
try
{
var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns>
public virtual Response<TableItem> CreateTableIfNotExists(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}");
scope.Start();
try
{
var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
return default;
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns>
public virtual async Task<Response<TableItem>> CreateTableIfNotExistsAsync(string tableName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tableName, nameof(tableName));
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}");
scope.Start();
try
{
var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, null, queryOptions: _defaultQueryOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value as TableItem, response.GetRawResponse());
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
return default;
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual Response DeleteTable(string tableName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}");
scope.Start();
try
{
return _tableOperations.Delete(tableName, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes a table on the service.
/// </summary>
/// <param name="tableName">The name of the table to create.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual async Task<Response> DeleteTableAsync(string tableName, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}");
scope.Start();
try
{
return await _tableOperations.DeleteAsync(tableName, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="properties"> The Table Service properties. </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual Response SetProperties(TableServiceProperties properties, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}");
scope.Start();
try
{
return _serviceOperations.SetProperties(properties, cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="properties"> The Table Service properties. </param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response"/> indicating the result of the operation.</returns>
public virtual async Task<Response> SetPropertiesAsync(TableServiceProperties properties, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}");
scope.Start();
try
{
return await _serviceOperations.SetPropertiesAsync(properties, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response{TableServiceProperties}"/> indicating the result of the operation.</returns>
public virtual Response<TableServiceProperties> GetProperties(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}");
scope.Start();
try
{
var response = _serviceOperations.GetProperties(cancellationToken: cancellationToken);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The <see cref="Response{TableServiceProperties}"/> indicating the result of the operation.</returns>
public virtual async Task<Response<TableServiceProperties>> GetPropertiesAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}");
scope.Start();
try
{
var response = await _serviceOperations.GetPropertiesAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public virtual async Task<Response<TableServiceStatistics>> GetStatisticsAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}");
scope.Start();
try
{
var response = await _secondaryServiceOperations.GetStatisticsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public virtual Response<TableServiceStatistics> GetStatistics(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}");
scope.Start();
try
{
var response = _secondaryServiceOperations.GetStatistics(cancellationToken: cancellationToken);
return Response.FromValue(response.Value, response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
internal static bool IsPremiumEndpoint(Uri endpoint)
{
string absoluteUri = endpoint.OriginalString.ToLowerInvariant();
return (endpoint.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) && endpoint.Port != 10002) ||
absoluteUri.Contains(TableConstants.CosmosTableDomain) || absoluteUri.Contains(TableConstants.LegacyCosmosTableDomain);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane
{
internal partial class PreviewPane : UserControl, IDisposable
{
private const double DefaultWidth = 400;
private static readonly string s_dummyThreeLineTitle = "A" + Environment.NewLine + "A" + Environment.NewLine + "A";
private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
private readonly string _id;
private readonly bool _logIdVerbatimInTelemetry;
private bool _isExpanded;
private double _heightForThreeLineTitle;
private IWpfDifferenceViewer _previewDiffViewer;
public PreviewPane(
Image severityIcon,
string id,
string title,
string description,
Uri helpLink,
string helpLinkToolTipText,
IReadOnlyList<object> previewContent,
bool logIdVerbatimInTelemetry)
{
InitializeComponent();
_id = id;
_logIdVerbatimInTelemetry = logIdVerbatimInTelemetry;
// Initialize header portion.
if ((severityIcon != null) && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(title))
{
HeaderStackPanel.Visibility = Visibility.Visible;
SeverityIconBorder.Child = severityIcon;
// Set the initial title text to three lines worth so that we can measure the pixel height
// that WPF requires to render three lines of text under the current font and DPI settings.
TitleRun.Text = s_dummyThreeLineTitle;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
_heightForThreeLineTitle = TitleTextBlock.DesiredSize.Height;
// Now set the actual title text.
TitleRun.Text = title;
InitializeHyperlinks(helpLink, helpLinkToolTipText);
if (!string.IsNullOrWhiteSpace(description))
{
DescriptionParagraph.Inlines.Add(description);
}
}
// Initialize preview (i.e. diff view) portion.
InitializePreviewElement(previewContent);
}
private void InitializePreviewElement(IReadOnlyList<object> previewItems)
{
var previewElement = CreatePreviewElement(previewItems);
if (previewElement != null)
{
HeaderSeparator.Visibility = Visibility.Visible;
PreviewDockPanel.Visibility = Visibility.Visible;
PreviewScrollViewer.Content = previewElement;
previewElement.VerticalAlignment = VerticalAlignment.Top;
previewElement.HorizontalAlignment = HorizontalAlignment.Left;
}
// 1. Width of the header section should not exceed the width of the preview content.
// In other words, the text we put in the header at the top of the preview pane
// should not cause the preview pane itself to grow wider than the width required to
// display the preview content at the bottom of the pane.
// 2. Adjust the height of the header section so that it displays only three lines worth
// by default.
AdjustWidthAndHeight(previewElement);
}
private FrameworkElement CreatePreviewElement(IReadOnlyList<object> previewItems)
{
if (previewItems == null || previewItems.Count == 0)
{
return null;
}
const int MaxItems = 3;
if (previewItems.Count > MaxItems)
{
previewItems = previewItems.Take(MaxItems).Concat("...").ToList();
}
var grid = new Grid();
for (var i = 0; i < previewItems.Count; i++)
{
var previewItem = previewItems[i];
FrameworkElement previewElement = null;
if (previewItem is IWpfDifferenceViewer)
{
_previewDiffViewer = (IWpfDifferenceViewer)previewItem;
previewElement = _previewDiffViewer.VisualElement;
PreviewDockPanel.Background = _previewDiffViewer.InlineView.Background;
}
else if (previewItem is string)
{
previewElement = GetPreviewForString((string)previewItem);
}
else if (previewItem is FrameworkElement)
{
previewElement = (FrameworkElement)previewItem;
}
var rowDefinition = i == 0 ? new RowDefinition() : new RowDefinition() { Height = GridLength.Auto };
grid.RowDefinitions.Add(rowDefinition);
Grid.SetRow(previewElement, grid.RowDefinitions.IndexOf(rowDefinition));
grid.Children.Add(previewElement);
if (i == 0)
{
grid.Width = previewElement.Width;
}
}
var preview = grid.Children.Count == 0 ? (FrameworkElement)grid.Children[0] : grid;
return preview;
}
private void InitializeHyperlinks(Uri helpLink, string helpLinkToolTipText)
{
IdHyperlink.SetVSHyperLinkStyle();
LearnMoreHyperlink.SetVSHyperLinkStyle();
IdHyperlink.Inlines.Add(_id);
IdHyperlink.NavigateUri = helpLink;
IdHyperlink.IsEnabled = true;
IdHyperlink.ToolTip = helpLinkToolTipText;
LearnMoreHyperlink.Inlines.Add(string.Format(ServicesVSResources.LearnMoreLinkText, _id));
LearnMoreHyperlink.NavigateUri = helpLink;
LearnMoreHyperlink.ToolTip = helpLinkToolTipText;
}
private static FrameworkElement GetPreviewForString(string previewContent)
{
return new TextBlock()
{
Margin = new Thickness(5),
VerticalAlignment = VerticalAlignment.Center,
Text = previewContent,
TextWrapping = TextWrapping.Wrap,
};
}
// This method adjusts the width of the header section to match that of the preview content
// thereby ensuring that the preview pane itself is never wider than the preview content.
// This method also adjusts the height of the header section so that it displays only three lines
// worth by default.
private void AdjustWidthAndHeight(FrameworkElement previewElement)
{
var headerStackPanelWidth = double.PositiveInfinity;
var titleTextBlockHeight = double.PositiveInfinity;
if (previewElement == null)
{
HeaderStackPanel.Measure(availableSize: s_infiniteSize);
headerStackPanelWidth = HeaderStackPanel.DesiredSize.Width;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
else
{
PreviewDockPanel.Measure(availableSize: new Size(
double.IsNaN(previewElement.Width) ? DefaultWidth : previewElement.Width,
double.PositiveInfinity));
headerStackPanelWidth = PreviewDockPanel.DesiredSize.Width;
if (IsNormal(headerStackPanelWidth))
{
TitleTextBlock.Measure(availableSize: new Size(headerStackPanelWidth, double.PositiveInfinity));
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
}
if (IsNormal(headerStackPanelWidth))
{
HeaderStackPanel.Width = headerStackPanelWidth;
}
// If the pixel height required to render the complete title in the
// TextBlock is larger than that required to render three lines worth,
// then trim the contents of the TextBlock with an ellipsis at the end and
// display the expander button that will allow users to view the full text.
if (HasDescription || (IsNormal(titleTextBlockHeight) && (titleTextBlockHeight > _heightForThreeLineTitle)))
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
ExpanderToggleButton.Visibility = Visibility.Visible;
if (_isExpanded)
{
ExpanderToggleButton.IsChecked = true;
}
}
}
private static bool IsNormal(double size)
{
return size > 0 && !double.IsNaN(size) && !double.IsInfinity(size);
}
private bool HasDescription
{
get
{
return DescriptionParagraph.Inlines.Count > 0;
}
}
#region IDisposable Implementation
private bool _disposedValue = false;
// VS editor will call Dispose at which point we should Close() the embedded IWpfDifferenceViewer.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing && (_previewDiffViewer != null) && !_previewDiffViewer.IsClosed)
{
_previewDiffViewer.Close();
}
}
_disposedValue = true;
}
void IDisposable.Dispose()
{
Dispose(true);
}
#endregion
private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (e.Uri == null)
{
return;
}
BrowserHelper.StartBrowser(e.Uri);
e.Handled = true;
var hyperlink = sender as Hyperlink;
if (hyperlink == null)
{
return;
}
DiagnosticLogger.LogHyperlink(hyperlink.Name ?? "Preview", _id, HasDescription, _logIdVerbatimInTelemetry, e.Uri.AbsoluteUri);
}
private void ExpanderToggleButton_CheckedChanged(object sender, RoutedEventArgs e)
{
if (ExpanderToggleButton.IsChecked ?? false)
{
TitleTextBlock.MaxHeight = double.PositiveInfinity;
TitleTextBlock.TextTrimming = TextTrimming.None;
if (HasDescription)
{
DescriptionDockPanel.Visibility = Visibility.Visible;
if (LearnMoreHyperlink.NavigateUri != null)
{
LearnMoreTextBlock.Visibility = Visibility.Visible;
LearnMoreHyperlink.IsEnabled = true;
}
}
_isExpanded = true;
}
else
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
DescriptionDockPanel.Visibility = Visibility.Collapsed;
_isExpanded = false;
}
}
}
}
| |
#region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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.
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.Caching;
using System.Runtime.Caching.Hosting;
using System.Threading;
using System.Threading.Tasks;
using Gigya.Microdot.Interfaces.Logging;
using Gigya.Microdot.Interfaces.SystemWrappers;
using Gigya.ServiceContract.HttpService;
using Metrics;
using System.Threading.Tasks.Dataflow;
using Gigya.Common.Contracts.Attributes;
using Gigya.Common.Contracts.Exceptions;
using Gigya.Microdot.SharedLogic.Events;
using Gigya.Microdot.ServiceDiscovery.Config;
namespace Gigya.Microdot.ServiceProxy.Caching
{
public sealed class AsyncCache : IMemoryCacheManager, IServiceProvider, IDisposable
{
// Main data structures:
// 1. The main cache that maps a cache key to an actual cached response. Some responses may contain revoke keys.
// We use MemoryCache and not a ConcurrentDictionary since it has some nice features like approximating its
// RAM usage and evicting items when there's RAM pressure.
private MemoryCache MemoryCache { get; set; } // maps cache key --> AsyncCacheItem that contains the response.
// Note that we may cache null responses (as per caching settings).
// 2. The list of requests in progress. We optionally group concurrent incoming requests for the same item to a single outgoing
// request to the service, to reduce load on the target service. Each request returns a tuple with "Ok" denoting whether the
// response should be cached as per the caching settings for the method being called.
private ConcurrentDictionary<string, Lazy<Task<object>>> RequestsInProgress
= new ConcurrentDictionary<string, Lazy<Task<object>>>();
// 3. A "reverse index" that maps revoke keys to items in the MemoryCache above. When we receive a revoke message,
// we look up that index, find the relevant items in the main cache and remove them or mark them as stale.
// Similarly, when an item is removed from the MemoryCache, we remove matching reverse index entries.
// The MemoryCache and the reverse index MUST be kept in sync, otherwise we might miss revokes or have a memory leak.
private ConcurrentDictionary<string /* revoke key */, HashSet<AsyncCacheItem>> RevokeKeyToCacheItemsIndex
= new ConcurrentDictionary<string, HashSet<AsyncCacheItem>>();
// 4. Index that keeps track of recent revoke messages. When we get a response from a service, in case
// it contains a revoke key that was revoked after having sent the request to the service, we consider the response
// stale. This is needed since we can't know ahead of time what revoke keys a response will contain.
private IRecentRevokesCache RecentRevokesCache { get; set; }
private IDateTime DateTime { get; }
private ILog Log { get; }
private long LastCacheSizeBytes { get; set; }
private MetricsContext Metrics { get; }
private MetricsContext Hits { get; set; }
private MetricsContext Misses { get; set; }
private MetricsContext JoinedTeam { get; set; }
private MetricsContext AwaitingResult { get; set; }
private MetricsContext Failed { get; set; }
private MetricsContext Items { get; set; }
private MetricsContext Revokes { get; set; }
private IDisposable RevokeDisposable { get; }
private const double MB = 1048576.0;
private int _clearCount;
public int RevokeKeysCount => RevokeKeyToCacheItemsIndex.Count;
/// <summary>
/// Not thread safe used for testing
/// </summary>
internal int CacheKeyCount => RevokeKeyToCacheItemsIndex.Sum(item => item.Value.Count);
private static long oneTime = 0;
public AsyncCache(ILog log, MetricsContext metrics, IDateTime dateTime, IRevokeListener revokeListener,
IRecentRevokesCache revokeCache)
{
DateTime = dateTime;
Log = log;
RecentRevokesCache = revokeCache;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (ObjectCache.Host == null
&& Interlocked.CompareExchange(ref oneTime, 1, 0) == 0)
{
ObjectCache.Host = this;
}
else
Log.Error("AsyncCache: Failed to register with ObjectCache.Host since it was already registered. Cache memory size will not be reported to Metrics.NET. Please make sure AsyncCache is singleton to prevent this issue.");
Clear();
Metrics = metrics;
InitMetrics();
var onRevoke = new ActionBlock<string>(OnRevoke);
RevokeDisposable = revokeListener.RevokeSource.LinkTo(onRevoke);
}
private void InitMetrics()
{
// Gauges
Metrics.Gauge("Size", () => LastCacheSizeBytes / MB, Unit.MegaBytes);
Metrics.Gauge("Entries", () => MemoryCache.GetCount(), Unit.Items);
Metrics.Gauge("SizeLimit", () => MemoryCache.CacheMemoryLimit / MB, Unit.MegaBytes);
Metrics.Gauge("RamUsageLimit", () => MemoryCache.PhysicalMemoryLimit, Unit.Percent);
Metrics.Gauge("ReverseIndexEntries", () => RevokeKeyToCacheItemsIndex.Count, Unit.Items);
Metrics.Gauge("ReverseIndexEntriesAndValues", () => RevokeKeyToCacheItemsIndex.Values.Sum(hash => hash.Count), Unit.Items);
Metrics.Gauge("RequestsInProgress", () => RequestsInProgress.Count, Unit.Items);
// Counters
AwaitingResult = Metrics.Context("AwaitingResult");
// Meters
Hits = Metrics.Context("Hits");
Misses = Metrics.Context("Misses");
JoinedTeam = Metrics.Context("JoinedTeam");
Failed = Metrics.Context("Failed");
Items = Metrics.Context("Items");
Revokes = Metrics.Context("Revoke");
}
public Task GetOrAdd(string key, Func<Task> serviceMethod, Type taskResultType, string[] metricsKeys, IMethodCachingSettings settings)
{
var getValueTask = Task.Run(() => GetOrAdd(key, () =>
TaskConverter.ToWeaklyTypedTask(serviceMethod(), taskResultType), metricsKeys, settings));
return TaskConverter.ToStronglyTypedTask(getValueTask, taskResultType);
}
private async Task<object> GetOrAdd(string key, Func<Task<object>> serviceMethod, string[] metricsKeys, IMethodCachingSettings settings)
{
AsyncCacheItem cached;
Task<object> MarkHitAndReturnValue(Task<object> obj) { Hits.Mark(metricsKeys); return obj; }
// In case caching is suppressed, we don't try to obtain an existing value from the cache, or even wait on an existing request
// in progress. Meaning we potentially issue multiple concurrent calls to the service (no request grouping).
if ( TracingContext.CacheSuppress == CacheSuppress.UpToNextServices
|| TracingContext.CacheSuppress == CacheSuppress.RecursiveAllDownstreamServices)
// If the caching settings specify we shouldn't cache responses when suppressed, then don't.
if (settings.CacheResponsesWhenSupressedBehavior == CacheResponsesWhenSupressedBehavior.Disabled)
return await (await CallService(serviceMethod, metricsKeys)).response;
// ...otherwise we do put the response in the cache so that subsequent calls to the cache do not revert to the previously-cached value.
else return await TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Suppress);
// Found a cached response.
// WARNING! Immediately after calling the line below, another thread may set a new value in the cache, and lines below
// that call TryFetchNewValue() do it needlessly, causing a redundant refresh operation. This is a rare race
// condition with negligible negative effects so we can ignore it for the sake of the simplicity of the code.
else if ((cached = (AsyncCacheItem)MemoryCache.Get(key)) != null)
// Response was revoked and settings specify we should not use revoked responses
if (cached.IsRevoked && settings.RevokedResponseBehavior != RevokedResponseBehavior.KeepUsingRevokedResponse)
// The caching settings specify we should ignore revoked responses; issue a request.
if (settings.RevokedResponseBehavior == RevokedResponseBehavior.FetchNewValueNextTime)
return await GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Revoked));
// The caching settings specify we should attempt to fetch a fresh response. If failed, return currently cached value.
else if (settings.RevokedResponseBehavior == RevokedResponseBehavior.TryFetchNewValueNextTimeOrUseOld)
return await GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Revoked, cached));
// In case RevokedResponseBehavior=TryFetchNewValueInBackgroundNextTime or the enum value is a new option we don't know
// how to handle yet, we initiate a background refresh and return the stale response.
else {
_ = GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Revoked));
return await MarkHitAndReturnValue(cached.Value); // Might throw stored exception
}
// If refreshes are disabled it's because manual revokes are being performed, meaning the current response is up-to-date.
// Same for UseRefreshesWhenDisconnectedFromCacheRevokesBus, which we currently don't support, and assume everything is okay.
else if ( settings.RefreshMode == RefreshMode.DoNotUseRefreshes
|| settings.RefreshMode == RefreshMode.UseRefreshesWhenDisconnectedFromCacheRevokesBus) //TODO: after DisconnectedFromCacheRevokesBus feature is done, fix this if (to be only when connected)
return await MarkHitAndReturnValue(cached.Value); // Might throw stored exception
// Refreshes are enabled and the refresh time passed
else if (DateTime.UtcNow >= cached.NextRefreshTime)
// Try calling the service to obtain a fresh response. In case of failure return the old response.
if (settings.RefreshBehavior == RefreshBehavior.TryFetchNewValueOrUseOld)
return await GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Refresh, cached));
// Return the current old response, and trigger a background refresh to obtain a new value.
// TODO: In Microdot v4, we'd like to change the default to try and fetch a new value and wait for it (TryFetchNewValueOrUseOld)
else {
_ = GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.Refresh, cached));
return await MarkHitAndReturnValue(cached.Value); // Might throw stored exception
}
// All ok, return cached value
else return await MarkHitAndReturnValue(cached.Value); // Might throw stored exception
// No cached response. Call service.
else return await GroupRequestsIfNeeded(settings, key, metricsKeys, () =>
TryFetchNewValue(key, serviceMethod, settings, metricsKeys, CallReason.New));
}
// This method looks up whether there's a request in progress for the given key. If there is, it returns that ongoing request's task.
// Otherwise, it triggers a new request by calling the supplied send(), tracks it in RequestsInProgress, and returns that ongoing request task.
// Once send() is done, it removes it from the list of RequestsInProgress.
private async Task<object> GroupRequestsIfNeeded(IMethodCachingSettings settings, string key, string[] metricsKeys, Func<Task<object>> send)
{
if (settings.RequestGroupingBehavior == RequestGroupingBehavior.Disabled) {
Misses.Mark(metricsKeys);
return await send();
}
else {
JoinedTeam.Mark(metricsKeys);
return await RequestsInProgress.GetOrAdd(key, _ => new Lazy<Task<object>>(async () =>
{
Misses.Mark(metricsKeys);
try { return await send(); }
finally { RequestsInProgress.TryRemove(key, out var _); }
})).Value;
}
}
// This method has one of 5 possible outcomes:
//
// 1. We got a response from the service (null, not null or an exception) and the caching settings dictate that we should cache it:
// We cache it with the default RefreshTime. This extends the ExpirationTime as well.
//
// 2. The caching settings dictate that the response shouldn't be cached, and should be ignored, and currentValue != null :
// We return the currentValue and set its next refresh time to be now + FailedRefreshDelay so we don't "attack" the target service
//
// 3. The caching settings dictate that the response should not be cached, and should be ignored, and currentValue == null :
// We return the response anyway, since we don't have a previously-good value
//
// 4. The caching settings dictate that the response shouldn't be cached, nor ignored and removed from cache:
// We return the response and remove the previously-cached response from the cache
//
// 5. The caching settings dictate that the response shouldn't be cached, nor ignored and remain in cache:
// We return the response
private async Task<object> TryFetchNewValue(string cacheKey, Func<Task<object>> serviceMethod,
IMethodCachingSettings settings, string[] metricsKeys, CallReason callReason, AsyncCacheItem currentValue = null)
{
// We use the RecentRevokesCache to keep track of recent revoke messages that arrived, to detect if the response we're about
// to receive was revoked while in transit. It will track revoke messages as long as the task is not completed.
var requestSendTime = DateTime.UtcNow;
var tcs = new TaskCompletionSource<bool>();
RecentRevokesCache.RegisterOutgoingRequest(tcs.Task, requestSendTime);
// We capture the response from the service here, including if it was an exception
var (response, responseKind) = await CallService(serviceMethod, metricsKeys);
string outcome = null;
// Outcome #1: Cache the response
if (settings.ResponseKindsToCache.HasFlag(responseKind))
{
outcome = "cached";
CacheResponse(cacheKey, requestSendTime, response, settings);
}
else if (settings.ResponseKindsToIgnore.HasFlag(responseKind))
// Outcome #2: Leave old response cached and return it, and set its refresh time to the (short) FailedRefreshDelay
if (currentValue != null)
{
outcome = "ignored_cachedValueExist";
currentValue.NextRefreshTime = DateTime.UtcNow + settings.FailedRefreshDelay.Value;
response = currentValue.Value;
}
// Outcome #3: We don't have currentValue, so we cant ignore response and we return it
else
outcome = "ignored_cachedValueDoesNotExist";
else //Dont cache and dont ignore (i.e. return it)
{
outcome = "notCachedNotIgnored";
// Outcome #4: Do not cache response and return it; remove previously-cached value (if exist)
if (settings.NotIgnoredResponseBehavior == NotIgnoredResponseBehavior.RemoveCachedResponse)
{
if (MemoryCache.Remove(cacheKey) != null)
outcome = "notCachedNotIgnored_cachedValueRemoved";
}
// Outcome #5: Do not cache response and return it; leave old response cached
// If old response is not null, set its refresh time to the (short) FailedRefreshDelay
else if (currentValue != null)
currentValue.NextRefreshTime = DateTime.UtcNow + settings.FailedRefreshDelay.Value;
}
Log.Debug(x => x("Service call", unencryptedTags: new { cacheKey, callReason, responseKind, outcome }));
tcs.SetResult(true); // RecentRevokesCache can stop tracking revoke keys
return await response; // Might throw stored exception
}
private async Task<(Task<object> response, ResponseKinds responseKind)> CallService(Func<Task<object>> serviceMethod, string[] metricsKeys)
{
Task<object> response;
ResponseKinds responseKind;
try
{
AwaitingResult.Increment(metricsKeys);
// Call the service
response = Task.FromResult(await serviceMethod());
// Determine the kind of response. We consider it null also in case we got a non-null Revocable<> with null inner Value
var isNullResponse = response.Result == null
|| ( response.Result.GetType().IsGenericType
&& response.Result.GetType().GetGenericTypeDefinition() == typeof(Revocable<>)
&& response.Result.GetType().GetProperty("Value").GetValue(response.Result) == null);
responseKind = isNullResponse ? ResponseKinds.NullResponse : ResponseKinds.NonNullResponse;
}
catch (Exception e)
{
if (!(e is RequestException))
Failed.Mark(metricsKeys);
// Determine the kind of exception
responseKind = e is RequestException ? ResponseKinds.RequestException
: e is EnvironmentException ? ResponseKinds.EnvironmentException
: e is TimeoutException || e is TaskCanceledException ? ResponseKinds.TimeoutException
: ResponseKinds.OtherExceptions;
response = Task.FromException<object>(e);
var observed = response.Exception; //dont remove this line as it prevents UnobservedTaskException to be thrown
}
finally
{
AwaitingResult.Decrement(metricsKeys);
}
return (response, responseKind);
}
private void CacheResponse(string cacheKey, DateTime requestSendTime, Task<object> responseTask, IMethodCachingSettings settings)
{
var cacheItem = new AsyncCacheItem
{
NextRefreshTime = DateTime.UtcNow + settings.RefreshTime.Value,
Value = responseTask,
};
// Register each revoke key in the response with the reverse index, if the response is not an exception and is a Revocable<>.
// Starting from now, the IsRevoked property in cacheItem might be set to true by another thread in OnRevoked().
var revokeKeys = ExtarctRevokeKeys(responseTask);
if (revokeKeys.Any())
lock (RevokeKeyToCacheItemsIndex)
foreach (var revokeKey in revokeKeys)
RevokeKeyToCacheItemsIndex.GetOrAdd(revokeKey, _ => new HashSet<AsyncCacheItem>()).Add(cacheItem);
// Check if we got a revoke message from one of the revoke keys in the response while the request was in progress.
// Do this AFTER the above, so there's no point in time that we don't monitor cache revokes
var recentlyRevokedKey = revokeKeys.FirstOrDefault(rk => RecentRevokesCache.TryGetRecentlyRevokedTime(rk, requestSendTime) != null);
if (recentlyRevokedKey != null)
{
Items.Meter("RevokeRaceCondition", Unit.Items).Mark();
Log.Warn(x => x("Got revoke during request, marking as stale", unencryptedTags: new
{
revokeKey = recentlyRevokedKey,
requestSendTime,
cacheKey,
revokeTime = RecentRevokesCache.TryGetRecentlyRevokedTime(recentlyRevokedKey, requestSendTime)
}));
cacheItem.IsRevoked = true;
}
// Set the MemoryCache policy based on our caching settings. If the response has no revoke keys, no need to receive a callback
// event when it's removed from the cache since we don't need to remove it from the reverse index.
var cacheItemPolicy = new CacheItemPolicy {};
if (settings.ExpirationBehavior == ExpirationBehavior.ExtendExpirationWhenReadFromCache)
cacheItemPolicy.SlidingExpiration = settings.ExpirationTime.Value;
else
cacheItemPolicy.AbsoluteExpiration = DateTime.UtcNow + settings.ExpirationTime.Value;
if (revokeKeys.Any())
cacheItemPolicy.RemovedCallback += ItemRemovedCallback;
// Store the response in the main cache. Note that this will trigger a removal of a currently-cached value, if any,
// i.e. call ItemRemovedCallback() with Reason=Removed.
MemoryCache.Set(new CacheItem(cacheKey, cacheItem), cacheItemPolicy);
}
/// <summary>
/// For revocable items, move over all revoke ids in cache index and remove them.
/// </summary>
private void ItemRemovedCallback(CacheEntryRemovedArguments arguments)
{
Items.Meter(arguments.RemovedReason.ToString(), Unit.Items).Mark();
var cacheItem = (AsyncCacheItem)arguments.CacheItem.Value;
var revokeKeys = ExtarctRevokeKeys(cacheItem.Value);
//Can lock as revokeKeys > 0
lock (RevokeKeyToCacheItemsIndex)
foreach (var revokeKey in revokeKeys)
if ( !RevokeKeyToCacheItemsIndex.TryGetValue(revokeKey, out var hash)
|| !hash.Remove(cacheItem)
|| (hash.Count == 0 && !RevokeKeyToCacheItemsIndex.TryRemove(revokeKey, out _)))
throw new ProgrammaticException("Invalid state");
}
private Task OnRevoke(string revokeKey)
{
if (revokeKey == null)
throw new ArgumentNullException();
RecentRevokesCache.RegisterRevokeKey(revokeKey, DateTime.UtcNow);
var revokeApplied = false;
if (RevokeKeyToCacheItemsIndex.TryGetValue(revokeKey, out var _))
lock (RevokeKeyToCacheItemsIndex)
if (RevokeKeyToCacheItemsIndex.TryGetValue(revokeKey, out var hash))
{
foreach (var item in hash)
item.IsRevoked = true;
revokeApplied = true;
}
if (revokeApplied)
{
Revokes.Meter("Succeeded", Unit.Events).Mark();
Log.Debug(x => x("Revoke applied", unencryptedTags: new { revokeKey }));
}
else
Revokes.Meter("Discarded", Unit.Events).Mark();
return Task.CompletedTask;
}
private IEnumerable<string> ExtarctRevokeKeys(Task<object> responseTask) => (!responseTask.IsFaulted && !responseTask.IsCanceled ? (responseTask.Result as IRevocable)?.RevokeKeys : null) ?? Enumerable.Empty<string>();
public void Clear()
{
var oldMemoryCache = MemoryCache;
MemoryCache = new MemoryCache(nameof(AsyncCache) + Interlocked.Increment(ref _clearCount), new NameValueCollection { { "PollingInterval", "00:00:01" } });
if (oldMemoryCache != null)
{
// Disposing of MemoryCache can be a CPU intensive task and should therefore not block the current thread.
Task.Run(() => oldMemoryCache.Dispose());
}
}
public void UpdateCacheSize(long size, MemoryCache cache)
{
if (cache != MemoryCache)
return;
LastCacheSizeBytes = size;
}
public void ReleaseCache(MemoryCache cache) { }
public object GetService(Type serviceType)
{
return serviceType == typeof(IMemoryCacheManager) ? this : null;
}
public void Dispose()
{
MemoryCache?.Dispose();
RevokeDisposable?.Dispose();
}
}
public enum CallReason
{
New,
Refresh,
Suppress,
Revoked
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright 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.
*/
namespace Facebook.Unity.Mobile.IOS
{
using System;
using System.Runtime.InteropServices;
internal class IOSWrapper : IIOSWrapper
{
public void Init(
string appId,
bool frictionlessRequests,
string urlSuffix,
string unityUserAgentSuffix)
{
IOSWrapper.IOSInit(
appId,
frictionlessRequests,
urlSuffix,
unityUserAgentSuffix);
}
public void LogInWithReadPermissions(
int requestId,
string scope)
{
IOSWrapper.IOSLogInWithReadPermissions(
requestId,
scope);
}
public void LogInWithPublishPermissions(
int requestId,
string scope)
{
IOSWrapper.IOSLogInWithPublishPermissions(
requestId,
scope);
}
public void LogOut()
{
IOSWrapper.IOSLogOut();
}
public void SetShareDialogMode(int mode)
{
IOSWrapper.IOSSetShareDialogMode(mode);
}
public void ShareLink(
int requestId,
string contentURL,
string contentTitle,
string contentDescription,
string photoURL)
{
IOSWrapper.IOSShareLink(
requestId,
contentURL,
contentTitle,
contentDescription,
photoURL);
}
public void FeedShare(
int requestId,
string toId,
string link,
string linkName,
string linkCaption,
string linkDescription,
string picture,
string mediaSource)
{
IOSWrapper.IOSFeedShare(
requestId,
toId,
link,
linkName,
linkCaption,
linkDescription,
picture,
mediaSource);
}
public void AppRequest(
int requestId,
string message,
string actionType,
string objectId,
string[] to = null,
int toLength = 0,
string filters = "",
string[] excludeIds = null,
int excludeIdsLength = 0,
bool hasMaxRecipients = false,
int maxRecipients = 0,
string data = "",
string title = "")
{
IOSWrapper.IOSAppRequest(
requestId,
message,
actionType,
objectId,
to,
toLength,
filters,
excludeIds,
excludeIdsLength,
hasMaxRecipients,
maxRecipients,
data,
title);
}
public void AppInvite(
int requestId,
string appLinkUrl,
string previewImageUrl)
{
IOSWrapper.IOSAppInvite(
requestId,
appLinkUrl,
previewImageUrl);
}
public void CreateGameGroup(
int requestId,
string name,
string description,
string privacy)
{
IOSWrapper.IOSCreateGameGroup(
requestId,
name,
description,
privacy);
}
public void JoinGameGroup(int requestId, string groupId)
{
IOSWrapper.IOSJoinGameGroup(requestId, groupId);
}
public void FBSettingsActivateApp(string appId)
{
IOSWrapper.IOSFBSettingsActivateApp(appId);
}
public void LogAppEvent(
string logEvent,
double valueToSum,
int numParams,
string[] paramKeys,
string[] paramVals)
{
IOSWrapper.IOSFBAppEventsLogEvent(
logEvent,
valueToSum,
numParams,
paramKeys,
paramVals);
}
public void LogPurchaseAppEvent(
double logPurchase,
string currency,
int numParams,
string[] paramKeys,
string[] paramVals)
{
IOSWrapper.IOSFBAppEventsLogPurchase(
logPurchase,
currency,
numParams,
paramKeys,
paramVals);
}
public void FBAppEventsSetLimitEventUsage(bool limitEventUsage)
{
IOSWrapper.IOSFBAppEventsSetLimitEventUsage(limitEventUsage);
}
public void GetAppLink(int requestId)
{
IOSWrapper.IOSGetAppLink(requestId);
}
public string FBSdkVersion()
{
return IOSWrapper.IOSFBSdkVersion();
}
public void FetchDeferredAppLink(int requestId)
{
IOSWrapper.IOSFetchDeferredAppLink(requestId);
}
public void RefreshCurrentAccessToken(int requestId)
{
IOSWrapper.IOSRefreshCurrentAccessToken(requestId);
}
#if UNITY_IOS
[DllImport ("__Internal")]
private static extern void IOSInit(
string appId,
bool frictionlessRequests,
string urlSuffix,
string unityUserAgentSuffix);
[DllImport ("__Internal")]
private static extern void IOSLogInWithReadPermissions(
int requestId,
string scope);
[DllImport ("__Internal")]
private static extern void IOSLogInWithPublishPermissions(
int requestId,
string scope);
[DllImport ("__Internal")]
private static extern void IOSLogOut();
[DllImport ("__Internal")]
private static extern void IOSSetShareDialogMode(int mode);
[DllImport ("__Internal")]
private static extern void IOSShareLink(
int requestId,
string contentURL,
string contentTitle,
string contentDescription,
string photoURL);
[DllImport ("__Internal")]
public static extern void IOSFeedShare(
int requestId,
string toId,
string link,
string linkName,
string linkCaption,
string linkDescription,
string picture,
string mediaSource);
[DllImport ("__Internal")]
private static extern void IOSAppRequest(
int requestId,
string message,
string actionType,
string objectId,
string[] to = null,
int toLength = 0,
string filters = "",
string[] excludeIds = null,
int excludeIdsLength = 0,
bool hasMaxRecipients = false,
int maxRecipients = 0,
string data = "",
string title = "");
[DllImport ("__Internal")]
private static extern void IOSAppInvite(
int requestId,
string appLinkUrl,
string previewImageUrl);
[DllImport ("__Internal")]
private static extern void IOSCreateGameGroup(
int requestId,
string name,
string description,
string privacy);
[DllImport ("__Internal")]
private static extern void IOSJoinGameGroup(int requestId, string groupId);
[DllImport ("__Internal")]
private static extern void IOSFBSettingsActivateApp(string appId);
[DllImport ("__Internal")]
private static extern void IOSFBAppEventsLogEvent(
string logEvent,
double valueToSum,
int numParams,
string[] paramKeys,
string[] paramVals);
[DllImport ("__Internal")]
private static extern void IOSFBAppEventsLogPurchase(
double logPurchase,
string currency,
int numParams,
string[] paramKeys,
string[] paramVals);
[DllImport ("__Internal")]
private static extern void IOSFBAppEventsSetLimitEventUsage(bool limitEventUsage);
[DllImport ("__Internal")]
private static extern void IOSGetAppLink(int requestID);
[DllImport ("__Internal")]
private static extern string IOSFBSdkVersion();
[DllImport ("__Internal")]
private static extern void IOSFetchDeferredAppLink(int requestID);
[DllImport ("__Internal")]
private static extern void IOSRefreshCurrentAccessToken(int requestID);
#else
private static void IOSInit(
string appId,
bool frictionlessRequests,
string urlSuffix,
string unityUserAgentSuffix)
{
}
private static void IOSLogInWithReadPermissions(
int requestId,
string scope)
{
}
private static void IOSLogInWithPublishPermissions(
int requestId,
string scope)
{
}
private static void IOSLogOut()
{
}
private static void IOSSetShareDialogMode(int mode)
{
}
private static void IOSShareLink(
int requestId,
string contentURL,
string contentTitle,
string contentDescription,
string photoURL)
{
}
private static void IOSFeedShare(
int requestId,
string toId,
string link,
string linkName,
string linkCaption,
string linkDescription,
string picture,
string mediaSource)
{
}
private static void IOSAppRequest(
int requestId,
string message,
string actionType,
string objectId,
string[] to = null,
int toLength = 0,
string filters = "",
string[] excludeIds = null,
int excludeIdsLength = 0,
bool hasMaxRecipients = false,
int maxRecipients = 0,
string data = "",
string title = "")
{
}
private static void IOSAppInvite(
int requestId,
string appLinkUrl,
string previewImageUrl)
{
}
private static void IOSCreateGameGroup(
int requestId,
string name,
string description,
string privacy)
{
}
private static void IOSJoinGameGroup(int requestId, string groupId)
{
}
private static void IOSFBSettingsActivateApp(string appId)
{
}
private static void IOSFBAppEventsLogEvent(
string logEvent,
double valueToSum,
int numParams,
string[] paramKeys,
string[] paramVals)
{
}
private static void IOSFBAppEventsLogPurchase(
double logPurchase,
string currency,
int numParams,
string[] paramKeys,
string[] paramVals)
{
}
private static void IOSFBAppEventsSetLimitEventUsage(bool limitEventUsage)
{
}
private static void IOSGetAppLink(int requestId)
{
}
private static string IOSFBSdkVersion()
{
return "NONE";
}
private static void IOSFetchDeferredAppLink(int requestId)
{
}
private static void IOSRefreshCurrentAccessToken(int requestId)
{
}
#endif
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.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:
//
// * 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 Ayende Rahien 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.Data;
using Xunit;
using Rhino.Mocks;
using Rhino.Mocks.Constraints;
using Rhino.Mocks.Exceptions;
using Rhino.Mocks.Impl;
using Rhino.Mocks.Tests.Callbacks;
using System.Collections.Generic;
namespace Rhino.Mocks.Tests
{
// Interface to create mocks for
public interface ITestInterface
{
event EventHandler<EventArgs> AnEvent;
void RefOut(string str, out int i, string str2, ref int j, string str3);
void VoidList(List<string> list);
void VoidObject (object obj);
}
public class ArgConstraintTests
{
private IDemo demoMock;
ITestInterface testMock;
private MockRepository mocks;
private delegate string StringDelegateWithParams(int a, string b);
public ArgConstraintTests()
{
mocks = new MockRepository();
demoMock = this.mocks.StrictMock<IDemo>();
testMock = mocks.StrictMock<ITestInterface>();
}
[Fact]
public void ThreeArgs_Pass()
{
demoMock.VoidThreeArgs(
Arg<int>.Is.Anything,
Arg.Text.Contains("eine"),
Arg<float>.Is.LessThan(2.5f));
mocks.ReplayAll();
demoMock.VoidThreeArgs(3, "Steinegger", 2.4f);
mocks.VerifyAll();
}
[Fact]
public void ThreeArgs_Fail()
{
demoMock.VoidThreeArgs(
Arg<int>.Is.Anything,
Arg.Text.Contains("eine"),
Arg<float>.Is.LessThan(2.5f));
mocks.ReplayAll();
Assert.Throws<ExpectationViolationException>(() => demoMock.VoidThreeArgs(2, "Steinegger", 2.6f));
}
[Fact]
public void Matches()
{
Expect.Call(delegate{
demoMock.VoidStringArg(Arg<string>.Matches(Is.Equal("hallo") || Text.EndsWith("b")));})
.Repeat.Times(3);
mocks.ReplayAll();
demoMock.VoidStringArg("hallo");
demoMock.VoidStringArg("ab");
demoMock.VoidStringArg("bb");
mocks.VerifyAll();
}
[Fact]
public void ConstraintsThatWerentCallCauseVerifyFailure()
{
this.demoMock.VoidStringArg(Arg.Text.Contains("World"));
this.mocks.Replay(this.demoMock);
Assert.Throws<ExpectationViolationException>("IDemo.VoidStringArg(contains \"World\"); Expected #1, Actual #0.",
() => this.mocks.Verify(this.demoMock));
}
[Fact]
public void RefAndOutArgs()
{
testMock.RefOut(
Arg<string>.Is.Anything,
out Arg<int>.Out(3).Dummy,
Arg<string>.Is.Equal("Steinegger"),
ref Arg<int>.Ref(Is.Equal(2), 7).Dummy,
Arg<string>.Is.NotNull
);
mocks.ReplayAll();
int iout = 0;
int iref = 2;
testMock.RefOut("hallo", out iout, "Steinegger", ref iref, "notnull");
Assert.Equal(3, iout);
Assert.Equal(7, iref);
mocks.VerifyAll();
}
[Fact]
public void Event()
{
ITestInterface eventMock = mocks.StrictMock<ITestInterface>();
eventMock.AnEvent += Arg<EventHandler<EventArgs>>.Is.Anything;
mocks.ReplayAll();
eventMock.AnEvent += handler;
mocks.VerifyAll();
}
[Fact]
public void ListTest()
{
ITestInterface testMock = mocks.StrictMock<ITestInterface>();
testMock.VoidList(Arg<List<string>>.List.Count(Is.GreaterThan(3)));
testMock.VoidList(Arg<List<string>>.List.IsIn("hello"));
mocks.ReplayAll();
testMock.VoidList(new List<string>(new string[] { "1", "2", "4", "5" }));
Assert.Throws<ExpectationViolationException>(
"ITestInterface.VoidList(System.Collections.Generic.List`1[System.String]); Expected #0, Actual #1.",
() => testMock.VoidList(new List<string>(new string[] { "1", "3" })));
}
[Fact]
public void ConstraintWithTooFewArguments_ThrowsException()
{
Assert.Throws<InvalidOperationException>(
"When using Arg<T>, all arguments must be defined using Arg<T>.Is, Arg<T>.Text, Arg<T>.List, Arg<T>.Ref or Arg<T>.Out. 3 arguments expected, 2 have been defined.",
() => demoMock.VoidThreeArgs(
Arg<int>.Is.Equal(4),
Arg.Text.Contains("World"),
3.14f));
}
[Fact]
public void ConstraintToManyArgs_ThrowsException()
{
Arg<int>.Is.Equal(4);
Assert.Throws<InvalidOperationException>(
"Use Arg<T> ONLY within a mock method call while recording. 3 arguments expected, 4 have been defined.",
() =>
demoMock.VoidThreeArgs(
Arg<int>.Is.Equal(4),
Arg.Text.Contains("World"),
Arg<float>.Is.Equal(3.14f)));
}
[Fact]
public void MockRepositoryClearsArgData()
{
Arg<int>.Is.Equal(4);
Arg<int>.Is.Equal(4);
// create new Mockrepositor yto see if the Arg data has been cleared
mocks = new MockRepository();
demoMock = this.mocks.StrictMock<IDemo>();
demoMock.VoidThreeArgs(
Arg<int>.Is.Equal(4),
Arg.Text.Contains("World"),
Arg<float>.Is.Equal(3.14f));
}
[Fact]
public void TooFewOutArgs()
{
int iout = 2;
Assert.Throws<InvalidOperationException>(
"When using Arg<T>, all arguments must be defined using Arg<T>.Is, Arg<T>.Text, Arg<T>.List, Arg<T>.Ref or Arg<T>.Out. 5 arguments expected, 4 have been defined.",
() => testMock.RefOut(
Arg<string>.Is.Anything,
out iout,
Arg.Text.Contains("Steinegger"),
ref Arg<int>.Ref(Is.Equal(2), 7).Dummy,
Arg<string>.Is.NotNull
));
}
[Fact]
public void RefInsteadOfOutArg()
{
Assert.Throws<InvalidOperationException>(
"Argument 1 must be defined as: out Arg<T>.Out(returnvalue).Dummy",
() => testMock.RefOut(
Arg<string>.Is.Anything,
out Arg<int>.Ref(Is.Equal(2), 7).Dummy,
Arg.Text.Contains("Steinegger"),
ref Arg<int>.Ref(Is.Equal(2), 7).Dummy,
Arg<string>.Is.NotNull
));
}
[Fact]
public void OutInsteadOfRefArg()
{
Assert.Throws<InvalidOperationException>(
"Argument 3 must be defined as: ref Arg<T>.Ref(constraint, returnvalue).Dummy",
() => testMock.RefOut(
Arg<string>.Is.Anything,
out Arg<int>.Out(7).Dummy,
Arg.Text.Contains("Steinegger"),
ref Arg<int>.Out(7).Dummy,
Arg<string>.Is.NotNull
));
}
[Fact]
public void OutInsteadOfInArg()
{
Assert.Throws<InvalidOperationException>(
"Argument 0 must be defined using: Arg<T>.Is, Arg<T>.Text or Arg<T>.List",
() => testMock.VoidObject(Arg<object>.Out(null)));
}
[Fact]
public void Is_EqualsThrowsException()
{
Assert.Throws<InvalidOperationException>(
"Don't use Equals() to define constraints, use Equal() instead",
() => Arg<object>.Is.Equals(null));
}
[Fact]
public void List_EqualsThrowsException()
{
Assert.Throws<InvalidOperationException>(
"Don't use Equals() to define constraints, use Equal() instead",
() => Arg<object>.List.Equals(null));
}
[Fact]
public void Text_EqualsThrowsException()
{
Assert.Throws<InvalidOperationException>(
"Don't use Equals() to define constraints, use Equal() instead",
() => Arg.Text.Equals(null));
}
/// <summary>
/// Adapted from MockingDelegatesTests.MockStringDelegateWithParams
/// </summary>
[Fact]
public void MockStringDelegateWithParams()
{
StringDelegateWithParams d = (StringDelegateWithParams)mocks.StrictMock(typeof(StringDelegateWithParams));
Expect.On(d).Call(
d(
Arg<int>.Is.Equal(1),
Arg<string>.Is.Equal("111")))
.Return("abc");
Expect.On(d).Call(
d(
Arg<int>.Is.Equal(2),
Arg<string>.Is.Equal("222")))
.Return("def");
mocks.Replay(d);
Assert.Equal("abc", d(1, "111"));
Assert.Equal("def", d(2, "222"));
try
{
d(3, "333");
Assert.False(true, "Expected an expectation violation to occur.");
}
catch (ExpectationViolationException)
{
// Expected.
}
}
private void handler(object o, EventArgs e)
{
}
[Fact]
public void Mock_object_using_ExpectMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior()
{
// Arrange
var mock = MockRepository.GenerateMock<IDemo>();
mock.Expect(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output");
// Act
var firstCallResult = mock.StringArgString("input");
var secondCallResult = mock.StringArgString("input");
// Assert
Assert.Equal("output", firstCallResult);
Assert.Equal(firstCallResult, secondCallResult);
}
[Fact]
public void Stub_object_using_ExpectMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior()
{
// Arrange
var mock = MockRepository.GenerateStub<IDemo>();
mock.Expect(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output");
// Act
var firstCallResult = mock.StringArgString("input");
var secondCallResult = mock.StringArgString("input");
// Assert
Assert.Equal("output", firstCallResult);
Assert.Equal(firstCallResult, secondCallResult);
}
[Fact]
public void Stub_object_using_StubMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior()
{
// Arrange
var stub = MockRepository.GenerateStub<IDemo>();
stub.Stub(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output");
// Act
var firstCallResult = stub.StringArgString("input");
var secondCallResult = stub.StringArgString("input");
// Assert
Assert.Equal("output", firstCallResult);
Assert.Equal(firstCallResult, secondCallResult);
}
[Fact]
public void Mock_object_using_StubMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior()
{
// Arrange
var mock = MockRepository.GenerateMock<IDemo>();
mock.Stub(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output");
// Act
var firstCallResult = mock.StringArgString("input");
var secondCallResult = mock.StringArgString("input");
// Assert
Assert.Equal("output", firstCallResult);
Assert.Equal(firstCallResult, secondCallResult);
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsEqual()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.Equal(1))).Return("test"); // 1 is inferred as Int32 (not Int64)
// Assert
Assert.Equal(null, stub.GetUser(0));
Assert.Equal("test", stub.GetUser(1));
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsNotEqual()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.NotEqual(1))).Return("test"); // 1 is inferred as Int32 (not Int64)
var actual = stub.GetUser(0);
// Assert
Assert.Equal("test", actual);
Assert.Equal(null, stub.GetUser(1));
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsGreaterThan()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.GreaterThan(1))).Return("test"); // 1 is inferred as Int32 (not Int64)
// Assert
Assert.Equal(null, stub.GetUser(0));
Assert.Equal(null, stub.GetUser(1));
Assert.Equal("test", stub.GetUser(2));
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsGreaterThanOrEqual()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.GreaterThanOrEqual(2))).Return("test"); // 1 is inferred as Int32 (not Int64)
// Assert
Assert.Equal(null, stub.GetUser(1));
Assert.Equal("test", stub.GetUser(2));
Assert.Equal("test", stub.GetUser(3));
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsLessThan()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.LessThan(2))).Return("test"); // 1 is inferred as Int32 (not Int64)
// Assert
Assert.Equal("test", stub.GetUser(1));
Assert.Equal(null, stub.GetUser(2));
Assert.Equal(null, stub.GetUser(3));
}
[Fact]
public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsLessThanOrEqual()
{
// Arrange
var stub = MockRepository.GenerateStub<ITestService>();
stub.Stub(x => x.GetUser(Arg<long>.Is.LessThanOrEqual(2))).Return("test"); // 1 is inferred as Int32 (not Int64)
// Assert
Assert.Equal("test", stub.GetUser(1));
Assert.Equal("test", stub.GetUser(2));
Assert.Equal(null, stub.GetUser(3));
}
public interface ITestService
{
string GetUser(long id);
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.IO;
using System.Runtime.InteropServices;
using SharpDX.Direct3D11;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A Texture 1D front end to <see cref="SharpDX.Direct3D11.Texture1D"/>.
/// </summary>
public class Texture1D : Texture1DBase
{
internal Texture1D(GraphicsDevice device, Texture1DDescription description1D, params DataBox[] dataBox) : base(device, description1D, dataBox)
{
}
internal Texture1D(GraphicsDevice device, Direct3D11.Texture1D texture) : base(device, texture)
{
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public override Texture Clone()
{
return new Texture1D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new texture from a <see cref="Texture1DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Texture1DDescription description)
{
return new Texture1D(device, description);
}
/// <summary>
/// Creates a new texture from a <see cref="Direct3D11.Texture1D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture1D"/>.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Direct3D11.Texture1D texture)
{
return new Texture1D(device, texture);
}
/// <summary>
/// Creates a new <see cref="Texture1D"/> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, int width, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return New(device, width, false, format, flags, arraySize, usage);
}
/// <summary>
/// Creates a new <see cref="Texture1D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
/// <returns>
/// A new instance of <see cref="Texture1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, int width, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture1D(device, NewDescription(width, format, flags, mipCount, arraySize, usage));
}
/// <summary>
/// Creates a new <see cref="Texture1D" /> with a single level of mipmap.
/// </summary>
/// <typeparam name="T">Type of the initial data to upload to the texture</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">Texture data. Size of must be equal to sizeof(Format) * width </param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>A new instance of <see cref="Texture1D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_Texture1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
/// <remarks>
/// The first dimension of mipMapTextures describes the number of array (Texture1D Array), second dimension is the mipmap, the third is the texture data for a particular mipmap.
/// </remarks>
public unsafe static Texture1D New<T>(GraphicsDevice device, int width, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct
{
return new Texture1D(device, NewDescription(width, format, flags, 1, 1, usage), GetDataBox(format, width, 1, 1, textureData, (IntPtr)Interop.Fixed(textureData)));
}
/// <summary>
/// Creates a new <see cref="Texture1D" /> directly from an <see cref="Image"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="image">An image in CPU memory.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture1D" /> class.</returns>
/// <msdn-id>ff476521</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static Texture1D New(GraphicsDevice device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
if (image == null) throw new ArgumentNullException("image");
if (image.Description.Dimension != TextureDimension.Texture1D)
throw new ArgumentException("Invalid image. Must be 1D", "image");
return new Texture1D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox());
}
/// <summary>
/// Loads a 1D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 1D</exception>
/// <returns>A texture</returns>
public static new Texture1D Load(GraphicsDevice device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
var texture = Texture.Load(device, stream, flags, usage);
if (!(texture is Texture1D))
throw new ArgumentException(string.Format("Texture is not type of [Texture1D] but [{0}]", texture.GetType().Name));
return (Texture1D)texture;
}
/// <summary>
/// Loads a 1D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 1D</exception>
/// <returns>A texture</returns>
public static new Texture1D Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
}
}
| |
// 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.Collections.Immutable;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
internal class StackTraceSymbols : IDisposable
{
private readonly Dictionary<IntPtr, MetadataReaderProvider> _metadataCache;
/// <summary>
/// Create an instance of this class.
/// </summary>
public StackTraceSymbols()
{
_metadataCache = new Dictionary<IntPtr, MetadataReaderProvider>();
}
/// <summary>
/// Clean up any cached providers.
/// </summary>
void IDisposable.Dispose()
{
foreach (MetadataReaderProvider provider in _metadataCache.Values)
{
provider.Dispose();
}
_metadataCache.Clear();
}
/// <summary>
/// Returns the source file and line number information for the method.
/// </summary>
/// <param name="assemblyPath">file path of the assembly or null</param>
/// <param name="loadedPeAddress">loaded PE image address or zero</param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">il offset of the stack frame</param>
/// <param name="sourceFile">source file return</param>
/// <param name="sourceLine">line number return</param>
/// <param name="sourceColumn">column return</param>
internal void GetSourceLineInfo(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn)
{
sourceFile = null;
sourceLine = 0;
sourceColumn = 0;
MetadataReader reader = TryGetReader(assemblyPath, loadedPeAddress, loadedPeSize, inMemoryPdbAddress, inMemoryPdbSize);
if (reader != null)
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind == HandleKind.MethodDefinition)
{
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
MethodDebugInformation methodInfo = reader.GetMethodDebugInformation(methodDebugHandle);
if (!methodInfo.SequencePointsBlob.IsNil)
{
SequencePointCollection sequencePoints = methodInfo.GetSequencePoints();
SequencePoint? bestPointSoFar = null;
foreach (SequencePoint point in sequencePoints)
{
if (point.Offset > ilOffset)
break;
if (point.StartLine != SequencePoint.HiddenLine)
bestPointSoFar = point;
}
if (bestPointSoFar.HasValue)
{
sourceLine = bestPointSoFar.Value.StartLine;
sourceColumn = bestPointSoFar.Value.StartColumn;
sourceFile = reader.GetString(reader.GetDocument(bestPointSoFar.Value.Document).Name);
}
}
}
}
}
/// <summary>
/// Returns the portable PDB reader for the assembly path
/// </summary>
/// <param name="assemblyPath">
/// File path of the assembly or null if the module is dynamic (generated by Reflection.Emit).
/// </param>
/// <param name="loadedPeAddress">
/// Loaded PE image address or zero if the module is dynamic (generated by Reflection.Emit).
/// Dynamic modules have their PDBs (if any) generated to an in-memory stream
/// (pointed to by <paramref name="inMemoryPdbAddress"/> and <paramref name="inMemoryPdbSize"/>).
/// </param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="reader">returns the reader</param>
/// <returns>reader</returns>
/// <remarks>
/// Assumes that neither PE image nor PDB loaded into memory can be unloaded or moved around.
/// </remarks>
private unsafe MetadataReader TryGetReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
if ((loadedPeAddress == IntPtr.Zero || assemblyPath == null) && inMemoryPdbAddress == IntPtr.Zero)
{
// Dynamic or in-memory module without symbols (they would be in-memory if they were available).
return null;
}
IntPtr cacheKey = (inMemoryPdbAddress != IntPtr.Zero) ? inMemoryPdbAddress : loadedPeAddress;
MetadataReaderProvider provider;
if (_metadataCache.TryGetValue(cacheKey, out provider))
{
return provider.GetMetadataReader();
}
provider = (inMemoryPdbAddress != IntPtr.Zero) ?
TryOpenReaderForInMemoryPdb(inMemoryPdbAddress, inMemoryPdbSize) :
TryOpenReaderFromAssemblyFile(assemblyPath, loadedPeAddress, loadedPeSize);
if (provider == null)
{
return null;
}
_metadataCache.Add(cacheKey, provider);
// The reader has already been open, so this doesn't throw:
return provider.GetMetadataReader();
}
private unsafe static MetadataReaderProvider TryOpenReaderForInMemoryPdb(IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
Debug.Assert(inMemoryPdbAddress != IntPtr.Zero);
// quick check to avoid throwing exceptions below in common cases:
const uint ManagedMetadataSignature = 0x424A5342;
if (inMemoryPdbSize < sizeof(uint) || *(uint*)inMemoryPdbAddress != ManagedMetadataSignature)
{
// not a Portable PDB
return null;
}
var provider = MetadataReaderProvider.FromMetadataImage((byte*)inMemoryPdbAddress, inMemoryPdbSize);
try
{
// may throw if the metadata is invalid
provider.GetMetadataReader();
return provider;
}
catch (BadImageFormatException)
{
provider.Dispose();
return null;
}
}
private unsafe static PEReader TryGetPEReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize)
{
// TODO: https://github.com/dotnet/corefx/issues/11406
//if (loadedPeAddress != IntPtr.Zero && loadedPeSize > 0)
//{
// return new PEReader((byte*)loadedPeAddress, loadedPeSize, isLoadedImage: true);
//}
Stream peStream = TryOpenFile(assemblyPath);
if (peStream != null)
{
return new PEReader(peStream);
}
return null;
}
private static MetadataReaderProvider TryOpenReaderFromAssemblyFile(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize)
{
using (var peReader = TryGetPEReader(assemblyPath, loadedPeAddress, loadedPeSize))
{
if (peReader == null)
{
return null;
}
string pdbPath;
MetadataReaderProvider provider;
if (peReader.TryOpenAssociatedPortablePdb(assemblyPath, TryOpenFile, out provider, out pdbPath))
{
// TODO:
// Consider caching the provider in a global cache (accross stack traces) if the PDB is embedded (pdbPath == null),
// as decompressing embedded PDB takes some time.
return provider;
}
}
return null;
}
private static Stream TryOpenFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
return File.OpenRead(path);
}
catch
{
return null;
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BuildIt.CognitiveServices
{
public partial class AcademicSearchAPI : Microsoft.Rest.ServiceClient<AcademicSearchAPI>, IAcademicSearchAPI
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the AcademicSearchAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AcademicSearchAPI(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AcademicSearchAPI class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public AcademicSearchAPI(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AcademicSearchAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AcademicSearchAPI(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AcademicSearchAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AcademicSearchAPI(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("http://westus.api.cognitive.microsoft.com/academic/v1.0");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// The interpret REST API takes an end user query string (i.e., a query
/// entered by a user of your application) and returns formatted
/// interpretations of user intent based on the Academic Graph data and the
/// Academic Grammar.
/// To provide an interactive experience, you can call this method repeatedly
/// after each character entered by the user. In that case, you should set
/// the complete parameter to 1 to enable auto-complete suggestions. If your
/// application does not want auto-completion, you should set the complete
/// parameter to 0.
/// </summary>
/// <param name='query'>
/// Query entered by user. If complete is set to 1, query will be interpreted
/// as a prefix for generating query auto-completion suggestions.
/// </param>
/// <param name='complete'>
/// 1 means that auto-completion suggestions are generated based on the
/// grammar and graph data.
/// </param>
/// <param name='count'>
/// Maximum number of interpretations to return.
/// </param>
/// <param name='offset'>
/// Index of the first interpretation to return. For example,
/// count=2&offset=0 returns interpretations 0 and 1.
/// count=2&offset=2 returns interpretations 2 and 3.
/// </param>
/// <param name='timeout'>
/// Timeout in milliseconds. Only interpretations found before the timeout has
/// elapsed are returned.
/// </param>
/// <param name='model'>
/// Name of the model that you wish to query. Currently, the value defaults to
/// "latest".
/// . Possible values include: 'beta-2015', 'latest'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> InterpretWithHttpMessagesAsync(string query, bool? complete = false, double? count = 10, double? offset = default(double?), double? timeout = default(double?), string model = "latest", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (query == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "query");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complete", complete);
tracingParameters.Add("count", count);
tracingParameters.Add("offset", offset);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("query", query);
tracingParameters.Add("model", model);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Interpret", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "interpret").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (complete != null)
{
_queryParameters.Add(string.Format("complete={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complete, this.SerializationSettings).Trim('"'))));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, this.SerializationSettings).Trim('"'))));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(offset, this.SerializationSettings).Trim('"'))));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.SerializationSettings).Trim('"'))));
}
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(query)));
}
if (model != null)
{
_queryParameters.Add(string.Format("model={0}", System.Uri.EscapeDataString(model)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 500 && (int)_statusCode != 404 && (int)_statusCode != 403)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The evaluate REST API is used to return a set of academic entities based
/// on a query expression.
/// </summary>
/// <param name='expr'>
/// A query expression that specifies which entities should be returned.
/// </param>
/// <param name='model'>
/// Name of the model that you wish to query. Currently, the value defaults to
/// "latest".
/// . Possible values include: 'beta-2015', 'latest'
/// </param>
/// <param name='count'>
/// Number of results to return.
/// </param>
/// <param name='offset'>
/// Index of the first result to return.
/// </param>
/// <param name='orderby'>
/// Name of an attribute that is used for sorting the entities. Optionally,
/// ascending/descending can be specified. The format is: name:asc or
/// name:desc.
/// </param>
/// <param name='attributes'>
/// A comma delimited list that specifies the attribute values that are
/// included in the response. Attribute names are case-sensitive. Possible
/// values include: 'Id'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> EvaluateWithHttpMessagesAsync(string expr, string model = "latest", double? count = 10, double? offset = 0, string orderby = default(string), string attributes = "Id", string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (expr == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "expr");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("expr", expr);
tracingParameters.Add("model", model);
tracingParameters.Add("count", count);
tracingParameters.Add("offset", offset);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("attributes", attributes);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Evaluate", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "evaluate").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (expr != null)
{
_queryParameters.Add(string.Format("expr={0}", System.Uri.EscapeDataString(expr)));
}
if (model != null)
{
_queryParameters.Add(string.Format("model={0}", System.Uri.EscapeDataString(model)));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, this.SerializationSettings).Trim('"'))));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(offset, this.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("orderby={0}", System.Uri.EscapeDataString(orderby)));
}
if (attributes != null)
{
_queryParameters.Add(string.Format("attributes={0}", System.Uri.EscapeDataString(attributes)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 500 && (int)_statusCode != 404 && (int)_statusCode != 403)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The calchistogram REST API is used to calculate the distribution of
/// attribute values for a set of paper entities.
/// </summary>
/// <param name='expr'>
/// A query expression that specifies the entities over which to calculate
/// histograms.
/// </param>
/// <param name='model'>
/// Name of the model that you wish to query. Currently, the value defaults to
/// "latest".
/// . Possible values include: 'beta-2015', 'latest'
/// </param>
/// <param name='attributes'>
/// A comma delimited list that specifies the attribute values that are
/// included in the response. Attribute names are case-sensitive.
/// </param>
/// <param name='count'>
/// Number of results to return.
/// </param>
/// <param name='offset'>
/// Index of the first result to return.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CalcHistogramWithHttpMessagesAsync(string expr, string model = "latest", string attributes = default(string), double? count = 10, double? offset = 0, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (expr == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "expr");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("expr", expr);
tracingParameters.Add("model", model);
tracingParameters.Add("attributes", attributes);
tracingParameters.Add("count", count);
tracingParameters.Add("offset", offset);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CalcHistogram", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "calchistogram").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (expr != null)
{
_queryParameters.Add(string.Format("expr={0}", System.Uri.EscapeDataString(expr)));
}
if (model != null)
{
_queryParameters.Add(string.Format("model={0}", System.Uri.EscapeDataString(model)));
}
if (attributes != null)
{
_queryParameters.Add(string.Format("attributes={0}", System.Uri.EscapeDataString(attributes)));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, this.SerializationSettings).Trim('"'))));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(offset, this.SerializationSettings).Trim('"'))));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 500 && (int)_statusCode != 404 && (int)_statusCode != 403)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Welcome to the Microsoft Cognitive Service Academic Search API, a web
/// service for retrieving paths and subgraphs from Microsoft Academic Graph.
/// The graph query interface powered by Graph Engine allows us to not only
/// query entities that meet certain criteria (e.g. find a paper with a given
/// title), but also perform pattern matching via graph exploration (e.g.
/// detect co-authorship).
/// </summary>
/// <param name='mode'>
/// Request type of query. Should be "json" or "lambda". Possible values
/// include: 'json', 'lambda'
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> GraphSearchWithHttpMessagesAsync(string mode, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (mode == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "mode");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("mode", mode);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GraphSearch", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "graph/search").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (mode != null)
{
_queryParameters.Add(string.Format("mode={0}", System.Uri.EscapeDataString(mode)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 413 && (int)_statusCode != 500)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The similarity REST API is used to calculate a floating point value based
/// on 2 text inputs.
/// </summary>
/// <param name='s1'>
/// String to be compared, input length is bounded by the limitation of the
/// length of URL. When the strings are too long to be processed using GET,
/// use POST instead.
/// </param>
/// <param name='s2'>
/// String to be compared, input length is bounded by the limitation of the
/// length of URL. When the strings are too long to be processed using GET,
/// use POST instead.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> SimilarityWithHttpMessagesAsync(string s1, string s2, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (s1 == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "s1");
}
if (s2 == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "s2");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("s1", s1);
tracingParameters.Add("s2", s2);
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Similarity", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "similarity").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (s1 != null)
{
_queryParameters.Add(string.Format("s1={0}", System.Uri.EscapeDataString(s1)));
}
if (s2 != null)
{
_queryParameters.Add(string.Format("s2={0}", System.Uri.EscapeDataString(s2)));
}
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 500 && (int)_statusCode != 408)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PostsimilarityWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionKey", subscriptionKey);
tracingParameters.Add("ocpApimSubscriptionKey", ocpApimSubscriptionKey);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Postsimilarity", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "similarity").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (subscriptionKey != null)
{
_queryParameters.Add(string.Format("subscription-key={0}", System.Uri.EscapeDataString(subscriptionKey)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ocpApimSubscriptionKey != null)
{
if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key"))
{
_httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key");
}
_httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);
}
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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 500 && (int)_statusCode != 408)
{
var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Tests.Bson;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
[TestFixture]
public class JPathExecuteTests : TestFixtureBase
{
[Test]
public void SelectTokenAfterEmptyContainer()
{
string json = @"{
'cont': [],
'test': 'no one will find me'
}";
JObject o = JObject.Parse(json);
IList<JToken> results = o.SelectTokens("$..test").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual("no one will find me", (string)results[0]);
}
[Test]
public void EvaluatePropertyWithRequired()
{
string json = "{\"bookId\":\"1000\"}";
JObject o = JObject.Parse(json);
string bookId = (string)o.SelectToken("bookId", true);
Assert.AreEqual("1000", bookId);
}
[Test]
public void EvaluateEmptyPropertyIndexer()
{
JObject o = new JObject(
new JProperty("", 1));
JToken t = o.SelectToken("['']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateEmptyString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("");
Assert.AreEqual(o, t);
t = o.SelectToken("['']");
Assert.AreEqual(null, t);
}
[Test]
public void EvaluateEmptyStringWithMatchingEmptyProperty()
{
JObject o = new JObject(
new JProperty(" ", 1));
JToken t = o.SelectToken("[' ']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWhitespaceString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken(" ");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("$");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarTypeString()
{
JObject o = new JObject(
new JProperty("$values", new JArray(1, 2, 3)));
JToken t = o.SelectToken("$values[1]");
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWildcardProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1),
new JProperty("Blah2", 2));
IList<JToken> t = o.SelectTokens("$.*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void QuoteName()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("['Blah']");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject.");
}
[Test]
public void EvaluateWildcardIndexOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
}
[Test]
public void EvaluateSliceOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
public void EvaluateMultipleResultsError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens.");
}
[Test]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray.");
}
[Test]
public void EvaluateNoResultsWithMultipleArrayIndexes()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxerWithError()
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxer()
{
JConstructor c = new JConstructor("Blah");
Assert.IsNull(c.SelectToken("[1]"));
}
[Test]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluatePropertyWithoutError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JValue v = (JValue)o.SelectToken("Blah", true);
Assert.AreEqual(1, v.Value);
}
[Test]
public void EvaluateMissingPropertyIndexWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluateMultiPropertyIndexOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray.");
}
[Test]
public void EvaluateArraySliceWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results.");
a = new JArray();
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results.");
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
public void EvaluateArrayOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray.");
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateArraySlice()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
IList<JToken> t = null;
t = a.SelectTokens("[-3:]").ToList();
Assert.AreEqual(3, t.Count);
Assert.AreEqual(7, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(9, (int)t[2]);
t = a.SelectTokens("[-1:-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(9, (int)t[0]);
t = a.SelectTokens("[-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(8, (int)t[0]);
t = a.SelectTokens("[1:1]").ToList();
Assert.AreEqual(0, t.Count);
t = a.SelectTokens("[1:2]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(2, (int)t[0]);
t = a.SelectTokens("[::-1]").ToList();
Assert.AreEqual(9, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(7, (int)t[2]);
Assert.AreEqual(6, (int)t[3]);
Assert.AreEqual(5, (int)t[4]);
Assert.AreEqual(4, (int)t[5]);
Assert.AreEqual(3, (int)t[6]);
Assert.AreEqual(2, (int)t[7]);
Assert.AreEqual(1, (int)t[8]);
t = a.SelectTokens("[::-2]").ToList();
Assert.AreEqual(5, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(7, (int)t[1]);
Assert.AreEqual(5, (int)t[2]);
Assert.AreEqual(3, (int)t[3]);
Assert.AreEqual(1, (int)t[4]);
}
[Test]
public void EvaluateWildcardArray()
{
JArray a = new JArray(1, 2, 3, 4);
List<JToken> t = a.SelectTokens("[*]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.AreEqual(3, (int)t[2]);
Assert.AreEqual(4, (int)t[3]);
}
[Test]
public void EvaluateArrayMultipleIndexes()
{
JArray a = new JArray(1, 2, 3, 4);
IEnumerable<JToken> t = a.SelectTokens("[1,2,0]");
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Count());
Assert.AreEqual(2, (int)t.ElementAt(0));
Assert.AreEqual(3, (int)t.ElementAt(1));
Assert.AreEqual(1, (int)t.ElementAt(2));
}
[Test]
public void EvaluateScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void EvaluateWildcardScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(5, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
}
[Test]
public void EvaluateScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3]));
}
[Test]
public void EvaluateWildcardScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(9, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
Assert.IsTrue(JToken.DeepEquals(o3, t[5]));
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7]));
Assert.AreEqual(3, (int)t[8]);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new[] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void ExistsQuery()
{
JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0]));
}
[Test]
public void EqualsQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", "ho")),
new JObject(new JProperty("hi", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0]));
}
[Test]
public void NotEqualsQuery()
{
JArray a = new JArray(
new JArray(new JObject(new JProperty("hi", "ho"))),
new JArray(new JObject(new JProperty("hi", "ha"))));
IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0]));
}
[Test]
public void NoPathQuery()
{
JArray a = new JArray(1, 2, 3);
IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(2, (int)t[0]);
Assert.AreEqual(3, (int)t[1]);
}
[Test]
public void MultipleQueries()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
// json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/
// first query resolves array to ints
// int has no children to query
IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(0, t.Count);
}
[Test]
public void GreaterQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || ASPNETCORE50 || PORTABLE40 || NET35 || NET20)
[Test]
public void GreaterQueryBigInteger()
{
JArray a = new JArray(
new JObject(new JProperty("hi", new BigInteger(1))),
new JObject(new JProperty("hi", new BigInteger(2))),
new JObject(new JProperty("hi", new BigInteger(3))));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#endif
[Test]
public void GreaterOrEqualQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 2.0)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3]));
}
[Test]
public void NestedQuery()
{
JArray a = new JArray(
new JObject(
new JProperty("name", "Bad Boys"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "Independence Day"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "The Rock"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Nick Cage")))))
);
IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual("Bad Boys", (string)t[0]);
Assert.AreEqual("Independence Day", (string)t[1]);
}
[Test]
public void PathWithConstructor()
{
JArray a = JArray.Parse(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]");
JValue v = (JValue)a.SelectToken("[1].Property2[1][0]");
Assert.AreEqual(1L, v.Value);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer
{
public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture>
{
public TypeInferrerTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
protected override async Task TestWorkerAsync(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition)
{
var root = await document.GetSyntaxRootAsync();
var node = FindExpressionSyntaxFromSpan(root, textSpan);
var typeInference = document.GetLanguageService<ITypeInferenceService>();
var inferredType = useNodeStartPosition
? typeInference.InferType(await document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None), node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None)
: typeInference.InferType(await document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None), node, objectAsDefault: true, cancellationToken: CancellationToken.None);
var typeSyntax = inferredType.GenerateTypeSyntax();
Assert.Equal(expectedType, typeSyntax.ToString());
}
private async Task TestInClassAsync(string text, string expectedType)
{
text = @"class C
{
$
}".Replace("$", text);
await TestAsync(text, expectedType);
}
private async Task TestInMethodAsync(string text, string expectedType, bool testNode = true, bool testPosition = true)
{
text = @"class C
{
void M()
{
$
}
}".Replace("$", text);
await TestAsync(text, expectedType, testNode: testNode, testPosition: testPosition);
}
private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan)
{
var token = root.FindToken(textSpan.Start);
var currentNode = token.Parent;
while (currentNode != null)
{
ExpressionSyntax result = currentNode as ExpressionSyntax;
if (result != null && result.Span == textSpan)
{
return result;
}
currentNode = currentNode.Parent;
}
return null;
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional1()
{
// We do not support position inference here as we're before the ? and we only look
// backwards to infer a type here.
await TestInMethodAsync("var q = [|Foo()|] ? 1 : 2;", "System.Boolean",
testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional2()
{
await TestInMethodAsync("var q = a ? [|Foo()|] : 2;", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConditional3()
{
await TestInMethodAsync(@"var q = a ? """" : [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestVariableDeclarator1()
{
await TestInMethodAsync("int q = [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestVariableDeclarator2()
{
await TestInMethodAsync("var q = [|Foo()|];", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce1()
{
await TestInMethodAsync("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce2()
{
await TestInMethodAsync(@"bool? b;
var q = b ?? [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce3()
{
await TestInMethodAsync(@"string s;
var q = s ?? [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCoalesce4()
{
await TestInMethodAsync("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryExpression1()
{
await TestInMethodAsync(@"string s;
var q = s + [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryExpression2()
{
await TestInMethodAsync(@"var s;
var q = s || [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryOperator1()
{
await TestInMethodAsync(@"var q = x << [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBinaryOperator2()
{
await TestInMethodAsync(@"var q = x >> [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestAssignmentOperator3()
{
await TestInMethodAsync(@"var q <<= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestAssignmentOperator4()
{
await TestInMethodAsync(@"var q >>= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestOverloadedConditionalLogicalOperatorsInferBool()
{
await TestAsync(@"using System;
class C
{
public static C operator &(C c, C d) { return null; }
public static bool operator true(C c) { return true; }
public static bool operator false(C c) { return false; }
static void Main(string[] args)
{
var c = new C() && [|Foo()|];
}
}", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestConditionalLogicalOrOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a || [|7|];
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestConditionalLogicalAndOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a && [|7|];
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | b | c || d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a | b | [|c|] || d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] | y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] | y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & b & c && d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a & b & [|c|] && d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] & y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] & y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ true;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ b ^ c && d;
}
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a ^ b ^ [|c|] && d;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(Program p)
{
return p;
}
}";
await TestAsync(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(bool p)
{
return p;
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] ^ y) != 0) {}
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^ y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] |= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalOrEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] |= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] &= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalAndEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] &= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^= y) {}
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617633")]
public async Task TestLogicalXorEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] ^= y;
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn1()
{
await TestInClassAsync(@"int M() { return [|Foo()|]; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn2()
{
await TestInMethodAsync("return [|Foo()|];", "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturn3()
{
await TestInClassAsync(@"int Property { get { return [|Foo()|]; } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
public async Task TestYieldReturn()
{
var markup =
@"using System.Collections.Generic;
class Program
{
IEnumerable<int> M()
{
yield return [|abc|]
}
}";
await TestAsync(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestReturnInLambda()
{
await TestInMethodAsync("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestLambda()
{
await TestInMethodAsync("System.Func<string, int> f = s => [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThrow()
{
await TestInMethodAsync("throw [|Foo()|];", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCatch()
{
await TestInMethodAsync("try { } catch ([|Foo|] ex) { }", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIf()
{
await TestInMethodAsync(@"if ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestWhile()
{
await TestInMethodAsync(@"while ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestDo()
{
await TestInMethodAsync(@"do { } while ([|Foo()|])", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor1()
{
await TestInMethodAsync(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor2()
{
await TestInMethodAsync(@"for (string i = [|Foo()|]; ; ) { }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestFor3()
{
await TestInMethodAsync(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing1()
{
await TestInMethodAsync(@"using ([|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing2()
{
await TestInMethodAsync(@"using (int i = [|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestUsing3()
{
await TestInMethodAsync(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestForEach()
{
await TestInMethodAsync(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression1()
{
await TestInMethodAsync(@"var q = +[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression2()
{
await TestInMethodAsync(@"var q = -[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression3()
{
await TestInMethodAsync(@"var q = ~[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression4()
{
await TestInMethodAsync(@"var q = ![|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPrefixExpression5()
{
await TestInMethodAsync(@"var q = System.DayOfWeek.Monday & ~[|Foo()|];", "global::System.DayOfWeek");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayRankSpecifier()
{
await TestInMethodAsync(@"var q = new string[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch1()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch2()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { default: }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestSwitch3()
{
await TestInMethodAsync(@"switch ([|Foo()|]) { case ""a"": }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall1()
{
await TestInMethodAsync(@"Bar([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall2()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall3()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall4()
{
await TestInClassAsync(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestMethodCall5()
{
await TestInClassAsync(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall1()
{
await TestInMethodAsync(@"new C([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall2()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall3()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C() { }", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall4()
{
await TestInClassAsync(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestConstructorCall5()
{
await TestInClassAsync(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThisConstructorInitializer1()
{
await TestAsync(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestThisConstructorInitializer2()
{
await TestAsync(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String");
}
[WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestBaseConstructorInitializer()
{
await TestAsync(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexAccess1()
{
await TestInMethodAsync(@"string[] i; i[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall1()
{
await TestInMethodAsync(@"this[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall2()
{
// Update this when binding of indexers is working.
await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall3()
{
// Update this when binding of indexers is working.
await TestInClassAsync(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestIndexerCall5()
{
await TestInClassAsync(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreationSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { 1, [|2|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
int Foo() { return 2; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation2()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInImplicitArrayCreation3()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
}";
await TestAsync(text, "System.Object");
}
[Fact]
public async Task TestArrayInitializerInEqualsValueClauseSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { 1, [|2|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
public async Task TestArrayInitializerInEqualsValueClause()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
new List<int>() { [|Foo()|] };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer2()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { [|Foo()|], """" } };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCollectionInitializer3()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { 0, [|Foo()|] } };
}
}";
await TestAsync(text, "System.String");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod1()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { [|a|] };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.Int32", testPosition: false);
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod2()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { ""test"", [|b|] } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.Boolean");
}
[Fact]
[WorkItem(529480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529480")]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestCustomCollectionInitializerAddMethod3()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { [|s|], true } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference1()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference1_Position()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference2()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
await TestAsync(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference2_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
await TestAsync(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference3()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[]", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference3_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
await TestAsync(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestArrayInference4()
{
var text =
@"
using System;
class A
{
void Foo()
{
Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] };
}
}";
await TestAsync(text, "global::System.Func<System.Int32,System.Int32>");
}
[WorkItem(538993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538993")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestInsideLambda2()
{
var text =
@"using System;
class C
{
void M()
{
Func<int,int> f = i => [|here|]
}
}";
await TestAsync(text, "System.Int32");
}
[WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestPointer1()
{
var text =
@"class C
{
void M(int* i)
{
var q = i[[|Foo()|]];
}
}";
await TestAsync(text, "System.Int32");
}
[WorkItem(539813, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539813")]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestDynamic1()
{
var text =
@"class C
{
void M(dynamic i)
{
var q = i[[|Foo()|]];
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public async Task TestChecked1()
{
var text =
@"class C
{
void M()
{
string q = checked([|Foo()|]);
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
int x = await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTaskOfTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
Task<int> x = await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553584")]
public async Task TestAwaitTask()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
await [|Foo()|];
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")]
public async Task TestLockStatement()
{
var text =
@"class C
{
void M()
{
lock([|Foo()|])
{
}
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617622")]
public async Task TestAwaitExpressionInLockStatement()
{
var text =
@"class C
{
async void M()
{
lock(await [|Foo()|])
{
}
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Object>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827897")]
public async Task TestReturnFromAsyncTaskOfT()
{
var markup =
@"using System.Threading.Tasks;
class Program
{
async Task<int> M()
{
await Task.Delay(1);
return [|ab|]
}
}";
await TestAsync(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments1()
{
var markup =
@"[A([|dd|], ee, Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "global::System.DayOfWeek");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments2()
{
var markup =
@"[A(dd, [|ee|], Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "System.Double");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853840")]
public async Task TestAttributeArguments3()
{
var markup =
@"[A(dd, ee, Y = [|ff|])]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
await TestAsync(markup, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(757111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/757111")]
public async Task TestReturnStatementWithinDelegateWithinAMethodCall()
{
var text =
@"using System;
class Program
{
delegate string A(int i);
static void Main(string[] args)
{
B(delegate(int i) { return [|M()|]; });
}
private static void B(A a)
{
}
}";
await TestAsync(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause()
{
var text =
@"
try
{ }
catch (Exception) if ([|M()|])
}";
await TestInMethodAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause1()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|])
}";
await TestInMethodAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994388")]
public async Task TestCatchFilterClause2()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|].N)
}";
await TestInMethodAsync(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public async Task TestAwaitExpressionWithChainingMethod()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M()|].ConfigureAwait(false);
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public async Task TestAwaitExpressionWithChainingMethod2()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; });
}
}";
await TestAsync(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public async Task TestAwaitExpressionWithGenericMethod1()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await X([|Test()|]);
}
private async Task<T> X<T>(T t) { return t; }
}";
await TestAsync(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public async Task TestAwaitExpressionWithGenericMethod2()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await Task.Run(() => [|Test()|]);;
}
private async Task<T> X<T>(T t) { return t; }
}";
await TestAsync(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator1()
{
var text =
@"class C
{
void M()
{
object z = [|a|]?? null;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator2()
{
var text =
@"class C
{
void M()
{
object z = [|a|] ?? b ?? c;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public async Task TestNullCoalescingOperator3()
{
var text =
@"class C
{
void M()
{
object z = a ?? [|b|] ?? c;
}
}";
await TestAsync(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public async Task TestSelectLambda()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[||])
}
}";
await TestAsync(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public async Task TestSelectLambda2()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[|b|])
}
}";
await TestAsync(text, "System.String", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(1903, "https://github.com/dotnet/roslyn/issues/1903")]
public async Task TestSelectLambda3()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class A { }
class B { }
class C
{
IEnumerable<B> GetB(IEnumerable<A> a)
{
return a.Select(i => [|Foo(i)|]);
}
}";
await TestAsync(text, "global::B");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")]
public async Task TestReturnInAsyncLambda1()
{
var text =
@"using System;
using System.IO;
using System.Threading.Tasks;
public class C
{
public async void M()
{
Func<Task<int>> t2 = async () => { return [|a|]; };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")]
public async Task TestReturnInAsyncLambda2()
{
var text =
@"using System;
using System.IO;
using System.Threading.Tasks;
public class C
{
public async void M()
{
Func<Task<int>> t2 = async delegate () { return [|a|]; };
}
}";
await TestAsync(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")]
public async Task TestDefaultStatement1()
{
var text =
@"class C
{
static void Main(string[] args)
{
System.ConsoleModifiers c = default([||])
}
}";
await TestAsync(text, "global::System.ConsoleModifiers", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(6765, "https://github.com/dotnet/roslyn/issues/6765")]
public async Task TestDefaultStatement2()
{
var text =
@"class C
{
static void Foo(System.ConsoleModifiers arg)
{
Foo(default([||])
}
}";
await TestAsync(text, "global::System.ConsoleModifiers", testNode: false);
}
}
}
| |
using System;
using Server.Network;
using Server.Multis;
using Server.Items;
using Server.Targeting;
using Server.Misc;
using Server.Regions;
namespace Server.Spells.Druid
{
public class MushroomGatewaySpell : DruidicSpell
{
private static SpellInfo m_Info = new SpellInfo(
"Mushroom Gateway", "Vauk Sepa Ohm",
//SpellCircle.Seventh,
263,
9032,
Reagent.SpidersSilk,
Reagent.MandrakeRoot,
Reagent.SpringWater
);
public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 3 ); } }
public override SpellCircle Circle { get { return SpellCircle.Seventh; } }
public override double RequiredSkill{ get{ return 70.0; } }
public override int RequiredMana{ get{ return 40; } }
private RunebookEntry m_Entry;
public MushroomGatewaySpell( Mobile caster, Item scroll ) : this( caster, scroll, null )
{
}
public MushroomGatewaySpell( Mobile caster, Item scroll, RunebookEntry entry ) : base( caster, scroll, m_Info )
{
m_Entry = entry;
}
public override void OnCast()
{
if ( m_Entry == null )
Caster.Target = new InternalTarget( this );
else
Effect( m_Entry.Location, m_Entry.Map, true );
}
public override bool CheckCast()
{
if ( Caster.Criminal )
{
Caster.SendLocalizedMessage( 1005561, "", 0x22 ); // Thou'rt a criminal and cannot escape so easily.
return false;
}
else if ( SpellHelper.CheckCombat( Caster ) )
{
Caster.SendLocalizedMessage( 1005564, "", 0x22 ); // Wouldst thou flee during the heat of battle??
return false;
}
return SpellHelper.CheckTravel( Caster, TravelCheckType.GateFrom );
}
public void Effect( Point3D loc, Map map, bool checkMulti )
{
if ( map == null || (!Core.AOS && Caster.Map != map) )
{
Caster.SendLocalizedMessage( 1005570 ); // You can not gate to another facet.
}
else if ( !SpellHelper.CheckTravel( Caster, TravelCheckType.GateFrom ) )
{
}
else if ( !SpellHelper.CheckTravel( Caster, map, loc, TravelCheckType.GateTo ) )
{
}
else if ( Caster.Kills >= 5 && map != Map.Felucca )
{
Caster.SendLocalizedMessage( 1019004 ); // You are not allowed to travel there.
}
else if ( Caster.Criminal )
{
Caster.SendLocalizedMessage( 1005561, "", 0x22 ); // Thou'rt a criminal and cannot escape so easily.
}
else if ( SpellHelper.CheckCombat( Caster ) )
{
Caster.SendLocalizedMessage( 1005564, "", 0x22 ); // Wouldst thou flee during the heat of battle??
}
else if ( !map.CanSpawnMobile( loc.X, loc.Y, loc.Z ) )
{
Caster.SendLocalizedMessage( 501942 ); // That location is blocked.
}
else if ( (checkMulti && SpellHelper.CheckMulti( loc, map )) )
{
Caster.SendLocalizedMessage( 501942 ); // That location is blocked.
}
else if ( CheckSequence() )
{
Caster.SendMessage( "You open a mystical portal in a mushroom circle" ); // You open a magical gate to another location
Effects.PlaySound( Caster.Location, Caster.Map, 0x1 );
int mushx;
int mushy;
int mushz;
InternalItem firstGatea = new InternalItem( loc, map );
mushx=Caster.X;
mushy=Caster.Y;
mushz=Caster.Z;
firstGatea.ItemID=0xD10;
Point3D mushxyz = new Point3D(mushx,mushy,mushz);
firstGatea.MoveToWorld( mushxyz, Caster.Map );
InternalItem firstGateb = new InternalItem( loc, map );
mushx=Caster.X;
mushy=Caster.Y;
firstGateb.ItemID=0x373A;
mushz=Caster.Z+1;
Point3D mushxyza = new Point3D(mushx,mushy,mushz);
firstGateb.MoveToWorld( mushxyza, Caster.Map );
InternalItem firstGatec = new InternalItem( loc, map );
mushx=Caster.X-1;
firstGatec.ItemID=0xD11;
mushy=Caster.Y+1;
mushz=Caster.Z;
Point3D mushxyzb = new Point3D(mushx,mushy,mushz);
firstGatec.MoveToWorld( mushxyzb, Caster.Map );
InternalItem firstGated = new InternalItem( loc, map);
firstGated.ItemID=0xD0C;
mushx=Caster.X;
mushy=Caster.Y+2;
mushz=Caster.Z;
Point3D mushxyzc = new Point3D(mushx,mushy,mushz);
firstGated.MoveToWorld( mushxyzc, Caster.Map );
InternalItem firstGatee = new InternalItem( loc, map );
mushx=Caster.X+1;
firstGatee.ItemID=0xD0D;
mushy=Caster.Y+1;
mushz=Caster.Z;
Point3D mushxyzd = new Point3D(mushx,mushy,mushz);
firstGatee.MoveToWorld( mushxyzd, Caster.Map );
InternalItem firstGatef = new InternalItem( loc, map );
firstGatef.ItemID=0xD0E;
mushx=Caster.X+2;
mushy=Caster.Y;
mushz=Caster.Z;
Point3D mushxyze = new Point3D(mushx,mushy,mushz);
firstGatef.MoveToWorld( mushxyze, Caster.Map );
InternalItem firstGateg = new InternalItem( loc, map );
mushx=Caster.X+1;
firstGateg.ItemID=0xD0F;
mushy=Caster.Y-1;
mushz=Caster.Z;
Point3D mushxyzf = new Point3D(mushx,mushy,mushz);
firstGateg.MoveToWorld( mushxyzf, Caster.Map );
Effects.PlaySound( loc, map, 0x1 );
InternalItem secondGatea = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X;
mushy=loc.Y;
mushz=loc.Z;
secondGatea.ItemID=0xD10;
Point3D mushaxyz = new Point3D(mushx,mushy,mushz);
secondGatea.MoveToWorld( mushaxyz, map);
InternalItem secondGateb = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X;
mushy=loc.Y;
secondGateb.ItemID=0x373A;
mushz=loc.Z+1;
Point3D mushaxyza = new Point3D(mushx,mushy,mushz);
secondGateb.MoveToWorld( mushaxyza, map);
InternalItem secondGatec = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X-1;
secondGatec.ItemID=0xD11;
mushy=loc.Y+1;
mushz=loc.Z-1;
Point3D mushaxyzb = new Point3D(mushx,mushy,mushz);
secondGatec.MoveToWorld( mushaxyzb, map);
InternalItem secondGated = new InternalItem( Caster.Location, Caster.Map);
mushx=loc.X;
mushy=loc.Y+2;
secondGated.ItemID=0xD0C;
mushz=loc.Z;
Point3D mushaxyzc = new Point3D(mushx,mushy,mushz);
secondGated.MoveToWorld( mushaxyzc, map);
InternalItem secondGatee = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X+1;
mushy=loc.Y+1;
mushz=loc.Z;
secondGatee.ItemID=0xD0D;
Point3D mushaxyzd = new Point3D(mushx,mushy,mushz);
secondGatee.MoveToWorld( mushaxyzd, map);
InternalItem secondGatef = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X+2;
mushy=loc.Y;
mushz=loc.Z;
secondGatef.ItemID=0xD0E;
Point3D mushaxyze = new Point3D(mushx,mushy,mushz);
secondGatef.MoveToWorld( mushaxyze, map);
InternalItem secondGateg = new InternalItem( Caster.Location, Caster.Map );
mushx=loc.X+1;
secondGateg.ItemID=0xD0F;
mushy=loc.Y-1;
mushz=loc.Z;
Point3D mushaxyzf = new Point3D(mushx,mushy,mushz);
secondGateg.MoveToWorld( mushaxyzf, map);
}
FinishSequence();
}
[DispellableField]
private class InternalItem : Moongate
{
public override bool ShowFeluccaWarning{ get{ return Core.AOS; } }
public InternalItem( Point3D target, Map map ) : base( target, map )
{
Map = map;
if ( ShowFeluccaWarning && map == Map.Felucca )
ItemID = 0xDDA;
Dispellable = true;
InternalTimer t = new InternalTimer( this );
t.Start();
}
public InternalItem( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
Delete();
}
private class InternalTimer : Timer
{
private Item m_Item;
public InternalTimer( Item item ) : base( TimeSpan.FromSeconds( 30.0 ) )
{
m_Item = item;
}
protected override void OnTick()
{
m_Item.Delete();
}
}
}
private class InternalTarget : Target
{
private MushroomGatewaySpell m_Owner;
public InternalTarget( MushroomGatewaySpell owner ) : base( 12, false, TargetFlags.None )
{
m_Owner = owner;
owner.Caster.LocalOverheadMessage( MessageType.Regular, 0x3B2, 501029 ); // Select Marked item.
}
protected override void OnTarget( Mobile from, object o )
{
if ( o is RecallRune )
{
RecallRune rune = (RecallRune)o;
if ( rune.Marked )
m_Owner.Effect( rune.Target, rune.TargetMap, true );
else
from.SendLocalizedMessage( 501803 ); // That rune is not yet marked.
}
else if ( o is Runebook )
{
RunebookEntry e = ((Runebook)o).Default;
if ( e != null )
m_Owner.Effect( e.Location, e.Map, true );
else
from.SendLocalizedMessage( 502354 ); // Target is not marked.
}
/*else if ( o is Key && ((Key)o).KeyValue != 0 && ((Key)o).Link is BaseBoat )
{
BaseBoat boat = ((Key)o).Link as BaseBoat;
if ( !boat.Deleted && boat.CheckKey( ((Key)o).KeyValue ) )
m_Owner.Effect( boat.GetMarkedLocation(), boat.Map, false );
else
from.Send( new MessageLocalized( from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, 501030, from.Name, "" ) ); // I can not gate travel from that object.
}*/
else
{
from.Send( new MessageLocalized( from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, 501030, from.Name, "" ) ); // I can not gate travel from that object.
}
}
protected override void OnTargetFinish( Mobile from )
{
m_Owner.FinishSequence();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using MS.Internal.Xml.XPath;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Xml.Schema;
namespace System.Xml.XPath
{
// Provides a navigation interface API using XPath data model.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XPathNavigator : XPathItem, IXPathNavigable, IXmlNamespaceResolver
{
internal static readonly XPathNavigatorKeyComparer comparer = new XPathNavigatorKeyComparer();
//-----------------------------------------------
// Object
//-----------------------------------------------
public override string ToString()
{
return Value;
}
//-----------------------------------------------
// XPathItem
//-----------------------------------------------
public override sealed bool IsNode
{
get { return true; }
}
public virtual void SetValue(string value)
{
throw new NotSupportedException();
}
public override object TypedValue
{
get
{
return Value;
}
}
public virtual void SetTypedValue(object typedValue)
{
if (typedValue == null)
{
throw new ArgumentNullException("typedValue");
}
switch (NodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Attribute:
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
SetValue(XmlUntypedConverter.ToString(typedValue, this));
}
public override Type ValueType
{
get
{
return typeof(string);
}
}
public override bool ValueAsBoolean
{
get
{
return XmlUntypedConverter.ToBoolean(Value);
}
}
public override DateTime ValueAsDateTime
{
get
{
return XmlUntypedConverter.ToDateTime(Value);
}
}
public override double ValueAsDouble
{
get
{
return XmlUntypedConverter.ToDouble(Value);
}
}
public override int ValueAsInt
{
get
{
return XmlUntypedConverter.ToInt32(Value);
}
}
public override long ValueAsLong
{
get
{
return XmlUntypedConverter.ToInt64(Value);
}
}
public override object ValueAs(Type returnType, IXmlNamespaceResolver nsResolver)
{
if (nsResolver == null)
{
nsResolver = this;
}
return XmlUntypedConverter.ChangeType(Value, returnType, nsResolver);
}
//-----------------------------------------------
// IXPathNavigable
//-----------------------------------------------
public virtual XPathNavigator CreateNavigator()
{
return Clone();
}
//-----------------------------------------------
// IXmlNamespaceResolver
//-----------------------------------------------
public abstract XmlNameTable NameTable { get; }
public virtual string LookupNamespace(string prefix)
{
if (prefix == null)
return null;
if (NodeType != XPathNodeType.Element)
{
XPathNavigator navSave = Clone();
// If current item is not an element, then try parent
if (navSave.MoveToParent())
return navSave.LookupNamespace(prefix);
}
else if (MoveToNamespace(prefix))
{
string namespaceURI = Value;
MoveToParent();
return namespaceURI;
}
// Check for "", "xml", and "xmlns" prefixes
if (prefix.Length == 0)
return string.Empty;
else if (prefix == "xml")
return XmlConst.ReservedNsXml;
else if (prefix == "xmlns")
return XmlConst.ReservedNsXmlNs;
return null;
}
public virtual string LookupPrefix(string namespaceURI)
{
if (namespaceURI == null)
return null;
XPathNavigator navClone = Clone();
if (NodeType != XPathNodeType.Element)
{
// If current item is not an element, then try parent
if (navClone.MoveToParent())
return navClone.LookupPrefix(namespaceURI);
}
else
{
if (navClone.MoveToFirstNamespace(XPathNamespaceScope.All))
{
// Loop until a matching namespace is found
do
{
if (namespaceURI == navClone.Value)
return navClone.LocalName;
}
while (navClone.MoveToNextNamespace(XPathNamespaceScope.All));
}
}
// Check for default, "xml", and "xmlns" namespaces
if (namespaceURI == LookupNamespace(string.Empty))
return string.Empty;
else if (namespaceURI == XmlConst.ReservedNsXml)
return "xml";
else if (namespaceURI == XmlConst.ReservedNsXmlNs)
return "xmlns";
return null;
}
public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
XPathNodeType nt = NodeType;
if ((nt != XPathNodeType.Element && scope != XmlNamespaceScope.Local) || nt == XPathNodeType.Attribute || nt == XPathNodeType.Namespace)
{
XPathNavigator navSave = Clone();
// If current item is not an element, then try parent
if (navSave.MoveToParent())
return navSave.GetNamespacesInScope(scope);
}
Dictionary<string, string> dict = new Dictionary<string, string>();
// "xml" prefix always in scope
if (scope == XmlNamespaceScope.All)
dict["xml"] = XmlConst.ReservedNsXml;
// Now add all in-scope namespaces
if (MoveToFirstNamespace((XPathNamespaceScope)scope))
{
do
{
string prefix = LocalName;
string ns = Value;
// Exclude xmlns="" declarations unless scope = Local
if (prefix.Length != 0 || ns.Length != 0 || scope == XmlNamespaceScope.Local)
dict[prefix] = ns;
}
while (MoveToNextNamespace((XPathNamespaceScope)scope));
MoveToParent();
}
return dict;
}
//-----------------------------------------------
// XPathNavigator
//-----------------------------------------------
// Returns an object of type IKeyComparer. Using this the navigators can be hashed
// on the basis of actual position it represents rather than the clr reference of
// the navigator object.
public static IEqualityComparer NavigatorComparer
{
get { return comparer; }
}
public abstract XPathNavigator Clone();
public abstract XPathNodeType NodeType { get; }
public abstract string LocalName { get; }
public abstract string Name { get; }
public abstract string NamespaceURI { get; }
public abstract string Prefix { get; }
public abstract string BaseURI { get; }
public abstract bool IsEmptyElement { get; }
public virtual string XmlLang
{
get
{
XPathNavigator navClone = Clone();
do
{
if (navClone.MoveToAttribute("lang", XmlConst.ReservedNsXml))
return navClone.Value;
}
while (navClone.MoveToParent());
return string.Empty;
}
}
public virtual XmlReader ReadSubtree()
{
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
return CreateReader();
}
public virtual void WriteSubtree(XmlWriter writer)
{
if (null == writer)
throw new ArgumentNullException("writer");
writer.WriteNode(this, true);
}
public virtual object UnderlyingObject
{
get { return null; }
}
public virtual bool HasAttributes
{
get
{
if (!MoveToFirstAttribute())
return false;
MoveToParent();
return true;
}
}
public virtual string GetAttribute(string localName, string namespaceURI)
{
string value;
if (!MoveToAttribute(localName, namespaceURI))
return "";
value = Value;
MoveToParent();
return value;
}
public virtual bool MoveToAttribute(string localName, string namespaceURI)
{
if (MoveToFirstAttribute())
{
do
{
if (localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
while (MoveToNextAttribute());
MoveToParent();
}
return false;
}
public abstract bool MoveToFirstAttribute();
public abstract bool MoveToNextAttribute();
public virtual string GetNamespace(string name)
{
string value;
if (!MoveToNamespace(name))
{
if (name == "xml")
return XmlConst.ReservedNsXml;
if (name == "xmlns")
return XmlConst.ReservedNsXmlNs;
return string.Empty;
}
value = Value;
MoveToParent();
return value;
}
public virtual bool MoveToNamespace(string name)
{
if (MoveToFirstNamespace(XPathNamespaceScope.All))
{
do
{
if (name == LocalName)
return true;
}
while (MoveToNextNamespace(XPathNamespaceScope.All));
MoveToParent();
}
return false;
}
public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope);
public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope);
public bool MoveToFirstNamespace() { return MoveToFirstNamespace(XPathNamespaceScope.All); }
public bool MoveToNextNamespace() { return MoveToNextNamespace(XPathNamespaceScope.All); }
public abstract bool MoveToNext();
public abstract bool MoveToPrevious();
public virtual bool MoveToFirst()
{
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// MoveToFirst should only succeed for content-typed nodes
return false;
}
if (!MoveToParent())
return false;
return MoveToFirstChild();
}
public abstract bool MoveToFirstChild();
public abstract bool MoveToParent();
public virtual void MoveToRoot()
{
while (MoveToParent())
;
}
public abstract bool MoveTo(XPathNavigator other);
public abstract bool MoveToId(string id);
public virtual bool MoveToChild(string localName, string namespaceURI)
{
if (MoveToFirstChild())
{
do
{
if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
while (MoveToNext());
MoveToParent();
}
return false;
}
public virtual bool MoveToChild(XPathNodeType type)
{
if (MoveToFirstChild())
{
int mask = XPathNavigatorEx.GetContentKindMask(type);
do
{
if (((1 << (int)NodeType) & mask) != 0)
return true;
}
while (MoveToNext());
MoveToParent();
}
return false;
}
public virtual bool MoveToFollowing(string localName, string namespaceURI)
{
return MoveToFollowing(localName, namespaceURI, null);
}
public virtual bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end)
{
XPathNavigator navSave = Clone();
if (end != null)
{
switch (end.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Scan until we come to the next content-typed node
// after the attribute or namespace node
end = end.Clone();
end.MoveToNonDescendant();
break;
}
}
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (!MoveToParent())
{
return false;
}
break;
}
do
{
if (!MoveToFirstChild())
{
// Look for next sibling
while (true)
{
if (MoveToNext())
break;
if (!MoveToParent())
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
}
// Have we reached the end of the scan?
if (end != null && IsSamePosition(end))
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
while (NodeType != XPathNodeType.Element
|| localName != LocalName
|| namespaceURI != NamespaceURI);
return true;
}
public virtual bool MoveToFollowing(XPathNodeType type)
{
return MoveToFollowing(type, null);
}
public virtual bool MoveToFollowing(XPathNodeType type, XPathNavigator end)
{
XPathNavigator navSave = Clone();
int mask = XPathNavigatorEx.GetContentKindMask(type);
if (end != null)
{
switch (end.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Scan until we come to the next content-typed node
// after the attribute or namespace node
end = end.Clone();
end.MoveToNonDescendant();
break;
}
}
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (!MoveToParent())
{
return false;
}
break;
}
do
{
if (!MoveToFirstChild())
{
// Look for next sibling
while (true)
{
if (MoveToNext())
break;
if (!MoveToParent())
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
}
// Have we reached the end of the scan?
if (end != null && IsSamePosition(end))
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
while (((1 << (int)NodeType) & mask) == 0);
return true;
}
public virtual bool MoveToNext(string localName, string namespaceURI)
{
XPathNavigator navClone = Clone();
while (MoveToNext())
{
if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
MoveTo(navClone);
return false;
}
public virtual bool MoveToNext(XPathNodeType type)
{
XPathNavigator navClone = Clone();
int mask = XPathNavigatorEx.GetContentKindMask(type);
while (MoveToNext())
{
if (((1 << (int)NodeType) & mask) != 0)
return true;
}
MoveTo(navClone);
return false;
}
public virtual bool HasChildren
{
get
{
if (MoveToFirstChild())
{
MoveToParent();
return true;
}
return false;
}
}
public abstract bool IsSamePosition(XPathNavigator other);
public virtual bool IsDescendant(XPathNavigator nav)
{
if (nav != null)
{
nav = nav.Clone();
while (nav.MoveToParent())
if (nav.IsSamePosition(this))
return true;
}
return false;
}
public virtual XmlNodeOrder ComparePosition(XPathNavigator nav)
{
if (nav == null)
{
return XmlNodeOrder.Unknown;
}
if (IsSamePosition(nav))
return XmlNodeOrder.Same;
XPathNavigator n1 = this.Clone();
XPathNavigator n2 = nav.Clone();
int depth1 = GetDepth(n1.Clone());
int depth2 = GetDepth(n2.Clone());
if (depth1 > depth2)
{
while (depth1 > depth2)
{
n1.MoveToParent();
depth1--;
}
if (n1.IsSamePosition(n2))
return XmlNodeOrder.After;
}
if (depth2 > depth1)
{
while (depth2 > depth1)
{
n2.MoveToParent();
depth2--;
}
if (n1.IsSamePosition(n2))
return XmlNodeOrder.Before;
}
XPathNavigator parent1 = n1.Clone();
XPathNavigator parent2 = n2.Clone();
while (true)
{
if (!parent1.MoveToParent() || !parent2.MoveToParent())
return XmlNodeOrder.Unknown;
if (parent1.IsSamePosition(parent2))
{
if (n1.GetType().ToString() != "Microsoft.VisualStudio.Modeling.StoreNavigator")
{
Debug.Assert(CompareSiblings(n1.Clone(), n2.Clone()) != CompareSiblings(n2.Clone(), n1.Clone()), "IsSamePosition() on custom navigator returns incosistent results");
}
return CompareSiblings(n1, n2);
}
n1.MoveToParent();
n2.MoveToParent();
}
}
public virtual XPathExpression Compile(string xpath)
{
return XPathExpression.Compile(xpath);
}
public virtual XPathNavigator SelectSingleNode(string xpath)
{
return SelectSingleNode(XPathExpression.Compile(xpath));
}
public virtual XPathNavigator SelectSingleNode(string xpath, IXmlNamespaceResolver resolver)
{
return SelectSingleNode(XPathExpression.Compile(xpath, resolver));
}
public virtual XPathNavigator SelectSingleNode(XPathExpression expression)
{
XPathNodeIterator iter = this.Select(expression);
if (iter.MoveNext())
{
return iter.Current;
}
return null;
}
public virtual XPathNodeIterator Select(string xpath)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
return this.Select(XPathExpression.Compile(xpath));
}
public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver resolver)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
return this.Select(XPathExpression.Compile(xpath, resolver));
}
public virtual XPathNodeIterator Select(XPathExpression expr)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
XPathNodeIterator result = Evaluate(expr) as XPathNodeIterator;
if (result == null)
{
throw XPathException.Create(SR.Xp_NodeSetExpected);
}
return result;
}
public virtual object Evaluate(string xpath)
{
return Evaluate(XPathExpression.Compile(xpath), null);
}
public virtual object Evaluate(string xpath, IXmlNamespaceResolver resolver)
{
return this.Evaluate(XPathExpression.Compile(xpath, resolver));
}
public virtual object Evaluate(XPathExpression expr)
{
return Evaluate(expr, null);
}
public virtual object Evaluate(XPathExpression expr, XPathNodeIterator context)
{
CompiledXpathExpr cexpr = expr as CompiledXpathExpr;
if (cexpr == null)
{
throw XPathException.Create(SR.Xp_BadQueryObject);
}
Query query = Query.Clone(cexpr.QueryTree);
query.Reset();
if (context == null)
{
context = new XPathSingletonIterator(this.Clone(), /*moved:*/true);
}
object result = query.Evaluate(context);
if (result is XPathNodeIterator)
{
return new XPathSelectionIterator(context.Current, query);
}
return result;
}
public virtual bool Matches(XPathExpression expr)
{
CompiledXpathExpr cexpr = expr as CompiledXpathExpr;
if (cexpr == null)
throw XPathException.Create(SR.Xp_BadQueryObject);
// We should clone query because some Query.MatchNode() alter expression state and this may brake
// SelectionIterators that are runing using this Query
// Example of MatchNode() that alret the state is FilterQuery.MatchNode()
Query query = Query.Clone(cexpr.QueryTree);
try
{
return query.MatchNode(this) != null;
}
catch (XPathException)
{
throw XPathException.Create(SR.Xp_InvalidPattern, cexpr.Expression);
}
}
public virtual bool Matches(string xpath)
{
return Matches(CompileMatchPattern(xpath));
}
public virtual XPathNodeIterator SelectChildren(XPathNodeType type)
{
return new XPathChildIterator(this.Clone(), type);
}
public virtual XPathNodeIterator SelectChildren(string name, string namespaceURI)
{
return new XPathChildIterator(this.Clone(), name, namespaceURI);
}
public virtual XPathNodeIterator SelectAncestors(XPathNodeType type, bool matchSelf)
{
return new XPathAncestorIterator(this.Clone(), type, matchSelf);
}
public virtual XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf)
{
return new XPathAncestorIterator(this.Clone(), name, namespaceURI, matchSelf);
}
public virtual XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf)
{
return new XPathDescendantIterator(this.Clone(), type, matchSelf);
}
public virtual XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf)
{
return new XPathDescendantIterator(this.Clone(), name, namespaceURI, matchSelf);
}
public virtual bool CanEdit
{
get
{
return false;
}
}
public virtual XmlWriter PrependChild()
{
throw new NotSupportedException();
}
public virtual XmlWriter AppendChild()
{
throw new NotSupportedException();
}
public virtual XmlWriter InsertAfter()
{
throw new NotSupportedException();
}
public virtual XmlWriter InsertBefore()
{
throw new NotSupportedException();
}
public virtual XmlWriter CreateAttributes()
{
throw new NotSupportedException();
}
public virtual XmlWriter ReplaceRange(XPathNavigator lastSiblingToReplace)
{
throw new NotSupportedException();
}
public virtual void ReplaceSelf(string newNode)
{
XmlReader reader = CreateContextReader(newNode, false);
ReplaceSelf(reader);
}
public virtual void ReplaceSelf(XmlReader newNode)
{
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
XPathNodeType type = NodeType;
if (type == XPathNodeType.Root
|| type == XPathNodeType.Attribute
|| type == XPathNodeType.Namespace)
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlWriter writer = ReplaceRange(this);
BuildSubtree(newNode, writer);
writer.Dispose();
}
public virtual void ReplaceSelf(XPathNavigator newNode)
{
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
XmlReader reader = newNode.CreateReader();
ReplaceSelf(reader);
}
// Returns the markup representing the current node and all of its children.
public virtual string OuterXml
{
get
{
StringWriter stringWriter;
XmlWriterSettings writerSettings;
// Attributes and namespaces are not allowed at the top-level by the well-formed writer
if (NodeType == XPathNodeType.Attribute)
{
return string.Concat(Name, "=\"", Value, "\"");
}
else if (NodeType == XPathNodeType.Namespace)
{
if (LocalName.Length == 0)
return string.Concat("xmlns=\"", Value, "\"");
else
return string.Concat("xmlns:", LocalName, "=\"", Value, "\"");
}
stringWriter = new StringWriter(CultureInfo.InvariantCulture);
writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.OmitXmlDeclaration = true;
writerSettings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
xmlWriter.WriteNode(this, true);
}
return stringWriter.ToString();
}
set
{
ReplaceSelf(value);
}
}
// Returns the markup representing just the children of the current node.
public virtual string InnerXml
{
get
{
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
StringWriter stringWriter;
XmlWriterSettings writerSettings;
XmlWriter xmlWriter;
stringWriter = new StringWriter(CultureInfo.InvariantCulture);
writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.OmitXmlDeclaration = true;
writerSettings.ConformanceLevel = ConformanceLevel.Auto;
xmlWriter = XmlWriter.Create(stringWriter, writerSettings);
try
{
if (MoveToFirstChild())
{
do
{
xmlWriter.WriteNode(this, true);
}
while (MoveToNext());
// Restore position
MoveToParent();
}
}
finally
{
xmlWriter.Dispose();
}
return stringWriter.ToString();
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
return Value;
default:
return string.Empty;
}
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
XPathNavigator edit = CreateNavigator();
while (edit.MoveToFirstChild())
{
edit.DeleteSelf();
}
if (value.Length != 0)
{
edit.AppendChild(value);
}
break;
case XPathNodeType.Attribute:
SetValue(value);
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
}
}
public virtual void AppendChild(string newChild)
{
XmlReader reader = CreateContextReader(newChild, true);
AppendChild(reader);
}
public virtual void AppendChild(XmlReader newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
XmlWriter writer = AppendChild();
BuildSubtree(newChild, writer);
writer.Dispose();
}
public virtual void AppendChild(XPathNavigator newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
if (!IsValidChildType(newChild.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newChild.CreateReader();
AppendChild(reader);
}
public virtual void PrependChild(string newChild)
{
XmlReader reader = CreateContextReader(newChild, true);
PrependChild(reader);
}
public virtual void PrependChild(XmlReader newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
XmlWriter writer = PrependChild();
BuildSubtree(newChild, writer);
writer.Dispose();
}
public virtual void PrependChild(XPathNavigator newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
if (!IsValidChildType(newChild.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newChild.CreateReader();
PrependChild(reader);
}
public virtual void InsertBefore(string newSibling)
{
XmlReader reader = CreateContextReader(newSibling, false);
InsertBefore(reader);
}
public virtual void InsertBefore(XmlReader newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
XmlWriter writer = InsertBefore();
BuildSubtree(newSibling, writer);
writer.Dispose();
}
public virtual void InsertBefore(XPathNavigator newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
if (!IsValidSiblingType(newSibling.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newSibling.CreateReader();
InsertBefore(reader);
}
public virtual void InsertAfter(string newSibling)
{
XmlReader reader = CreateContextReader(newSibling, false);
InsertAfter(reader);
}
public virtual void InsertAfter(XmlReader newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
XmlWriter writer = InsertAfter();
BuildSubtree(newSibling, writer);
writer.Dispose();
}
public virtual void InsertAfter(XPathNavigator newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
if (!IsValidSiblingType(newSibling.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newSibling.CreateReader();
InsertAfter(reader);
}
public virtual void DeleteRange(XPathNavigator lastSiblingToDelete)
{
throw new NotSupportedException();
}
public virtual void DeleteSelf()
{
DeleteRange(this);
}
// base for following methods
private static void WriteElement(XmlWriter writer, string prefix, string localName, string namespaceURI, string value)
{
writer.WriteStartElement(prefix, localName, namespaceURI);
if (value != null)
{
writer.WriteString(value);
}
writer.WriteEndElement();
writer.Dispose();
}
public virtual void PrependChildElement(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(PrependChild(), prefix, localName, namespaceURI, value);
}
public virtual void AppendChildElement(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(AppendChild(), prefix, localName, namespaceURI, value);
}
public virtual void InsertElementBefore(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(InsertBefore(), prefix, localName, namespaceURI, value);
}
public virtual void InsertElementAfter(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(InsertAfter(), prefix, localName, namespaceURI, value);
}
public virtual void CreateAttribute(string prefix, string localName, string namespaceURI, string value)
{
XmlWriter writer = CreateAttributes();
writer.WriteStartAttribute(prefix, localName, namespaceURI);
if (value != null)
{
writer.WriteString(value);
}
writer.WriteEndAttribute();
writer.Dispose();
}
//-----------------------------------------------
// Internal
//-----------------------------------------------
internal bool MoveToNonDescendant()
{
// If current node is document, there is no next non-descendant
if (NodeType == XPathNodeType.Root)
return false;
// If sibling exists, it is the next non-descendant
if (MoveToNext())
return true;
// The current node is either an attribute, namespace, or last child node
XPathNavigator navSave = Clone();
if (!MoveToParent())
return false;
switch (navSave.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Next node in document order is first content-child of parent
if (MoveToFirstChild())
return true;
break;
}
while (!MoveToNext())
{
if (!MoveToParent())
{
// Restore original position and return false
MoveTo(navSave);
return false;
}
}
return true;
}
/// <summary>
/// Returns ordinal number of attribute, namespace or child node within its parent.
/// Order is reversed for attributes and child nodes to avoid O(N**2) running time.
/// This property is useful for debugging, and also used in UniqueId implementation.
/// </summary>
internal uint IndexInParent
{
get
{
XPathNavigator nav = this.Clone();
uint idx = 0;
switch (NodeType)
{
case XPathNodeType.Attribute:
while (nav.MoveToNextAttribute())
{
idx++;
}
break;
case XPathNodeType.Namespace:
while (nav.MoveToNextNamespace())
{
idx++;
}
break;
default:
while (nav.MoveToNext())
{
idx++;
}
break;
}
return idx;
}
}
internal static readonly char[] NodeTypeLetter = new char[] {
'R', // Root
'E', // Element
'A', // Attribute
'N', // Namespace
'T', // Text
'S', // SignificantWhitespace
'W', // Whitespace
'P', // ProcessingInstruction
'C', // Comment
'X', // All
};
internal static readonly char[] UniqueIdTbl = new char[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4',
'5', '6'
};
// Requirements for id:
// 1. must consist of alphanumeric characters only
// 2. must begin with an alphabetic character
// 3. same id is generated for the same node
// 4. ids are unique
//
// id = node type letter + reverse path to root in terms of encoded IndexInParent integers from node to root seperated by 0's if needed
internal virtual string UniqueId
{
get
{
XPathNavigator nav = this.Clone();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Ensure distinguishing attributes, namespaces and child nodes
sb.Append(NodeTypeLetter[(int)NodeType]);
while (true)
{
uint idx = nav.IndexInParent;
if (!nav.MoveToParent())
{
break;
}
if (idx <= 0x1f)
{
sb.Append(UniqueIdTbl[idx]);
}
else
{
sb.Append('0');
do
{
sb.Append(UniqueIdTbl[idx & 0x1f]);
idx >>= 5;
} while (idx != 0);
sb.Append('0');
}
}
return sb.ToString();
}
}
private static XPathExpression CompileMatchPattern(string xpath)
{
bool hasPrefix;
Query query = new QueryBuilder().BuildPatternQuery(xpath, out hasPrefix);
return new CompiledXpathExpr(query, xpath, hasPrefix);
}
private static int GetDepth(XPathNavigator nav)
{
int depth = 0;
while (nav.MoveToParent())
{
depth++;
}
return depth;
}
// XPath based comparison for namespaces, attributes and other
// items with the same parent element.
//
// n2
// namespace(0) attribute(-1) other(-2)
// n1
// namespace(0) ?(0) before(-1) before(-2)
// attribute(1) after(1) ?(0) before(-1)
// other (2) after(2) after(1) ?(0)
private static XmlNodeOrder CompareSiblings(XPathNavigator n1, XPathNavigator n2)
{
int cmp = 0;
#if DEBUG
Debug.Assert(!n1.IsSamePosition(n2));
XPathNavigator p1 = n1.Clone(), p2 = n2.Clone();
Debug.Assert(p1.MoveToParent() && p2.MoveToParent() && p1.IsSamePosition(p2));
#endif
switch (n1.NodeType)
{
case XPathNodeType.Namespace:
break;
case XPathNodeType.Attribute:
cmp += 1;
break;
default:
cmp += 2;
break;
}
switch (n2.NodeType)
{
case XPathNodeType.Namespace:
if (cmp == 0)
{
while (n1.MoveToNextNamespace())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
case XPathNodeType.Attribute:
cmp -= 1;
if (cmp == 0)
{
while (n1.MoveToNextAttribute())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
default:
cmp -= 2;
if (cmp == 0)
{
while (n1.MoveToNext())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
}
return cmp < 0 ? XmlNodeOrder.Before : XmlNodeOrder.After;
}
internal static bool IsText(XPathNodeType type)
{
return (uint)(type - XPathNodeType.Text) <= (XPathNodeType.Whitespace - XPathNodeType.Text);
}
// Lax check for potential child item.
private bool IsValidChildType(XPathNodeType type)
{
switch (NodeType)
{
case XPathNodeType.Root:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
case XPathNodeType.Element:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
}
return false;
}
// Lax check for potential sibling item.
private bool IsValidSiblingType(XPathNodeType type)
{
switch (NodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
}
return false;
}
private XmlReader CreateReader()
{
return XPathNavigatorReader.Create(this);
}
private XmlReader CreateContextReader(string xml, bool fromCurrentNode)
{
if (xml == null)
{
throw new ArgumentNullException("xml");
}
// We have to set the namespace context for the reader.
XPathNavigator editor = CreateNavigator();
// scope starts from parent.
XmlNamespaceManager mgr = new XmlNamespaceManager(NameTable);
if (!fromCurrentNode)
{
editor.MoveToParent(); // should always succeed.
}
if (editor.MoveToFirstNamespace(XPathNamespaceScope.All))
{
do
{
mgr.AddNamespace(editor.LocalName, editor.Value);
}
while (editor.MoveToNextNamespace(XPathNamespaceScope.All));
}
XmlParserContext context = new XmlParserContext(NameTable, mgr, null, XmlSpace.Default);
return XmlReader.Create(new StringReader(xml), new XmlReaderSettings(), context);
}
internal static void BuildSubtree(XmlReader reader, XmlWriter writer)
{
// important (perf) string literal...
string xmlnsUri = XmlConst.ReservedNsXmlNs; // http://www.w3.org/2000/xmlns/
ReadState readState = reader.ReadState;
if (readState != ReadState.Initial
&& readState != ReadState.Interactive)
{
throw new ArgumentException(SR.Xml_InvalidOperation, "reader");
}
int level = 0;
if (readState == ReadState.Initial)
{
if (!reader.Read())
return;
level++; // if start in initial, read everything (not just first)
}
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
bool isEmptyElement = reader.IsEmptyElement;
while (reader.MoveToNextAttribute())
{
if ((object)reader.NamespaceURI == (object)xmlnsUri)
{
if (reader.Prefix.Length == 0)
{
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value);
}
else
{
Debug.Assert(reader.Prefix == "xmlns");
writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value);
}
}
else
{
writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteString(reader.Value);
writer.WriteEndAttribute();
}
}
reader.MoveToElement();
if (isEmptyElement)
{
// there might still be a value, if there is a default value specified in the schema
writer.WriteEndElement();
}
else
{
level++;
}
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
//should not read beyond the level of the reader's original position.
level--;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
writer.WriteString(reader.Value);
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
writer.WriteString(reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.LocalName, reader.Value);
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
break;
case XmlNodeType.EndEntity:
case XmlNodeType.None:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
break;
case XmlNodeType.Attribute:
if ((object)reader.NamespaceURI == (object)xmlnsUri)
{
if (reader.Prefix.Length == 0)
{
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value);
}
else
{
Debug.Assert(reader.Prefix == "xmlns");
writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value);
}
}
else
{
writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteString(reader.Value);
writer.WriteEndAttribute();
}
break;
}
}
while (reader.Read() && (level > 0));
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayProxy(this); } }
[DebuggerDisplay("{ToString()}")]
internal struct DebuggerDisplayProxy
{
XPathNavigator nav;
public DebuggerDisplayProxy(XPathNavigator nav)
{
this.nav = nav;
}
public override string ToString()
{
string result = nav.NodeType.ToString();
switch (nav.NodeType)
{
case XPathNodeType.Element:
result += ", Name=\"" + nav.Name + '"';
break;
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
case XPathNodeType.ProcessingInstruction:
result += ", Name=\"" + nav.Name + '"';
result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(nav.Value) + '"';
break;
case XPathNodeType.Text:
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Comment:
result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(nav.Value) + '"';
break;
}
return result;
}
}
}
}
| |
// <copyright file="SelectElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.UI
{
/// <summary>
/// Provides a convenience method for manipulating selections of options in an HTML select element.
/// </summary>
public class SelectElement : IWrapsElement
{
private readonly IWebElement element;
/// <summary>
/// Initializes a new instance of the <see cref="SelectElement"/> class.
/// </summary>
/// <param name="element">The element to be wrapped</param>
/// <exception cref="ArgumentNullException">Thrown when the <see cref="IWebElement"/> object is <see langword="null"/></exception>
/// <exception cref="UnexpectedTagNameException">Thrown when the element wrapped is not a <select> element.</exception>
public SelectElement(IWebElement element)
{
if (element == null)
{
throw new ArgumentNullException("element", "element cannot be null");
}
if (string.IsNullOrEmpty(element.TagName) || string.Compare(element.TagName, "select", StringComparison.OrdinalIgnoreCase) != 0)
{
throw new UnexpectedTagNameException("select", element.TagName);
}
this.element = element;
// let check if it's a multiple
string attribute = element.GetAttribute("multiple");
this.IsMultiple = attribute != null && attribute.ToLowerInvariant() != "false";
}
/// <summary>
/// Gets the <see cref="IWebElement"/> wrapped by this object.
/// </summary>
public IWebElement WrappedElement
{
get { return this.element; }
}
/// <summary>
/// Gets a value indicating whether the parent element supports multiple selections.
/// </summary>
public bool IsMultiple { get; private set; }
/// <summary>
/// Gets the list of options for the select element.
/// </summary>
public IList<IWebElement> Options
{
get
{
return this.element.FindElements(By.TagName("option"));
}
}
/// <summary>
/// Gets the selected item within the select element.
/// </summary>
/// <remarks>If more than one item is selected this will return the first item.</remarks>
/// <exception cref="NoSuchElementException">Thrown if no option is selected.</exception>
public IWebElement SelectedOption
{
get
{
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
return option;
}
}
throw new NoSuchElementException("No option is selected");
}
}
/// <summary>
/// Gets all of the selected options within the select element.
/// </summary>
public IList<IWebElement> AllSelectedOptions
{
get
{
List<IWebElement> returnValue = new List<IWebElement>();
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
returnValue.Add(option);
}
}
return returnValue;
}
}
/// <summary>
/// Select all options by the text displayed.
/// </summary>
/// <param name="text">The text of the option to be selected. If an exact match is not found,
/// this method will perform a substring match.</param>
/// <remarks>When given "Bar" this method would select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown if there is no element with the given text present.</exception>
public void SelectByText(string text)
{
if (text == null)
{
throw new ArgumentNullException("text", "text must not be null");
}
// try to find the option via XPATH ...
IList<IWebElement> options = this.element.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"));
bool matched = false;
foreach (IWebElement option in options)
{
SetSelected(option);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (options.Count == 0 && text.Contains(" "))
{
string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
IList<IWebElement> candidates;
if (string.IsNullOrEmpty(substringWithoutSpace))
{
// hmm, text is either empty or contains only spaces - get all options ...
candidates = this.element.FindElements(By.TagName("option"));
}
else
{
// get candidates via XPATH ...
candidates = this.element.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"));
}
foreach (IWebElement option in candidates)
{
if (text == option.Text)
{
SetSelected(option);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
}
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate element with text: " + text);
}
}
/// <summary>
/// Select an option by the value.
/// </summary>
/// <param name="value">The value of the option to be selected.</param>
/// <remarks>When given "foo" this method will select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown when no element with the specified value is found.</exception>
public void SelectByValue(string value)
{
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
bool matched = false;
foreach (IWebElement option in options)
{
SetSelected(option);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with value: " + value);
}
}
/// <summary>
/// Select the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <param name="index">The value of the index attribute of the option to be selected.</param>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified index attribute.</exception>
public void SelectByIndex(int index)
{
string match = index.ToString(CultureInfo.InvariantCulture);
bool matched = false;
foreach (IWebElement option in this.Options)
{
if (option.GetAttribute("index") == match)
{
SetSelected(option);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with index: " + index);
}
}
/// <summary>
/// Clear all selected entries. This is only valid when the SELECT supports multiple selections.
/// </summary>
/// <exception cref="WebDriverException">Thrown when attempting to deselect all options from a SELECT
/// that does not support multiple selections.</exception>
public void DeselectAll()
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect all options if multi-select is supported");
}
foreach (IWebElement webElement in this.Options)
{
if (webElement.Selected)
{
webElement.Click();
}
}
}
/// <summary>
/// Deselect the option by the text displayed.
/// </summary>
/// <param name="text">The text of the option to be deselected.</param>
/// <remarks>When given "Bar" this method would deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByText(string text)
{
StringBuilder builder = new StringBuilder(".//option[normalize-space(.) = ");
builder.Append(EscapeQuotes(text));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
if (option.Selected)
{
option.Click();
}
}
}
/// <summary>
/// Deselect the option having value matching the specified text.
/// </summary>
/// <param name="value">The value of the option to deselect.</param>
/// <remarks>When given "foo" this method will deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByValue(string value)
{
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
if (option.Selected)
{
option.Click();
}
}
}
/// <summary>
/// Deselect the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <param name="index">The value of the index attribute of the option to deselect.</param>
public void DeselectByIndex(int index)
{
string match = index.ToString(CultureInfo.InvariantCulture);
foreach (IWebElement option in this.Options)
{
if (match == option.GetAttribute("index") && option.Selected)
{
option.Click();
}
}
}
private static string EscapeQuotes(string toEscape)
{
// Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1 && toEscape.IndexOf("'", StringComparison.OrdinalIgnoreCase) > -1)
{
bool quoteIsLast = false;
if (toEscape.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase) == toEscape.Length - 1)
{
quoteIsLast = true;
}
List<string> substrings = new List<string>(toEscape.Split('\"'));
if (quoteIsLast && string.IsNullOrEmpty(substrings[substrings.Count - 1]))
{
// If the last character is a quote ('"'), we end up with an empty entry
// at the end of the list, which is unnecessary. We don't want to split
// ignoring *all* empty entries, since that might mask legitimate empty
// strings. Instead, just remove the empty ending entry.
substrings.RemoveAt(substrings.Count - 1);
}
StringBuilder quoted = new StringBuilder("concat(");
for (int i = 0; i < substrings.Count; i++)
{
quoted.Append("\"").Append(substrings[i]).Append("\"");
if (i == substrings.Count - 1)
{
if (quoteIsLast)
{
quoted.Append(", '\"')");
}
else
{
quoted.Append(")");
}
}
else
{
quoted.Append(", '\"', ");
}
}
return quoted.ToString();
}
// Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1)
{
return string.Format(CultureInfo.InvariantCulture, "'{0}'", toEscape);
}
// Otherwise return the quoted string
return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", toEscape);
}
private static string GetLongestSubstringWithoutSpace(string s)
{
string result = string.Empty;
string[] substrings = s.Split(' ');
foreach (string substring in substrings)
{
if (substring.Length > result.Length)
{
result = substring;
}
}
return result;
}
private static void SetSelected(IWebElement option)
{
if (!option.Selected)
{
option.Click();
}
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IReceivingWorksheetApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Create a receivingWorksheet
/// </summary>
/// <remarks>
/// Inserts a new receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>ReceivingWorksheet</returns>
ReceivingWorksheet AddReceivingWorksheet (ReceivingWorksheet body);
/// <summary>
/// Create a receivingWorksheet
/// </summary>
/// <remarks>
/// Inserts a new receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>ApiResponse of ReceivingWorksheet</returns>
ApiResponse<ReceivingWorksheet> AddReceivingWorksheetWithHttpInfo (ReceivingWorksheet body);
/// <summary>
/// Delete a receivingWorksheet
/// </summary>
/// <remarks>
/// Deletes the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns></returns>
void DeleteReceivingWorksheet (int? receivingWorksheetId);
/// <summary>
/// Delete a receivingWorksheet
/// </summary>
/// <remarks>
/// Deletes the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DeleteReceivingWorksheetWithHttpInfo (int? receivingWorksheetId);
/// <summary>
/// Search receivingWorksheets by filter
/// </summary>
/// <remarks>
/// Returns the list of receivingWorksheets that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<ReceivingWorksheet></returns>
List<ReceivingWorksheet> GetReceivingWorksheetByFilter (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search receivingWorksheets by filter
/// </summary>
/// <remarks>
/// Returns the list of receivingWorksheets that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<ReceivingWorksheet></returns>
ApiResponse<List<ReceivingWorksheet>> GetReceivingWorksheetByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a receivingWorksheet by id
/// </summary>
/// <remarks>
/// Returns the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>ReceivingWorksheet</returns>
ReceivingWorksheet GetReceivingWorksheetById (int? receivingWorksheetId);
/// <summary>
/// Get a receivingWorksheet by id
/// </summary>
/// <remarks>
/// Returns the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>ApiResponse of ReceivingWorksheet</returns>
ApiResponse<ReceivingWorksheet> GetReceivingWorksheetByIdWithHttpInfo (int? receivingWorksheetId);
/// <summary>
/// Update a receivingWorksheet
/// </summary>
/// <remarks>
/// Updates an existing receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns></returns>
void UpdateReceivingWorksheet (ReceivingWorksheet body);
/// <summary>
/// Update a receivingWorksheet
/// </summary>
/// <remarks>
/// Updates an existing receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> UpdateReceivingWorksheetWithHttpInfo (ReceivingWorksheet body);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Create a receivingWorksheet
/// </summary>
/// <remarks>
/// Inserts a new receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>Task of ReceivingWorksheet</returns>
System.Threading.Tasks.Task<ReceivingWorksheet> AddReceivingWorksheetAsync (ReceivingWorksheet body);
/// <summary>
/// Create a receivingWorksheet
/// </summary>
/// <remarks>
/// Inserts a new receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>Task of ApiResponse (ReceivingWorksheet)</returns>
System.Threading.Tasks.Task<ApiResponse<ReceivingWorksheet>> AddReceivingWorksheetAsyncWithHttpInfo (ReceivingWorksheet body);
/// <summary>
/// Delete a receivingWorksheet
/// </summary>
/// <remarks>
/// Deletes the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DeleteReceivingWorksheetAsync (int? receivingWorksheetId);
/// <summary>
/// Delete a receivingWorksheet
/// </summary>
/// <remarks>
/// Deletes the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DeleteReceivingWorksheetAsyncWithHttpInfo (int? receivingWorksheetId);
/// <summary>
/// Search receivingWorksheets by filter
/// </summary>
/// <remarks>
/// Returns the list of receivingWorksheets that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<ReceivingWorksheet></returns>
System.Threading.Tasks.Task<List<ReceivingWorksheet>> GetReceivingWorksheetByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search receivingWorksheets by filter
/// </summary>
/// <remarks>
/// Returns the list of receivingWorksheets that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<ReceivingWorksheet>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ReceivingWorksheet>>> GetReceivingWorksheetByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a receivingWorksheet by id
/// </summary>
/// <remarks>
/// Returns the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>Task of ReceivingWorksheet</returns>
System.Threading.Tasks.Task<ReceivingWorksheet> GetReceivingWorksheetByIdAsync (int? receivingWorksheetId);
/// <summary>
/// Get a receivingWorksheet by id
/// </summary>
/// <remarks>
/// Returns the receivingWorksheet identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>Task of ApiResponse (ReceivingWorksheet)</returns>
System.Threading.Tasks.Task<ApiResponse<ReceivingWorksheet>> GetReceivingWorksheetByIdAsyncWithHttpInfo (int? receivingWorksheetId);
/// <summary>
/// Update a receivingWorksheet
/// </summary>
/// <remarks>
/// Updates an existing receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task UpdateReceivingWorksheetAsync (ReceivingWorksheet body);
/// <summary>
/// Update a receivingWorksheet
/// </summary>
/// <remarks>
/// Updates an existing receivingWorksheet using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> UpdateReceivingWorksheetAsyncWithHttpInfo (ReceivingWorksheet body);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ReceivingWorksheetApi : IReceivingWorksheetApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingWorksheetApi"/> class.
/// </summary>
/// <returns></returns>
public ReceivingWorksheetApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingWorksheetApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ReceivingWorksheetApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Create a receivingWorksheet Inserts a new receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>ReceivingWorksheet</returns>
public ReceivingWorksheet AddReceivingWorksheet (ReceivingWorksheet body)
{
ApiResponse<ReceivingWorksheet> localVarResponse = AddReceivingWorksheetWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a receivingWorksheet Inserts a new receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>ApiResponse of ReceivingWorksheet</returns>
public ApiResponse< ReceivingWorksheet > AddReceivingWorksheetWithHttpInfo (ReceivingWorksheet body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling ReceivingWorksheetApi->AddReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ReceivingWorksheet>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ReceivingWorksheet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReceivingWorksheet)));
}
/// <summary>
/// Create a receivingWorksheet Inserts a new receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>Task of ReceivingWorksheet</returns>
public async System.Threading.Tasks.Task<ReceivingWorksheet> AddReceivingWorksheetAsync (ReceivingWorksheet body)
{
ApiResponse<ReceivingWorksheet> localVarResponse = await AddReceivingWorksheetAsyncWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a receivingWorksheet Inserts a new receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be inserted.</param>
/// <returns>Task of ApiResponse (ReceivingWorksheet)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ReceivingWorksheet>> AddReceivingWorksheetAsyncWithHttpInfo (ReceivingWorksheet body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling ReceivingWorksheetApi->AddReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ReceivingWorksheet>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ReceivingWorksheet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReceivingWorksheet)));
}
/// <summary>
/// Delete a receivingWorksheet Deletes the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns></returns>
public void DeleteReceivingWorksheet (int? receivingWorksheetId)
{
DeleteReceivingWorksheetWithHttpInfo(receivingWorksheetId);
}
/// <summary>
/// Delete a receivingWorksheet Deletes the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> DeleteReceivingWorksheetWithHttpInfo (int? receivingWorksheetId)
{
// verify the required parameter 'receivingWorksheetId' is set
if (receivingWorksheetId == null)
throw new ApiException(400, "Missing required parameter 'receivingWorksheetId' when calling ReceivingWorksheetApi->DeleteReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet/{receivingWorksheetId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (receivingWorksheetId != null) localVarPathParams.Add("receivingWorksheetId", Configuration.ApiClient.ParameterToString(receivingWorksheetId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Delete a receivingWorksheet Deletes the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DeleteReceivingWorksheetAsync (int? receivingWorksheetId)
{
await DeleteReceivingWorksheetAsyncWithHttpInfo(receivingWorksheetId);
}
/// <summary>
/// Delete a receivingWorksheet Deletes the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteReceivingWorksheetAsyncWithHttpInfo (int? receivingWorksheetId)
{
// verify the required parameter 'receivingWorksheetId' is set
if (receivingWorksheetId == null)
throw new ApiException(400, "Missing required parameter 'receivingWorksheetId' when calling ReceivingWorksheetApi->DeleteReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet/{receivingWorksheetId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (receivingWorksheetId != null) localVarPathParams.Add("receivingWorksheetId", Configuration.ApiClient.ParameterToString(receivingWorksheetId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Search receivingWorksheets by filter Returns the list of receivingWorksheets that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<ReceivingWorksheet></returns>
public List<ReceivingWorksheet> GetReceivingWorksheetByFilter (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<ReceivingWorksheet>> localVarResponse = GetReceivingWorksheetByFilterWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search receivingWorksheets by filter Returns the list of receivingWorksheets that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<ReceivingWorksheet></returns>
public ApiResponse< List<ReceivingWorksheet> > GetReceivingWorksheetByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/receivingWorksheet/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetReceivingWorksheetByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ReceivingWorksheet>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ReceivingWorksheet>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ReceivingWorksheet>)));
}
/// <summary>
/// Search receivingWorksheets by filter Returns the list of receivingWorksheets that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<ReceivingWorksheet></returns>
public async System.Threading.Tasks.Task<List<ReceivingWorksheet>> GetReceivingWorksheetByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<ReceivingWorksheet>> localVarResponse = await GetReceivingWorksheetByFilterAsyncWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search receivingWorksheets by filter Returns the list of receivingWorksheets that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<ReceivingWorksheet>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ReceivingWorksheet>>> GetReceivingWorksheetByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/receivingWorksheet/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetReceivingWorksheetByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ReceivingWorksheet>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ReceivingWorksheet>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ReceivingWorksheet>)));
}
/// <summary>
/// Get a receivingWorksheet by id Returns the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>ReceivingWorksheet</returns>
public ReceivingWorksheet GetReceivingWorksheetById (int? receivingWorksheetId)
{
ApiResponse<ReceivingWorksheet> localVarResponse = GetReceivingWorksheetByIdWithHttpInfo(receivingWorksheetId);
return localVarResponse.Data;
}
/// <summary>
/// Get a receivingWorksheet by id Returns the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>ApiResponse of ReceivingWorksheet</returns>
public ApiResponse< ReceivingWorksheet > GetReceivingWorksheetByIdWithHttpInfo (int? receivingWorksheetId)
{
// verify the required parameter 'receivingWorksheetId' is set
if (receivingWorksheetId == null)
throw new ApiException(400, "Missing required parameter 'receivingWorksheetId' when calling ReceivingWorksheetApi->GetReceivingWorksheetById");
var localVarPath = "/v1.0/receivingWorksheet/{receivingWorksheetId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (receivingWorksheetId != null) localVarPathParams.Add("receivingWorksheetId", Configuration.ApiClient.ParameterToString(receivingWorksheetId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetReceivingWorksheetById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ReceivingWorksheet>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ReceivingWorksheet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReceivingWorksheet)));
}
/// <summary>
/// Get a receivingWorksheet by id Returns the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>Task of ReceivingWorksheet</returns>
public async System.Threading.Tasks.Task<ReceivingWorksheet> GetReceivingWorksheetByIdAsync (int? receivingWorksheetId)
{
ApiResponse<ReceivingWorksheet> localVarResponse = await GetReceivingWorksheetByIdAsyncWithHttpInfo(receivingWorksheetId);
return localVarResponse.Data;
}
/// <summary>
/// Get a receivingWorksheet by id Returns the receivingWorksheet identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="receivingWorksheetId">Id of the receivingWorksheet to be returned.</param>
/// <returns>Task of ApiResponse (ReceivingWorksheet)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ReceivingWorksheet>> GetReceivingWorksheetByIdAsyncWithHttpInfo (int? receivingWorksheetId)
{
// verify the required parameter 'receivingWorksheetId' is set
if (receivingWorksheetId == null)
throw new ApiException(400, "Missing required parameter 'receivingWorksheetId' when calling ReceivingWorksheetApi->GetReceivingWorksheetById");
var localVarPath = "/v1.0/receivingWorksheet/{receivingWorksheetId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (receivingWorksheetId != null) localVarPathParams.Add("receivingWorksheetId", Configuration.ApiClient.ParameterToString(receivingWorksheetId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetReceivingWorksheetById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ReceivingWorksheet>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ReceivingWorksheet) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReceivingWorksheet)));
}
/// <summary>
/// Update a receivingWorksheet Updates an existing receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns></returns>
public void UpdateReceivingWorksheet (ReceivingWorksheet body)
{
UpdateReceivingWorksheetWithHttpInfo(body);
}
/// <summary>
/// Update a receivingWorksheet Updates an existing receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> UpdateReceivingWorksheetWithHttpInfo (ReceivingWorksheet body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling ReceivingWorksheetApi->UpdateReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update a receivingWorksheet Updates an existing receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task UpdateReceivingWorksheetAsync (ReceivingWorksheet body)
{
await UpdateReceivingWorksheetAsyncWithHttpInfo(body);
}
/// <summary>
/// Update a receivingWorksheet Updates an existing receivingWorksheet using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">ReceivingWorksheet to be updated.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateReceivingWorksheetAsyncWithHttpInfo (ReceivingWorksheet body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling ReceivingWorksheetApi->UpdateReceivingWorksheet");
var localVarPath = "/v1.0/receivingWorksheet";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateReceivingWorksheet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
internal static class File
{
private const int ERROR_INVALID_PARAMETER = 87;
internal const int GENERIC_READ = unchecked((int)0x80000000);
private const int GetFileExInfoStandard = 0;
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
public static bool Exists(String path)
{
return InternalExistsHelper(path);
}
private static bool InternalExistsHelper(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
internal static bool InternalExists(String path)
{
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None))
{
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int)fileLength;
bytes = new byte[count];
while (count > 0)
{
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
#if PLATFORM_UNIX
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
#endif // PLATFORM_UNIX
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try
{
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData);
try
{
if (handle.IsInvalid)
{
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally
{
// Close the Win32 handle
try
{
handle.Close();
}
catch
{
// if we're already returning an error, don't throw another one.
if (!error)
{
Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
finally
{
Win32Native.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try
{
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
finally
{
Win32Native.SetErrorMode(oldMode);
}
if (!success)
{
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else
{
if (!returnErrorOnNotFound)
{
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
}
}
| |
//
// Mono.System.Xml.XmlParserContext
//
// Author:
// Jason Diamond (jason@injektilo.org)
// Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//
// (C) 2001, 2002 Jason Diamond http://injektilo.org/
// (C) 2003 Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Text;
using Mono.Xml;
#if NET_2_0
using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
#else
using XmlTextReaderImpl = System.Xml.XmlTextReader;
#endif
namespace Mono.System.Xml
{
public class XmlParserContext
{
#region Class
class ContextItem
{
public string BaseURI;
public string XmlLang;
public XmlSpace XmlSpace;
}
#endregion
#region Constructors
public XmlParserContext (
XmlNameTable nt,
XmlNamespaceManager nsMgr,
string xmlLang,
XmlSpace xmlSpace) :
this (
nt,
nsMgr,
null,
null,
null,
null,
null,
xmlLang,
xmlSpace,
null
)
{
}
public XmlParserContext (
XmlNameTable nt,
XmlNamespaceManager nsMgr,
string xmlLang,
XmlSpace xmlSpace,
Encoding enc) :
this (
nt,
nsMgr,
null,
null,
null,
null,
null,
xmlLang,
xmlSpace,
enc
)
{
}
public XmlParserContext (
XmlNameTable nt,
XmlNamespaceManager nsMgr,
string docTypeName,
string pubId,
string sysId,
string internalSubset,
string baseURI,
string xmlLang,
XmlSpace xmlSpace) :
this (
nt,
nsMgr,
docTypeName,
pubId,
sysId,
internalSubset,
baseURI,
xmlLang,
xmlSpace,
null
)
{
}
public XmlParserContext (
XmlNameTable nt,
XmlNamespaceManager nsMgr,
string docTypeName,
string pubId,
string sysId,
string internalSubset,
string baseURI,
string xmlLang,
XmlSpace xmlSpace,
Encoding enc)
: this (
nt,
nsMgr,
(docTypeName != null && docTypeName != String.Empty) ?
new XmlTextReaderImpl (TextReader.Null, nt).GenerateDTDObjectModel (
docTypeName, pubId, sysId, internalSubset) : null,
baseURI,
xmlLang,
xmlSpace,
enc)
{
}
internal XmlParserContext (XmlNameTable nt,
XmlNamespaceManager nsMgr,
DTDObjectModel dtd,
string baseURI,
string xmlLang,
XmlSpace xmlSpace,
Encoding enc)
{
this.namespaceManager = nsMgr;
this.nameTable = nt != null ? nt : nsMgr != null ? nsMgr.NameTable : null;
if (dtd != null) {
this.DocTypeName = dtd.Name;
this.PublicId = dtd.PublicId;
this.SystemId = dtd.SystemId;
this.InternalSubset = dtd.InternalSubset;
this.dtd = dtd;
}
this.encoding = enc;
this.BaseURI = baseURI;
this.XmlLang = xmlLang;
this.xmlSpace = xmlSpace;
contextItems = new ArrayList ();
}
#endregion
#region Fields
private string baseURI = String.Empty;
private string docTypeName = String.Empty;
private Encoding encoding;
private string internalSubset = String.Empty;
private XmlNamespaceManager namespaceManager;
private XmlNameTable nameTable;
private string publicID = String.Empty;
private string systemID = String.Empty;
private string xmlLang = String.Empty;
private XmlSpace xmlSpace;
private ArrayList contextItems;
private int contextItemCount;
private DTDObjectModel dtd;
#endregion
#region Properties
public string BaseURI {
get { return baseURI; }
set { baseURI = value != null ? value : String.Empty; }
}
public string DocTypeName {
get { return docTypeName != null ? docTypeName : dtd != null ? dtd.Name : null; }
set { docTypeName = value != null ? value : String.Empty; }
}
internal DTDObjectModel Dtd {
get { return dtd; }
set { dtd = value; }
}
public Encoding Encoding {
get { return encoding; }
set { encoding = value; }
}
public string InternalSubset {
get { return internalSubset != null ? internalSubset : dtd != null ? dtd.InternalSubset : null; }
set { internalSubset = value != null ? value : String.Empty; }
}
public XmlNamespaceManager NamespaceManager {
get { return namespaceManager; }
set { namespaceManager = value; }
}
public XmlNameTable NameTable {
get { return nameTable; }
set { nameTable = value; }
}
public string PublicId {
get { return publicID != null ? publicID : dtd != null ? dtd.PublicId : null; }
set { publicID = value != null ? value : String.Empty; }
}
public string SystemId {
get { return systemID != null ? systemID : dtd != null ? dtd.SystemId : null; }
set { systemID = value != null ? value : String.Empty; }
}
public string XmlLang {
get { return xmlLang; }
set { xmlLang = value != null ? value : String.Empty; }
}
public XmlSpace XmlSpace {
get { return xmlSpace; }
set { xmlSpace = value; }
}
#endregion
#region Methods
internal void PushScope ()
{
ContextItem item = null;
if (contextItems.Count == contextItemCount) {
item = new ContextItem ();
contextItems.Add (item);
}
else
item = (ContextItem) contextItems [contextItemCount];
item.BaseURI = BaseURI;
item.XmlLang = XmlLang;
item.XmlSpace = XmlSpace;
contextItemCount++;
}
internal void PopScope ()
{
if (contextItemCount == 0)
throw new XmlException ("Unexpected end of element scope.");
contextItemCount--;
ContextItem prev = (ContextItem) contextItems [contextItemCount];
baseURI = prev.BaseURI;
xmlLang = prev.XmlLang;
xmlSpace = prev.XmlSpace;
}
#endregion
}
}
| |
namespace Azure.Storage.Queues
{
public partial class QueueClient
{
protected QueueClient() { }
public QueueClient(string connectionString, string queueName) { }
public QueueClient(string connectionString, string queueName, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueClient(System.Uri queueUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual bool CanGenerateSasUri { get { throw null; } }
public virtual int MaxPeekableMessages { get { throw null; } }
public virtual int MessageMaxBytes { get { throw null; } }
protected virtual System.Uri MessagesUri { get { throw null; } }
public virtual string Name { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response ClearMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> ClearMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Create(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response CreateIfNotExists(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateIfNotExistsAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> DeleteIfExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> DeleteIfExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteMessage(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteMessageAsync(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> Exists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasBuilder builder) { throw null; }
public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected internal virtual Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClientCore() { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected virtual System.Threading.Tasks.Task OnMessageDecodingFailedAsync(Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage> PeekMessage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage>> PeekMessageAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]> PeekMessages(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]>> PeekMessagesAsync(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage> ReceiveMessage(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage>> ReceiveMessageAsync(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages() { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync() { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetMetadata(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetMetadataAsync(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected internal virtual Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptionsCore(Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; }
}
public partial class QueueClientOptions : Azure.Core.ClientOptions
{
public QueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_06_12) { }
public System.Uri GeoRedundantSecondaryUri { get { throw null; } set { } }
public Azure.Storage.Queues.QueueMessageEncoding MessageEncoding { get { throw null; } set { } }
public Azure.Storage.Queues.QueueClientOptions.ServiceVersion Version { get { throw null; } }
public event Azure.Core.SyncAsyncEventHandler<Azure.Storage.Queues.QueueMessageDecodingFailedEventArgs> MessageDecodingFailed { add { } remove { } }
public enum ServiceVersion
{
V2019_02_02 = 1,
V2019_07_07 = 2,
V2019_12_12 = 3,
V2020_02_10 = 4,
V2020_04_08 = 5,
V2020_06_12 = 6,
}
}
public partial class QueueMessageDecodingFailedEventArgs : Azure.SyncAsyncEventArgs
{
public QueueMessageDecodingFailedEventArgs(Azure.Storage.Queues.QueueClient queueClient, Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) : base (default(bool), default(System.Threading.CancellationToken)) { }
public Azure.Storage.Queues.Models.PeekedMessage PeekedMessage { get { throw null; } }
public Azure.Storage.Queues.QueueClient Queue { get { throw null; } }
public Azure.Storage.Queues.Models.QueueMessage ReceivedMessage { get { throw null; } }
}
public enum QueueMessageEncoding
{
None = 0,
Base64 = 1,
}
public partial class QueueServiceClient
{
protected QueueServiceClient() { }
public QueueServiceClient(string connectionString) { }
public QueueServiceClient(string connectionString, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueServiceClient(System.Uri serviceUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual bool CanGenerateAccountSasUri { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response<Azure.Storage.Queues.QueueClient> CreateQueue(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.QueueClient>> CreateQueueAsync(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteQueue(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteQueueAsync(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasBuilder builder) { throw null; }
public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasPermissions permissions, System.DateTimeOffset expiresOn, Azure.Storage.Sas.AccountSasResourceTypes resourceTypes) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Storage.Queues.QueueClient GetQueueClient(string queueName) { throw null; }
public virtual Azure.Pageable<Azure.Storage.Queues.Models.QueueItem> GetQueues(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Storage.Queues.Models.QueueItem> GetQueuesAsync(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetProperties(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class QueueUriBuilder
{
public QueueUriBuilder(System.Uri uri) { }
public string AccountName { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public string MessageId { get { throw null; } set { } }
public bool Messages { get { throw null; } set { } }
public int Port { get { throw null; } set { } }
public string Query { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public Azure.Storage.Sas.SasQueryParameters Sas { get { throw null; } set { } }
public string Scheme { get { throw null; } set { } }
public override string ToString() { throw null; }
public System.Uri ToUri() { throw null; }
}
}
namespace Azure.Storage.Queues.Models
{
public partial class PeekedMessage
{
internal PeekedMessage() { }
public System.BinaryData Body { get { throw null; } }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public string MessageText { get { throw null; } }
}
public partial class QueueAccessPolicy
{
public QueueAccessPolicy() { }
public System.DateTimeOffset? ExpiresOn { get { throw null; } set { } }
public string Permissions { get { throw null; } set { } }
public System.DateTimeOffset? StartsOn { get { throw null; } set { } }
}
public partial class QueueAnalyticsLogging
{
public QueueAnalyticsLogging() { }
public bool Delete { get { throw null; } set { } }
public bool Read { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
public bool Write { get { throw null; } set { } }
}
public partial class QueueCorsRule
{
public QueueCorsRule() { }
public string AllowedHeaders { get { throw null; } set { } }
public string AllowedMethods { get { throw null; } set { } }
public string AllowedOrigins { get { throw null; } set { } }
public string ExposedHeaders { get { throw null; } set { } }
public int MaxAgeInSeconds { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct QueueErrorCode : System.IEquatable<Azure.Storage.Queues.Models.QueueErrorCode>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public QueueErrorCode(string value) { throw null; }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountBeingCreated { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountIsDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthenticationFailed { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationFailure { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationPermissionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationProtocolMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationServiceMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationSourceIPMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionNotMet { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode EmptyMetadataKey { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode FeatureVersionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InsufficientAccountPermissions { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InternalError { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidAuthenticationInfo { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHeaderValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMarker { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMd5 { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMetadata { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidRange { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidResourceName { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidUri { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlDocument { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlNodeValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode Md5Mismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MetadataTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingContentLengthHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredXmlNode { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MultipleConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OperationTimedOut { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode PopReceiptMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueBeingDeleted { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotEmpty { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestBodyTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestUrlFailedToParse { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ServerBusy { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedXmlNode { get { throw null; } }
public bool Equals(Azure.Storage.Queues.Models.QueueErrorCode other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public static implicit operator Azure.Storage.Queues.Models.QueueErrorCode (string value) { throw null; }
public static bool operator !=(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public override string ToString() { throw null; }
}
public partial class QueueGeoReplication
{
internal QueueGeoReplication() { }
public System.DateTimeOffset? LastSyncedOn { get { throw null; } }
public Azure.Storage.Queues.Models.QueueGeoReplicationStatus Status { get { throw null; } }
}
public enum QueueGeoReplicationStatus
{
Live = 0,
Bootstrap = 1,
Unavailable = 2,
}
public partial class QueueItem
{
internal QueueItem() { }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class QueueMessage
{
internal QueueMessage() { }
public System.BinaryData Body { get { throw null; } }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public string MessageText { get { throw null; } }
public System.DateTimeOffset? NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
public Azure.Storage.Queues.Models.QueueMessage Update(Azure.Storage.Queues.Models.UpdateReceipt updated) { throw null; }
}
public partial class QueueMetrics
{
public QueueMetrics() { }
public bool Enabled { get { throw null; } set { } }
public bool? IncludeApis { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
public partial class QueueProperties
{
public QueueProperties() { }
public int ApproximateMessagesCount { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
}
public partial class QueueRetentionPolicy
{
public QueueRetentionPolicy() { }
public int? Days { get { throw null; } set { } }
public bool Enabled { get { throw null; } set { } }
}
public partial class QueueServiceProperties
{
public QueueServiceProperties() { }
public System.Collections.Generic.IList<Azure.Storage.Queues.Models.QueueCorsRule> Cors { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics HourMetrics { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueAnalyticsLogging Logging { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics MinuteMetrics { get { throw null; } set { } }
}
public partial class QueueServiceStatistics
{
internal QueueServiceStatistics() { }
public Azure.Storage.Queues.Models.QueueGeoReplication GeoReplication { get { throw null; } }
}
public partial class QueueSignedIdentifier
{
public QueueSignedIdentifier() { }
public Azure.Storage.Queues.Models.QueueAccessPolicy AccessPolicy { get { throw null; } set { } }
public string Id { get { throw null; } set { } }
}
public static partial class QueuesModelFactory
{
public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, System.BinaryData message, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, string messageText, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueGeoReplication QueueGeoReplication(Azure.Storage.Queues.Models.QueueGeoReplicationStatus status, System.DateTimeOffset? lastSyncedOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueItem QueueItem(string name, System.Collections.Generic.IDictionary<string, string> metadata = null) { throw null; }
public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, System.BinaryData body, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, string messageText, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueProperties QueueProperties(System.Collections.Generic.IDictionary<string, string> metadata, int approximateMessagesCount) { throw null; }
public static Azure.Storage.Queues.Models.QueueServiceStatistics QueueServiceStatistics(Azure.Storage.Queues.Models.QueueGeoReplication geoReplication = null) { throw null; }
public static Azure.Storage.Queues.Models.SendReceipt SendReceipt(string messageId, System.DateTimeOffset insertionTime, System.DateTimeOffset expirationTime, string popReceipt, System.DateTimeOffset timeNextVisible) { throw null; }
public static Azure.Storage.Queues.Models.UpdateReceipt UpdateReceipt(string popReceipt, System.DateTimeOffset nextVisibleOn) { throw null; }
}
[System.FlagsAttribute]
public enum QueueTraits
{
None = 0,
Metadata = 1,
}
public partial class SendReceipt
{
internal SendReceipt() { }
public System.DateTimeOffset ExpirationTime { get { throw null; } }
public System.DateTimeOffset InsertionTime { get { throw null; } }
public string MessageId { get { throw null; } }
public string PopReceipt { get { throw null; } }
public System.DateTimeOffset TimeNextVisible { get { throw null; } }
}
public partial class UpdateReceipt
{
internal UpdateReceipt() { }
public System.DateTimeOffset NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
}
}
namespace Azure.Storage.Queues.Specialized
{
public partial class ClientSideDecryptionFailureEventArgs
{
internal ClientSideDecryptionFailureEventArgs() { }
public System.Exception Exception { get { throw null; } }
}
public partial class QueueClientSideEncryptionOptions : Azure.Storage.ClientSideEncryptionOptions
{
public QueueClientSideEncryptionOptions(Azure.Storage.ClientSideEncryptionVersion version) : base (default(Azure.Storage.ClientSideEncryptionVersion)) { }
public event System.EventHandler<Azure.Storage.Queues.Specialized.ClientSideDecryptionFailureEventArgs> DecryptionFailed { add { } remove { } }
}
public partial class SpecializedQueueClientOptions : Azure.Storage.Queues.QueueClientOptions
{
public SpecializedQueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_06_12) : base (default(Azure.Storage.Queues.QueueClientOptions.ServiceVersion)) { }
public Azure.Storage.ClientSideEncryptionOptions ClientSideEncryption { get { throw null; } set { } }
}
public static partial class SpecializedQueueExtensions
{
public static Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClient(this Azure.Storage.Queues.QueueClient client) { throw null; }
public static Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptions(this Azure.Storage.Queues.QueueClient client, Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; }
}
}
namespace Azure.Storage.Sas
{
[System.FlagsAttribute]
public enum QueueAccountSasPermissions
{
All = -1,
Read = 1,
Write = 2,
Delete = 4,
List = 8,
Add = 16,
Update = 32,
Process = 64,
}
public partial class QueueSasBuilder
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public QueueSasBuilder() { }
public QueueSasBuilder(Azure.Storage.Sas.QueueAccountSasPermissions permissions, System.DateTimeOffset expiresOn) { }
public QueueSasBuilder(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Storage.Sas.SasIPRange IPRange { get { throw null; } set { } }
public string Permissions { get { throw null; } }
public Azure.Storage.Sas.SasProtocol Protocol { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public void SetPermissions(Azure.Storage.Sas.QueueAccountSasPermissions permissions) { }
public void SetPermissions(Azure.Storage.Sas.QueueSasPermissions permissions) { }
public void SetPermissions(string rawPermissions) { }
public void SetPermissions(string rawPermissions, bool normalize = false) { }
public Azure.Storage.Sas.SasQueryParameters ToSasQueryParameters(Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum QueueSasPermissions
{
All = -1,
Read = 1,
Add = 2,
Update = 4,
Process = 8,
}
}
namespace Microsoft.Extensions.Azure
{
public static partial class QueueClientBuilderExtensions
{
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
}
}
| |
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 RunnersTimeManagement.WebServer.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
//
// 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 job streams. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations for more
/// information)
/// </summary>
internal partial class JobStreamOperations : IServiceOperations<AutomationManagementClient>, IJobStreamOperations
{
/// <summary>
/// Initializes a new instance of the JobStreamOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal JobStreamOperations(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 job stream identified by job stream id. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations 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='jobId'>
/// Required. The job id.
/// </param>
/// <param name='jobStreamId'>
/// Required. The job stream id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get job stream operation.
/// </returns>
public async Task<JobStreamGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid jobId, string jobStreamId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (jobStreamId == null)
{
throw new ArgumentNullException("jobStreamId");
}
// 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("jobId", jobId);
tracingParameters.Add("jobStreamId", jobStreamId);
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 + "/Jobs/";
url = url + Uri.EscapeDataString(jobId.ToString());
url = url + "/streams/";
url = url + Uri.EscapeDataString(jobStreamId);
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
JobStreamGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobStreamGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JobStream jobStreamInstance = new JobStream();
result.JobStream = jobStreamInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobStreamProperties propertiesInstance = new JobStreamProperties();
jobStreamInstance.Properties = propertiesInstance;
JToken jobStreamIdValue = propertiesValue["jobStreamId"];
if (jobStreamIdValue != null && jobStreamIdValue.Type != JTokenType.Null)
{
string jobStreamIdInstance = ((string)jobStreamIdValue);
propertiesInstance.JobStreamId = jobStreamIdInstance;
}
JToken timeValue = propertiesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
propertiesInstance.Time = timeInstance;
}
JToken streamTypeValue = propertiesValue["streamType"];
if (streamTypeValue != null && streamTypeValue.Type != JTokenType.Null)
{
string streamTypeInstance = ((string)streamTypeValue);
propertiesInstance.StreamType = streamTypeInstance;
}
JToken streamTextValue = propertiesValue["streamText"];
if (streamTextValue != null && streamTextValue.Type != JTokenType.Null)
{
string streamTextInstance = ((string)streamTextValue);
propertiesInstance.StreamText = streamTextInstance;
}
JToken summaryValue = propertiesValue["summary"];
if (summaryValue != null && summaryValue.Type != JTokenType.Null)
{
string summaryInstance = ((string)summaryValue);
propertiesInstance.Summary = summaryInstance;
}
JToken valueSequenceElement = ((JToken)propertiesValue["value"]);
if (valueSequenceElement != null && valueSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in valueSequenceElement)
{
string valueKey = ((string)property.Name);
object valueValue = property.Value.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Value.Add(valueKey, valueValue);
}
}
}
}
}
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 test job streams identified by runbook name and stream
/// id. (see http://aka.ms/azureautomationsdk/jobstreamoperations 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='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='jobStreamId'>
/// Required. The job stream id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get job stream operation.
/// </returns>
public async Task<JobStreamGetResponse> GetTestJobStreamAsync(string resourceGroupName, string automationAccount, string runbookName, string jobStreamId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
if (jobStreamId == null)
{
throw new ArgumentNullException("jobStreamId");
}
// 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("runbookName", runbookName);
tracingParameters.Add("jobStreamId", jobStreamId);
TracingAdapter.Enter(invocationId, this, "GetTestJobStreamAsync", 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 + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob/streams/";
url = url + Uri.EscapeDataString(jobStreamId);
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
JobStreamGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobStreamGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JobStream jobStreamInstance = new JobStream();
result.JobStream = jobStreamInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobStreamProperties propertiesInstance = new JobStreamProperties();
jobStreamInstance.Properties = propertiesInstance;
JToken jobStreamIdValue = propertiesValue["jobStreamId"];
if (jobStreamIdValue != null && jobStreamIdValue.Type != JTokenType.Null)
{
string jobStreamIdInstance = ((string)jobStreamIdValue);
propertiesInstance.JobStreamId = jobStreamIdInstance;
}
JToken timeValue = propertiesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
propertiesInstance.Time = timeInstance;
}
JToken streamTypeValue = propertiesValue["streamType"];
if (streamTypeValue != null && streamTypeValue.Type != JTokenType.Null)
{
string streamTypeInstance = ((string)streamTypeValue);
propertiesInstance.StreamType = streamTypeInstance;
}
JToken streamTextValue = propertiesValue["streamText"];
if (streamTextValue != null && streamTextValue.Type != JTokenType.Null)
{
string streamTextInstance = ((string)streamTextValue);
propertiesInstance.StreamText = streamTextInstance;
}
JToken summaryValue = propertiesValue["summary"];
if (summaryValue != null && summaryValue.Type != JTokenType.Null)
{
string summaryInstance = ((string)summaryValue);
propertiesInstance.Summary = summaryInstance;
}
JToken valueSequenceElement = ((JToken)propertiesValue["value"]);
if (valueSequenceElement != null && valueSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in valueSequenceElement)
{
string valueKey = ((string)property.Name);
object valueValue = property.Value.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Value.Add(valueKey, valueValue);
}
}
}
}
}
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 jobs streams identified by job id. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations 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='jobId'>
/// Required. The job Id.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list job stream's stream
/// items operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list job stream operation.
/// </returns>
public async Task<JobStreamListResponse> ListAsync(string resourceGroupName, string automationAccount, Guid jobId, JobStreamListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// 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("jobId", jobId);
tracingParameters.Add("parameters", parameters);
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 + "/jobs/";
url = url + Uri.EscapeDataString(jobId.ToString());
url = url + "/streams";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.Time != null)
{
odataFilter.Add("properties/time ge " + Uri.EscapeDataString(parameters.Time));
}
if (parameters != null && parameters.StreamType != null)
{
odataFilter.Add("properties/streamType eq '" + Uri.EscapeDataString(parameters.StreamType) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
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
JobStreamListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobStreamListResponse();
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))
{
JobStream jobStreamInstance = new JobStream();
result.JobStreams.Add(jobStreamInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobStreamProperties propertiesInstance = new JobStreamProperties();
jobStreamInstance.Properties = propertiesInstance;
JToken jobStreamIdValue = propertiesValue["jobStreamId"];
if (jobStreamIdValue != null && jobStreamIdValue.Type != JTokenType.Null)
{
string jobStreamIdInstance = ((string)jobStreamIdValue);
propertiesInstance.JobStreamId = jobStreamIdInstance;
}
JToken timeValue = propertiesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
propertiesInstance.Time = timeInstance;
}
JToken streamTypeValue = propertiesValue["streamType"];
if (streamTypeValue != null && streamTypeValue.Type != JTokenType.Null)
{
string streamTypeInstance = ((string)streamTypeValue);
propertiesInstance.StreamType = streamTypeInstance;
}
JToken streamTextValue = propertiesValue["streamText"];
if (streamTextValue != null && streamTextValue.Type != JTokenType.Null)
{
string streamTextInstance = ((string)streamTextValue);
propertiesInstance.StreamText = streamTextInstance;
}
JToken summaryValue = propertiesValue["summary"];
if (summaryValue != null && summaryValue.Type != JTokenType.Null)
{
string summaryInstance = ((string)summaryValue);
propertiesInstance.Summary = summaryInstance;
}
JToken valueSequenceElement = ((JToken)propertiesValue["value"]);
if (valueSequenceElement != null && valueSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in valueSequenceElement)
{
string valueKey = ((string)property.Name);
object valueValue2 = property.Value.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Value.Add(valueKey, valueValue2);
}
}
}
}
}
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>
/// Gets the next page of job streams using next link.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list job stream operation.
/// </returns>
public async Task<JobStreamListResponse> 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
JobStreamListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobStreamListResponse();
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))
{
JobStream jobStreamInstance = new JobStream();
result.JobStreams.Add(jobStreamInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobStreamProperties propertiesInstance = new JobStreamProperties();
jobStreamInstance.Properties = propertiesInstance;
JToken jobStreamIdValue = propertiesValue["jobStreamId"];
if (jobStreamIdValue != null && jobStreamIdValue.Type != JTokenType.Null)
{
string jobStreamIdInstance = ((string)jobStreamIdValue);
propertiesInstance.JobStreamId = jobStreamIdInstance;
}
JToken timeValue = propertiesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
propertiesInstance.Time = timeInstance;
}
JToken streamTypeValue = propertiesValue["streamType"];
if (streamTypeValue != null && streamTypeValue.Type != JTokenType.Null)
{
string streamTypeInstance = ((string)streamTypeValue);
propertiesInstance.StreamType = streamTypeInstance;
}
JToken streamTextValue = propertiesValue["streamText"];
if (streamTextValue != null && streamTextValue.Type != JTokenType.Null)
{
string streamTextInstance = ((string)streamTextValue);
propertiesInstance.StreamText = streamTextInstance;
}
JToken summaryValue = propertiesValue["summary"];
if (summaryValue != null && summaryValue.Type != JTokenType.Null)
{
string summaryInstance = ((string)summaryValue);
propertiesInstance.Summary = summaryInstance;
}
JToken valueSequenceElement = ((JToken)propertiesValue["value"]);
if (valueSequenceElement != null && valueSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in valueSequenceElement)
{
string valueKey = ((string)property.Name);
object valueValue2 = property.Value.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Value.Add(valueKey, valueValue2);
}
}
}
}
}
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 a list of test job streams identified by runbook name.
/// (see http://aka.ms/azureautomationsdk/jobstreamoperations 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='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list job stream's stream
/// items operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list job stream operation.
/// </returns>
public async Task<JobStreamListResponse> ListTestJobStreamsAsync(string resourceGroupName, string automationAccount, string runbookName, JobStreamListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// 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("runbookName", runbookName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListTestJobStreamsAsync", 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 + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/testJob/streams";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.Time != null)
{
odataFilter.Add("properties/time ge " + Uri.EscapeDataString(parameters.Time));
}
if (parameters != null && parameters.StreamType != null)
{
odataFilter.Add("properties/streamType eq '" + Uri.EscapeDataString(parameters.StreamType) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
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
JobStreamListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobStreamListResponse();
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))
{
JobStream jobStreamInstance = new JobStream();
result.JobStreams.Add(jobStreamInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobStreamProperties propertiesInstance = new JobStreamProperties();
jobStreamInstance.Properties = propertiesInstance;
JToken jobStreamIdValue = propertiesValue["jobStreamId"];
if (jobStreamIdValue != null && jobStreamIdValue.Type != JTokenType.Null)
{
string jobStreamIdInstance = ((string)jobStreamIdValue);
propertiesInstance.JobStreamId = jobStreamIdInstance;
}
JToken timeValue = propertiesValue["time"];
if (timeValue != null && timeValue.Type != JTokenType.Null)
{
DateTimeOffset timeInstance = ((DateTimeOffset)timeValue);
propertiesInstance.Time = timeInstance;
}
JToken streamTypeValue = propertiesValue["streamType"];
if (streamTypeValue != null && streamTypeValue.Type != JTokenType.Null)
{
string streamTypeInstance = ((string)streamTypeValue);
propertiesInstance.StreamType = streamTypeInstance;
}
JToken streamTextValue = propertiesValue["streamText"];
if (streamTextValue != null && streamTextValue.Type != JTokenType.Null)
{
string streamTextInstance = ((string)streamTextValue);
propertiesInstance.StreamText = streamTextInstance;
}
JToken summaryValue = propertiesValue["summary"];
if (summaryValue != null && summaryValue.Type != JTokenType.Null)
{
string summaryInstance = ((string)summaryValue);
propertiesInstance.Summary = summaryInstance;
}
JToken valueSequenceElement = ((JToken)propertiesValue["value"]);
if (valueSequenceElement != null && valueSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in valueSequenceElement)
{
string valueKey = ((string)property.Name);
object valueValue2 = property.Value.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Value.Add(valueKey, valueValue2);
}
}
}
}
}
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();
}
}
}
}
}
| |
// 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.Runtime.InteropServices.ComTypes;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
public static int GetHRForException(Exception e)
{
return e?.HResult ?? 0;
}
public static int AddRef(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool AreComObjectsAvailableForCleanup() => false;
public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object BindToMoniker(String monikerName)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void CleanupUnusedObjectsInCurrentContext()
{
}
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object CreateWrapperOfType(object o, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int FinalReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetComObjectData(object obj, object key)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetHINSTANCE(Module m)
{
if (m == null)
{
throw new ArgumentNullException(nameof(m));
}
return (IntPtr) (-1);
}
public static IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject(object obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForIUnknown(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForNativeVariant(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetStartComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetEndComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Type GetTypeFromCLSID(Guid clsid)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static string GetTypeInfoName(ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetUniqueObjectForIUnknown(IntPtr unknown)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool IsComObject(object o)
{
if (o == null)
{
throw new ArgumentNullException(nameof(o));
}
return false;
}
public static bool IsTypeVisibleFromCom(Type t)
{
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
return false;
}
public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int Release(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int ReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool SetComObjectData(object obj, object key, object data)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A PCI device
/// First published in XenServer 6.0.
/// </summary>
public partial class PCI : XenObject<PCI>
{
public PCI()
{
}
public PCI(string uuid,
string class_name,
string vendor_name,
string device_name,
XenRef<Host> host,
string pci_id,
List<XenRef<PCI>> dependencies,
Dictionary<string, string> other_config,
string subsystem_vendor_name,
string subsystem_device_name)
{
this.uuid = uuid;
this.class_name = class_name;
this.vendor_name = vendor_name;
this.device_name = device_name;
this.host = host;
this.pci_id = pci_id;
this.dependencies = dependencies;
this.other_config = other_config;
this.subsystem_vendor_name = subsystem_vendor_name;
this.subsystem_device_name = subsystem_device_name;
}
/// <summary>
/// Creates a new PCI from a Proxy_PCI.
/// </summary>
/// <param name="proxy"></param>
public PCI(Proxy_PCI proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PCI.
/// </summary>
public override void UpdateFrom(PCI update)
{
uuid = update.uuid;
class_name = update.class_name;
vendor_name = update.vendor_name;
device_name = update.device_name;
host = update.host;
pci_id = update.pci_id;
dependencies = update.dependencies;
other_config = update.other_config;
subsystem_vendor_name = update.subsystem_vendor_name;
subsystem_device_name = update.subsystem_device_name;
}
internal void UpdateFromProxy(Proxy_PCI proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
class_name = proxy.class_name == null ? null : (string)proxy.class_name;
vendor_name = proxy.vendor_name == null ? null : (string)proxy.vendor_name;
device_name = proxy.device_name == null ? null : (string)proxy.device_name;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
pci_id = proxy.pci_id == null ? null : (string)proxy.pci_id;
dependencies = proxy.dependencies == null ? null : XenRef<PCI>.Create(proxy.dependencies);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
subsystem_vendor_name = proxy.subsystem_vendor_name == null ? null : (string)proxy.subsystem_vendor_name;
subsystem_device_name = proxy.subsystem_device_name == null ? null : (string)proxy.subsystem_device_name;
}
public Proxy_PCI ToProxy()
{
Proxy_PCI result_ = new Proxy_PCI();
result_.uuid = uuid ?? "";
result_.class_name = class_name ?? "";
result_.vendor_name = vendor_name ?? "";
result_.device_name = device_name ?? "";
result_.host = host ?? "";
result_.pci_id = pci_id ?? "";
result_.dependencies = (dependencies != null) ? Helper.RefListToStringArray(dependencies) : new string[] {};
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.subsystem_vendor_name = subsystem_vendor_name ?? "";
result_.subsystem_device_name = subsystem_device_name ?? "";
return result_;
}
/// <summary>
/// Creates a new PCI from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PCI(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PCI
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("class_name"))
class_name = Marshalling.ParseString(table, "class_name");
if (table.ContainsKey("vendor_name"))
vendor_name = Marshalling.ParseString(table, "vendor_name");
if (table.ContainsKey("device_name"))
device_name = Marshalling.ParseString(table, "device_name");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("pci_id"))
pci_id = Marshalling.ParseString(table, "pci_id");
if (table.ContainsKey("dependencies"))
dependencies = Marshalling.ParseSetRef<PCI>(table, "dependencies");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("subsystem_vendor_name"))
subsystem_vendor_name = Marshalling.ParseString(table, "subsystem_vendor_name");
if (table.ContainsKey("subsystem_device_name"))
subsystem_device_name = Marshalling.ParseString(table, "subsystem_device_name");
}
public bool DeepEquals(PCI other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._class_name, other._class_name) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._device_name, other._device_name) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._pci_id, other._pci_id) &&
Helper.AreEqual2(this._dependencies, other._dependencies) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._subsystem_vendor_name, other._subsystem_vendor_name) &&
Helper.AreEqual2(this._subsystem_device_name, other._subsystem_device_name);
}
internal static List<PCI> ProxyArrayToObjectList(Proxy_PCI[] input)
{
var result = new List<PCI>();
foreach (var item in input)
result.Add(new PCI(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PCI server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
PCI.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static PCI get_record(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_record(session.opaque_ref, _pci);
else
return new PCI((Proxy_PCI)session.proxy.pci_get_record(session.opaque_ref, _pci ?? "").parse());
}
/// <summary>
/// Get a reference to the PCI instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PCI> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PCI>.Create(session.proxy.pci_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_uuid(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_uuid(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_uuid(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the class_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_class_name(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_class_name(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_class_name(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the vendor_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_vendor_name(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_vendor_name(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_vendor_name(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the device_name field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_device_name(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_device_name(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_device_name(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the host field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static XenRef<Host> get_host(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_host(session.opaque_ref, _pci);
else
return XenRef<Host>.Create(session.proxy.pci_get_host(session.opaque_ref, _pci ?? "").parse());
}
/// <summary>
/// Get the pci_id field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_pci_id(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_pci_id(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_pci_id(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the dependencies field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static List<XenRef<PCI>> get_dependencies(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_dependencies(session.opaque_ref, _pci);
else
return XenRef<PCI>.Create(session.proxy.pci_get_dependencies(session.opaque_ref, _pci ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static Dictionary<string, string> get_other_config(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_other_config(session.opaque_ref, _pci);
else
return Maps.convert_from_proxy_string_string(session.proxy.pci_get_other_config(session.opaque_ref, _pci ?? "").parse());
}
/// <summary>
/// Get the subsystem_vendor_name field of the given PCI.
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_subsystem_vendor_name(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_subsystem_vendor_name(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_subsystem_vendor_name(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Get the subsystem_device_name field of the given PCI.
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
public static string get_subsystem_device_name(Session session, string _pci)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_subsystem_device_name(session.opaque_ref, _pci);
else
return (string)session.proxy.pci_get_subsystem_device_name(session.opaque_ref, _pci ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pci, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pci_set_other_config(session.opaque_ref, _pci, _other_config);
else
session.proxy.pci_set_other_config(session.opaque_ref, _pci ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given PCI.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pci, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pci_add_to_other_config(session.opaque_ref, _pci, _key, _value);
else
session.proxy.pci_add_to_other_config(session.opaque_ref, _pci ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given PCI. If the key is not in that Map, then do nothing.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pci">The opaque_ref of the given pci</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pci, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pci_remove_from_other_config(session.opaque_ref, _pci, _key);
else
session.proxy.pci_remove_from_other_config(session.opaque_ref, _pci ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the PCIs known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PCI>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_all(session.opaque_ref);
else
return XenRef<PCI>.Create(session.proxy.pci_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PCI Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PCI>, PCI> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pci_get_all_records(session.opaque_ref);
else
return XenRef<PCI>.Create<Proxy_PCI>(session.proxy.pci_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// PCI class name
/// </summary>
public virtual string class_name
{
get { return _class_name; }
set
{
if (!Helper.AreEqual(value, _class_name))
{
_class_name = value;
Changed = true;
NotifyPropertyChanged("class_name");
}
}
}
private string _class_name = "";
/// <summary>
/// Vendor name
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
Changed = true;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name = "";
/// <summary>
/// Device name
/// </summary>
public virtual string device_name
{
get { return _device_name; }
set
{
if (!Helper.AreEqual(value, _device_name))
{
_device_name = value;
Changed = true;
NotifyPropertyChanged("device_name");
}
}
}
private string _device_name = "";
/// <summary>
/// Physical machine that owns the PCI device
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL");
/// <summary>
/// PCI ID of the physical device
/// </summary>
public virtual string pci_id
{
get { return _pci_id; }
set
{
if (!Helper.AreEqual(value, _pci_id))
{
_pci_id = value;
Changed = true;
NotifyPropertyChanged("pci_id");
}
}
}
private string _pci_id = "";
/// <summary>
/// List of dependent PCI devices
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PCI>))]
public virtual List<XenRef<PCI>> dependencies
{
get { return _dependencies; }
set
{
if (!Helper.AreEqual(value, _dependencies))
{
_dependencies = value;
Changed = true;
NotifyPropertyChanged("dependencies");
}
}
}
private List<XenRef<PCI>> _dependencies = new List<XenRef<PCI>>() {};
/// <summary>
/// Additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Subsystem vendor name
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
public virtual string subsystem_vendor_name
{
get { return _subsystem_vendor_name; }
set
{
if (!Helper.AreEqual(value, _subsystem_vendor_name))
{
_subsystem_vendor_name = value;
Changed = true;
NotifyPropertyChanged("subsystem_vendor_name");
}
}
}
private string _subsystem_vendor_name = "";
/// <summary>
/// Subsystem device name
/// First published in XenServer 6.2 SP1 Hotfix 11.
/// </summary>
public virtual string subsystem_device_name
{
get { return _subsystem_device_name; }
set
{
if (!Helper.AreEqual(value, _subsystem_device_name))
{
_subsystem_device_name = value;
Changed = true;
NotifyPropertyChanged("subsystem_device_name");
}
}
}
private string _subsystem_device_name = "";
}
}
| |
using System.Diagnostics;
namespace System.Data.SQLite
{
internal partial class Sqlite3
{
/*
** 2007 August 27
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement mutexes on Btree objects.
** This code really belongs in btree.c. But btree.c is getting too
** big and we want to break it down some. This packaged seemed like
** a good breakout.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "btreeInt.h"
#if !SQLITE_OMIT_SHARED_CACHE
#if SQLITE_THREADSAFE
/*
** Obtain the BtShared mutex associated with B-Tree handle p. Also,
** set BtShared.db to the database handle associated with p and the
** p->locked boolean to true.
*/
static void lockBtreeMutex(Btree *p){
assert( p->locked==0 );
assert( sqlite3_mutex_notheld(p->pBt->mutex) );
assert( sqlite3_mutex_held(p->db->mutex) );
sqlite3_mutex_enter(p->pBt->mutex);
p->pBt->db = p->db;
p->locked = 1;
}
/*
** Release the BtShared mutex associated with B-Tree handle p and
** clear the p->locked boolean.
*/
static void unlockBtreeMutex(Btree *p){
BtShared *pBt = p->pBt;
assert( p->locked==1 );
assert( sqlite3_mutex_held(pBt->mutex) );
assert( sqlite3_mutex_held(p->db->mutex) );
assert( p->db==pBt->db );
sqlite3_mutex_leave(pBt->mutex);
p->locked = 0;
}
/*
** Enter a mutex on the given BTree object.
**
** If the object is not sharable, then no mutex is ever required
** and this routine is a no-op. The underlying mutex is non-recursive.
** But we keep a reference count in Btree.wantToLock so the behavior
** of this interface is recursive.
**
** To avoid deadlocks, multiple Btrees are locked in the same order
** by all database connections. The p->pNext is a list of other
** Btrees belonging to the same database connection as the p Btree
** which need to be locked after p. If we cannot get a lock on
** p, then first unlock all of the others on p->pNext, then wait
** for the lock to become available on p, then relock all of the
** subsequent Btrees that desire a lock.
*/
void sqlite3BtreeEnter(Btree *p){
Btree *pLater;
/* Some basic sanity checking on the Btree. The list of Btrees
** connected by pNext and pPrev should be in sorted order by
** Btree.pBt value. All elements of the list should belong to
** the same connection. Only shared Btrees are on the list. */
assert( p->pNext==0 || p->pNext->pBt>p->pBt );
assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
assert( p->pNext==0 || p->pNext->db==p->db );
assert( p->pPrev==0 || p->pPrev->db==p->db );
assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
/* Check for locking consistency */
assert( !p->locked || p->wantToLock>0 );
assert( p->sharable || p->wantToLock==0 );
/* We should already hold a lock on the database connection */
assert( sqlite3_mutex_held(p->db->mutex) );
/* Unless the database is sharable and unlocked, then BtShared.db
** should already be set correctly. */
assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
if( !p->sharable ) return;
p->wantToLock++;
if( p->locked ) return;
/* In most cases, we should be able to acquire the lock we
** want without having to go throught the ascending lock
** procedure that follows. Just be sure not to block.
*/
if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
p->pBt->db = p->db;
p->locked = 1;
return;
}
/* To avoid deadlock, first release all locks with a larger
** BtShared address. Then acquire our lock. Then reacquire
** the other BtShared locks that we used to hold in ascending
** order.
*/
for(pLater=p->pNext; pLater; pLater=pLater->pNext){
assert( pLater->sharable );
assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
assert( !pLater->locked || pLater->wantToLock>0 );
if( pLater->locked ){
unlockBtreeMutex(pLater);
}
}
lockBtreeMutex(p);
for(pLater=p->pNext; pLater; pLater=pLater->pNext){
if( pLater->wantToLock ){
lockBtreeMutex(pLater);
}
}
}
/*
** Exit the recursive mutex on a Btree.
*/
void sqlite3BtreeLeave(Btree *p){
if( p->sharable ){
assert( p->wantToLock>0 );
p->wantToLock--;
if( p->wantToLock==0 ){
unlockBtreeMutex(p);
}
}
}
#if NDEBUG
/*
** Return true if the BtShared mutex is held on the btree, or if the
** B-Tree is not marked as sharable.
**
** This routine is used only from within assert() statements.
*/
int sqlite3BtreeHoldsMutex(Btree *p){
assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
return (p->sharable==0 || p->locked);
}
#endif
#if SQLITE_OMIT_INCRBLOB
/*
** Enter and leave a mutex on a Btree given a cursor owned by that
** Btree. These entry points are used by incremental I/O and can be
** omitted if that module is not used.
*/
void sqlite3BtreeEnterCursor(BtCursor *pCur){
sqlite3BtreeEnter(pCur->pBtree);
}
void sqlite3BtreeLeaveCursor(BtCursor *pCur){
sqlite3BtreeLeave(pCur->pBtree);
}
#endif //* SQLITE_OMIT_INCRBLOB */
/*
** Enter the mutex on every Btree associated with a database
** connection. This is needed (for example) prior to parsing
** a statement since we will be comparing table and column names
** against all schemas and we do not want those schemas being
** reset out from under us.
**
** There is a corresponding leave-all procedures.
**
** Enter the mutexes in accending order by BtShared pointer address
** to avoid the possibility of deadlock when two threads with
** two or more btrees in common both try to lock all their btrees
** at the same instant.
*/
void sqlite3BtreeEnterAll(sqlite3 db){
int i;
Btree *p;
assert( sqlite3_mutex_held(db->mutex) );
for(i=0; i<db->nDb; i++){
p = db->aDb[i].pBt;
if( p ) sqlite3BtreeEnter(p);
}
}
void sqlite3BtreeLeaveAll(sqlite3 db){
int i;
Btree *p;
assert( sqlite3_mutex_held(db->mutex) );
for(i=0; i<db->nDb; i++){
p = db->aDb[i].pBt;
if( p ) sqlite3BtreeLeave(p);
}
}
/*
** Return true if a particular Btree requires a lock. Return FALSE if
** no lock is ever required since it is not sharable.
*/
int sqlite3BtreeSharable(Btree *p){
return p->sharable;
}
#if NDEBUG
/*
** Return true if the current thread holds the database connection
** mutex and all required BtShared mutexes.
**
** This routine is used inside assert() statements only.
*/
int sqlite3BtreeHoldsAllMutexes(sqlite3 db){
int i;
if( !sqlite3_mutex_held(db->mutex) ){
return 0;
}
for(i=0; i<db->nDb; i++){
Btree *p;
p = db->aDb[i].pBt;
if( p && p->sharable &&
(p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
return 0;
}
}
return 1;
}
#endif //* NDEBUG */
#if NDEBUG
/*
** Return true if the correct mutexes are held for accessing the
** db->aDb[iDb].pSchema structure. The mutexes required for schema
** access are:
**
** (1) The mutex on db
** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
**
** If pSchema is not NULL, then iDb is computed from pSchema and
** db using sqlite3SchemaToIndex().
*/
int sqlite3SchemaMutexHeld(sqlite3 db, int iDb, Schema *pSchema){
Btree *p;
assert( db!=0 );
if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
assert( iDb>=0 && iDb<db->nDb );
if( !sqlite3_mutex_held(db->mutex) ) return 0;
if( iDb==1 ) return 1;
p = db->aDb[iDb].pBt;
assert( p!=0 );
return p->sharable==0 || p->locked==1;
}
#endif //* NDEBUG */
#else //* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
/*
** The following are special cases for mutex enter routines for use
** in single threaded applications that use shared cache. Except for
** these two routines, all mutex operations are no-ops in that case and
** are null #defines in btree.h.
**
** If shared cache is disabled, then all btree mutex routines, including
** the ones below, are no-ops and are null #defines in btree.h.
*/
void sqlite3BtreeEnter(Btree *p){
p->pBt->db = p->db;
}
void sqlite3BtreeEnterAll(sqlite3 db){
int i;
for(i=0; i<db->nDb; i++){
Btree *p = db->aDb[i].pBt;
if( p ){
p->pBt->db = p->db;
}
}
}
#endif //* if SQLITE_THREADSAFE */
#endif //* ifndef SQLITE_OMIT_SHARED_CACHE */
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.ExternalSharingWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdlib.h>
/*
** The charMap() macro maps alphabetic characters into their
** lower-case ASCII equivalent. On ASCII machines, this is just
** an upper-to-lower case map. On EBCDIC machines we also need
** to adjust the encoding. Only alphabetic characters and underscores
** need to be translated.
*/
#if SQLITE_ASCII
//# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
#endif
//#if SQLITE_EBCDIC
//# define charMap(X) ebcdicToAscii[(unsigned char)X]
//const unsigned char ebcdicToAscii[] = {
///* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
// 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
// 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
// 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
// 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
// 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
// 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
//};
//#endif
/*
** The sqlite3KeywordCode function looks up an identifier to determine if
** it is a keyword. If it is a keyword, the token code of that keyword is
** returned. If the input is not a keyword, TK_ID is returned.
**
** The implementation of this routine was generated by a program,
** mkkeywordhash.h, located in the tool subdirectory of the distribution.
** The output of the mkkeywordhash.c program is written into a file
** named keywordhash.h and then included into this source file by
** the #include below.
*/
//#include "keywordhash.h"
/*
** If X is a character that can be used in an identifier then
** IdChar(X) will be true. Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier. For 7-bit characters,
** sqlite3IsIdChar[X] must be 1.
**
** For EBCDIC, the rules are more complex but have the same
** end result.
**
** Ticket #1066. the SQL standard does not allow '$' in the
** middle of identfiers. But many SQL implementations do.
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
#if SQLITE_ASCII
//#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
#endif
//#if SQLITE_EBCDIC
//const char sqlite3IsEbcdicIdChar[] = {
///* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
// 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
//};
//#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
//#endif
/// <summary>
/// Return the length of the token that begins at z[iOffset + 0].
/// Store the token type in *tokenType before returning.
/// </summary>
/// <returns>
/// Length of token
/// </returns>
/// <param name='z'>
/// raw string
/// </param>
/// <param name='iOffset'>
/// Offset.
/// </param>
/// <param name='tokenType'>
/// Token type.
/// </param>
static int sqlite3GetToken(string z, int iOffset, ref int tokenType)
{
int i;
byte c = 0;
switch (z[iOffset + 0])
{
case ' ':
case '\t':
case '\n':
case '\f':
case '\r':
{
testcase(z[iOffset + 0] == ' ');
testcase(z[iOffset + 0] == '\t');
testcase(z[iOffset + 0] == '\n');
testcase(z[iOffset + 0] == '\f');
testcase(z[iOffset + 0] == '\r');
for (i = 1; z.Length > iOffset + i && sqlite3Isspace(z[iOffset + i]); i++)
{
}
tokenType = TK_SPACE;
return i;
}
case '-':
{
if (z.Length > iOffset + 1 && z[iOffset + 1] == '-')
{
/* IMP: R-15891-05542 -- syntax diagram for comments */
for (i = 2; z.Length > iOffset + i && (c = (byte)z[iOffset + i]) != 0 && c != '\n'; i++)
{
}
tokenType = TK_SPACE; /* IMP: R-22934-25134 */
return i;
}
tokenType = TK_MINUS;
return 1;
}
case '(':
{
tokenType = TK_LP;
return 1;
}
case ')':
{
tokenType = TK_RP;
return 1;
}
case ';':
{
tokenType = TK_SEMI;
return 1;
}
case '+':
{
tokenType = TK_PLUS;
return 1;
}
case '*':
{
tokenType = TK_STAR;
return 1;
}
case '/':
{
if (iOffset + 2 >= z.Length || z[iOffset + 1] != '*')
{
tokenType = TK_SLASH;
return 1;
}
/* IMP: R-15891-05542 -- syntax diagram for comments */
for (i = 3, c = (byte)z[iOffset + 2]; iOffset + i < z.Length && (c != '*' || (z[iOffset + i] != '/') && (c != 0)); i++)
{
c = (byte)z[iOffset + i];
}
if (iOffset + i == z.Length)
c = 0;
if (c != 0)
i++;
tokenType = TK_SPACE; /* IMP: R-22934-25134 */
return i;
}
case '%':
{
tokenType = TK_REM;
return 1;
}
case '=':
{
tokenType = TK_EQ;
return 1 + (z[iOffset + 1] == '=' ? 1 : 0);
}
case '<':
{
if ((c = (byte)z[iOffset + 1]) == '=')
{
tokenType = TK_LE;
return 2;
}
else if (c == '>')
{
tokenType = TK_NE;
return 2;
}
else if (c == '<')
{
tokenType = TK_LSHIFT;
return 2;
}
else
{
tokenType = TK_LT;
return 1;
}
}
case '>':
{
if (z.Length > iOffset + 1 && (c = (byte)z[iOffset + 1]) == '=')
{
tokenType = TK_GE;
return 2;
}
else if (c == '>')
{
tokenType = TK_RSHIFT;
return 2;
}
else
{
tokenType = TK_GT;
return 1;
}
}
case '!':
{
if (z[iOffset + 1] != '=')
{
tokenType = TK_ILLEGAL;
return 2;
}
else
{
tokenType = TK_NE;
return 2;
}
}
case '|':
{
if (z[iOffset + 1] != '|')
{
tokenType = TK_BITOR;
return 1;
}
else
{
tokenType = TK_CONCAT;
return 2;
}
}
case ',':
{
tokenType = TK_COMMA;
return 1;
}
case '&':
{
tokenType = TK_BITAND;
return 1;
}
case '~':
{
tokenType = TK_BITNOT;
return 1;
}
case '`':
case '\'':
case '"':
{
int delim = z[iOffset + 0];
testcase(delim == '`');
testcase(delim == '\'');
testcase(delim == '"');
for (i = 1; (iOffset + i) < z.Length && (c = (byte)z[iOffset + i]) != 0; i++)
{
if (c == delim)
{
if (z.Length > iOffset + i + 1 && z[iOffset + i + 1] == delim)
{
i++;
}
else
{
break;
}
}
}
if ((iOffset + i == z.Length && c != delim) || z[iOffset + i] != delim)
{
tokenType = TK_ILLEGAL;
return i + 1;
}
if (c == '\'')
{
tokenType = TK_STRING;
return i + 1;
}
else if (c != 0)
{
tokenType = TK_ID;
return i + 1;
}
else
{
tokenType = TK_ILLEGAL;
return i;
}
}
case '.':
{
#if !SQLITE_OMIT_FLOATING_POINT
if (!sqlite3Isdigit(z[iOffset + 1]))
#endif
{
tokenType = TK_DOT;
return 1;
}
/* If the next character is a digit, this is a floating point
** number that begins with ".". Fall thru into the next case */
goto case '0';
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
testcase(z[iOffset] == '0');
testcase(z[iOffset] == '1');
testcase(z[iOffset] == '2');
testcase(z[iOffset] == '3');
testcase(z[iOffset] == '4');
testcase(z[iOffset] == '5');
testcase(z[iOffset] == '6');
testcase(z[iOffset] == '7');
testcase(z[iOffset] == '8');
testcase(z[iOffset] == '9');
tokenType = TK_INTEGER;
for (i = 0; z.Length > iOffset + i && sqlite3Isdigit(z[iOffset + i]); i++)
{
}
#if !SQLITE_OMIT_FLOATING_POINT
if (z.Length > iOffset + i && z[iOffset + i] == '.')
{
i++;
while (z.Length > iOffset + i && sqlite3Isdigit(z[iOffset + i]))
{
i++;
}
tokenType = TK_FLOAT;
}
if (z.Length > iOffset + i + 1 && (z[iOffset + i] == 'e' || z[iOffset + i] == 'E') &&
(sqlite3Isdigit(z[iOffset + i + 1])
|| z.Length > iOffset + i + 2 && ((z[iOffset + i + 1] == '+' || z[iOffset + i + 1] == '-') && sqlite3Isdigit(z[iOffset + i + 2]))
)
)
{
i += 2;
while (z.Length > iOffset + i && sqlite3Isdigit(z[iOffset + i]))
{
i++;
}
tokenType = TK_FLOAT;
}
#endif
while (iOffset + i < z.Length && IdChar((byte)z[iOffset + i]))
{
tokenType = TK_ILLEGAL;
i++;
}
return i;
}
case '[':
{
for (i = 1, c = (byte)z[iOffset + 0]; c != ']' && (iOffset + i) < z.Length && (c = (byte)z[iOffset + i]) != 0; i++)
{
}
tokenType = c == ']' ? TK_ID : TK_ILLEGAL;
return i;
}
case '?':
{
tokenType = TK_VARIABLE;
for (i = 1; z.Length > iOffset + i && sqlite3Isdigit(z[iOffset + i]); i++)
{
}
return i;
}
case '#':
{
for (i = 1; z.Length > iOffset + i && sqlite3Isdigit(z[iOffset + i]); i++)
{
}
if (i > 1)
{
/* Parameters of the form #NNN (where NNN is a number) are used
** internally by sqlite3NestedParse. */
tokenType = TK_REGISTER;
return i;
}
/* Fall through into the next case if the '#' is not followed by
** a digit. Try to match #AAAA where AAAA is a parameter name. */
goto case ':';
}
#if !SQLITE_OMIT_TCL_VARIABLE
case '$':
#endif
case '@': /* For compatibility with MS SQL Server */
case ':':
{
int n = 0;
testcase(z[iOffset + 0] == '$');
testcase(z[iOffset + 0] == '@');
testcase(z[iOffset + 0] == ':');
tokenType = TK_VARIABLE;
for (i = 1; z.Length > iOffset + i && (c = (byte)z[iOffset + i]) != 0; i++)
{
if (IdChar(c))
{
n++;
#if !SQLITE_OMIT_TCL_VARIABLE
}
else if (c == '(' && n > 0)
{
do
{
i++;
} while ((iOffset + i) < z.Length && (c = (byte)z[iOffset + i]) != 0 && !sqlite3Isspace(c) && c != ')');
if (c == ')')
{
i++;
}
else
{
tokenType = TK_ILLEGAL;
}
break;
}
else if (c == ':' && z[iOffset + i + 1] == ':')
{
i++;
#endif
}
else
{
break;
}
}
if (n == 0)
tokenType = TK_ILLEGAL;
return i;
}
#if !SQLITE_OMIT_BLOB_LITERAL
case 'x':
case 'X':
{
testcase(z[iOffset + 0] == 'x');
testcase(z[iOffset + 0] == 'X');
if (z.Length > iOffset + 1 && z[iOffset + 1] == '\'')
{
tokenType = TK_BLOB;
for (i = 2; z.Length > iOffset + i && sqlite3Isxdigit(z[iOffset + i]); i++)
{
}
if (iOffset + i == z.Length || z[iOffset + i] != '\'' || i % 2 != 0)
{
tokenType = TK_ILLEGAL;
while (z.Length > iOffset + i && z[iOffset + i] != '\'')
{
i++;
}
}
if (z.Length > iOffset + i)
i++;
return i;
}
goto default;
/* Otherwise fall through to the next case */
}
#endif
default:
{
if (!IdChar((byte)z[iOffset]))
{
break;
}
for (i = 1; i < z.Length - iOffset && IdChar((byte)z[iOffset + i]); i++)
{
}
tokenType = keywordCode(z, iOffset, i);
return i;
}
}
tokenType = TK_ILLEGAL;
return 1;
}
/// <summary>
/// Run the parser on the given SQL string. The parser structure is
/// passed in. An SQLITE_ status code is returned. If an error occurs
/// then an and attempt is made to write an error message into
/// memory obtained from sqlite3_malloc() and to make pzErrMsg point to that
/// error message.
/// </summary>
/// <returns>
/// An SQLITE_ status code
/// </returns>
/// <param name='pParse'>
/// P parse.
/// </param>
/// <param name='zSql'>
/// sql.
/// </param>
/// <param name='pzErrMsg'>
/// Pz error message.
/// </param>
static int sqlite3RunParser(Parse pParse, string zSql, ref string pzErrMsg)
{
int nErr = 0; /* Number of errors encountered */
int i; /* Loop counter */
yyParser pEngine; /* The LEMON-generated LALR(1) parser */
int tokenType = 0; /* type of the next token */
int lastTokenParsed = -1; /* type of the previous token */
byte enableLookaside; /* Saved value of db->lookaside.bEnabled */
sqlite3 db = pParse.db; /* The database connection */
int mxSqlLen; /* Max length of an SQL string */
mxSqlLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH];
if (db.activeVdbeCnt == 0)
{
db.u1.isInterrupted = false;
}
pParse.rc = SQLITE_OK;
pParse.zTail = new StringBuilder(zSql);
i = 0;
Debug.Assert(pzErrMsg != null);
pEngine = sqlite3ParserAlloc();
Debug.Assert(pParse.pNewTable == null);
Debug.Assert(pParse.pNewTrigger == null);
Debug.Assert(pParse.nVar == 0);
Debug.Assert(pParse.nzVar == 0);
Debug.Assert(pParse.azVar == null);
enableLookaside = db.lookaside.bEnabled;
if (db.lookaside.pStart != 0)
db.lookaside.bEnabled = 1;
while (i < zSql.Length)
{
Debug.Assert(i >= 0);
pParse.sLastToken.n = sqlite3GetToken(zSql, i, ref tokenType);
pParse.sLastToken.z = zSql.Substring(i);
i += pParse.sLastToken.n;
if (i > mxSqlLen)
{
pParse.rc = SQLITE_TOOBIG;
break;
}
switch (tokenType)
{
case TK_SPACE:
{
if (db.u1.isInterrupted)
{
sqlite3ErrorMsg(pParse, "interrupt");
pParse.rc = SQLITE_INTERRUPT;
goto abort_parse;
}
break;
}
case TK_ILLEGAL:
{
sqlite3DbFree(db, ref pzErrMsg);
pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
(object)pParse.sLastToken);
nErr++;
goto abort_parse;
}
case TK_SEMI:
{
//pParse.zTail = new StringBuilder(zSql.Substring( i,zSql.Length-i ));
/* Fall thru into the default case */
goto default;
}
default:
{
sqlite3Parser(pEngine, tokenType, pParse.sLastToken, pParse);
lastTokenParsed = tokenType;
if (pParse.rc != SQLITE_OK)
{
goto abort_parse;
}
break;
}
}
}
abort_parse:
pParse.zTail = new StringBuilder(zSql.Length <= i ? "" : zSql.Substring(i, zSql.Length - i));
if (zSql.Length >= i && nErr == 0 && pParse.rc == SQLITE_OK)
{
if (lastTokenParsed != TK_SEMI)
{
sqlite3Parser(pEngine, TK_SEMI, pParse.sLastToken, pParse);
}
sqlite3Parser(pEngine, 0, pParse.sLastToken, pParse);
}
#if YYTRACKMAXSTACKDEPTH
sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
sqlite3ParserStackPeak(pEngine)
);
#endif //* YYDEBUG */
sqlite3ParserFree(pEngine, null);//sqlite3_free );
db.lookaside.bEnabled = enableLookaside;
//if ( db.mallocFailed != 0 )
//{
// pParse.rc = SQLITE_NOMEM;
//}
if (pParse.rc != SQLITE_OK && pParse.rc != SQLITE_DONE && pParse.zErrMsg == "")
{
sqlite3SetString(ref pParse.zErrMsg, db, sqlite3ErrStr(pParse.rc));
}
//assert( pzErrMsg!=0 );
if (pParse.zErrMsg != null)
{
pzErrMsg = pParse.zErrMsg;
sqlite3_log(pParse.rc, "%s", pzErrMsg);
pParse.zErrMsg = "";
nErr++;
}
if (pParse.pVdbe != null && pParse.nErr > 0 && pParse.nested == 0)
{
sqlite3VdbeDelete(ref pParse.pVdbe);
pParse.pVdbe = null;
}
#if !SQLITE_OMIT_SHARED_CACHE
if ( pParse.nested == 0 )
{
sqlite3DbFree( db, ref pParse.aTableLock );
pParse.aTableLock = null;
pParse.nTableLock = 0;
}
#endif
#if !SQLITE_OMIT_VIRTUALTABLE
pParse.apVtabLock = null;//sqlite3_free( pParse.apVtabLock );
#endif
if (!IN_DECLARE_VTAB(pParse))
{
/* If the pParse.declareVtab flag is set, do not delete any table
** structure built up in pParse.pNewTable. The calling code (see vtab.c)
** will take responsibility for freeing the Table structure.
*/
sqlite3DeleteTable(db, ref pParse.pNewTable);
}
#if !SQLITE_OMIT_TRIGGER
sqlite3DeleteTrigger(db, ref pParse.pNewTrigger);
#endif
//for ( i = pParse.nzVar - 1; i >= 0; i-- )
// sqlite3DbFree( db, pParse.azVar[i] );
sqlite3DbFree(db, ref pParse.azVar);
sqlite3DbFree(db, ref pParse.aAlias);
while (pParse.pAinc != null)
{
AutoincInfo p = pParse.pAinc;
pParse.pAinc = p.pNext;
sqlite3DbFree(db, ref p);
}
while (pParse.pZombieTab != null)
{
Table p = pParse.pZombieTab;
pParse.pZombieTab = p.pNextZombie;
sqlite3DeleteTable(db, ref p);
}
if (nErr > 0 && pParse.rc == SQLITE_OK)
{
pParse.rc = SQLITE_ERROR;
}
return nErr;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved.
// Licensed under the MIT License. Please see the LICENSE file in the project root for full license information.
// --------------------------------------------------------------------------------------------------------------------
using LeadPipe.Net.FiniteStateMachine;
using Moq;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Linq;
namespace LeadPipe.Net.Tests.FiniteStateMachineTests
{
/// <summary>
/// PerformTransition method tests.
/// </summary>
[TestFixture]
public class PerformTransitionShould
{
/// <summary>
/// The closed state.
/// </summary>
private IFiniteState closedState;
/// <summary>
/// The close transition.
/// </summary>
private IFiniteStateTransition closeTransition;
/// <summary>
/// The machine.
/// </summary>
private FiniteStateMachine.FiniteStateMachine machine;
/// <summary>
/// The open state.
/// </summary>
private IFiniteState openState;
/// <summary>
/// The open transition.
/// </summary>
private IFiniteStateTransition openTransition;
/// <summary>
/// The start transition.
/// </summary>
private IFiniteStateTransition startTransition;
/// <summary>
/// Tests to make sure that state changes are captured in history.
/// </summary>
[Test]
public void AddEntriesToHistory()
{
// Act
this.machine.PerformTransition(this.closeTransition, "Close 1");
this.machine.PerformTransition(this.openTransition, "Open 2");
this.machine.PerformTransition(this.closeTransition, "Close 3");
this.machine.PerformTransition(this.openTransition, "Open 4");
this.machine.PerformTransition(this.closeTransition, "Close 5");
this.machine.PerformTransition(this.openTransition, "Open 6");
this.machine.History.Entries.ToList().ForEach(x => Debug.WriteLine(string.Format("{0}-{1}: {2} ({3}), {4}", x.EntryNumber, x.EntryDate, x.StateCode, x.ReasonCode, x.Comments)));
// Assert
Assert.IsTrue(this.machine.History.Entries.Count() == 7);
}
/// <summary>
/// Tests to make sure that the current state changes when the transition is available.
/// </summary>
[Test]
public void ChangeCurrentStateGivenAvailableTransition()
{
// Act
this.machine.PerformTransition(this.closeTransition);
// Assert
Assert.IsTrue(this.machine.CurrentState.Name.Equals("Closed"));
}
/// <summary>
/// Tests to make sure that the current state changes when using a transition with a delegate.
/// </summary>
[Test]
public void ChangeCurrentStateGivenTransitionWithDelegate()
{
// Arrange
this.openState.RemoveTransition(this.closeTransition);
this.closeTransition = new FiniteStateTransition(
2,
"Close",
new FiniteStateMachineTransitionReason("2", "Closed"),
this.closedState,
() => this.closedState);
this.openState.RegisterTransition(this.closeTransition);
// Act
this.machine.PerformTransition(this.closeTransition);
// Assert
Assert.IsTrue(this.machine.CurrentState.Name.Equals("Closed"));
}
/// <summary>
/// Tests to make sure that the current state does not change if the transition says it can't transition via delegate.
/// </summary>
[Test]
public void NotChangeStateGivenTransitionCanTransitionDelegateReturnsFalse()
{
// Arrange
this.openState.RemoveTransition(this.closeTransition);
this.closeTransition = new FiniteStateTransition(
2,
"Close",
new FiniteStateMachineTransitionReason("2", "Closed"),
this.closedState,
() => this.closedState,
() => false);
this.openState.RegisterTransition(this.closeTransition);
// Act & Assert
Assert.Throws<ApplicationException>(() => this.machine.PerformTransition(this.closeTransition));
}
/// <summary>
/// Tests to make sure that the current state does not change if the transition says it can't transition.
/// </summary>
[Test]
public void NotChangeStateGivenTransitionCanTransitionReturnsFalse()
{
// Arrange
var mock = new Mock<IFiniteStateTransition>();
mock.Setup(x => x.Name).Returns("AlwaysFalse");
mock.Setup(x => x.Reason).Returns(new FiniteStateMachineTransitionReason("5", "Just Testing"));
mock.Setup(x => x.EndState).Returns(this.closedState);
mock.Setup(x => x.CanTransition()).Returns(false);
this.openState.RemoveTransition(this.closeTransition);
this.openState.RegisterTransition(mock.Object);
// Act
Assert.Throws<ApplicationException>(() => this.machine.PerformTransition(mock.Object));
}
/// <summary>
/// Tests to make sure that an exception is thrown when the transition is null.
/// </summary>
[Test]
[Ignore("Currently broken due to the generic implementation.")]
public void ThrowExceptionGivenNullTransition()
{
// Act
Assert.Throws<ArgumentNullException>(() => this.machine.PerformTransition((FiniteStateTransition)null));
}
/// <summary>
/// Tests to make sure that an exception is thrown when the transition returns a state that isn't registered.
/// </summary>
[Test]
public void ThrowExceptionGivenTransitionReturnsUnregisteredState()
{
// Arrange
var unregisteredState = new FiniteState(99, "Unregistered");
this.openState.RemoveTransition(this.closeTransition);
this.closeTransition = new FiniteStateTransition(
2,
"Close",
new FiniteStateMachineTransitionReason("2", "Closed"),
unregisteredState,
() => unregisteredState);
this.openState.RegisterTransition(this.closeTransition);
// Act
Assert.Throws<StateNotRegisteredException>(() => this.machine.PerformTransition(this.closeTransition));
}
/// <summary>
/// Tests to make sure that an exception is thrown when the transition is not available.
/// </summary>
[Test]
public void ThrowExceptionGivenUnavailableTransition()
{
// Act
Assert.Throws<TransitionNotAvailableException>(() => this.machine.PerformTransition(this.openTransition));
}
/// <summary>
/// Runs before each test.
/// </summary>
[SetUp]
public void TestSetup()
{
// Create our states...
this.openState = new FiniteState(0, "Open");
this.closedState = new FiniteState(1, "Closed");
// Create our transitions...
this.startTransition = new FiniteStateTransition(0, "New", new FiniteStateMachineTransitionReason("0", "New"), this.openState);
this.openTransition = new FiniteStateTransition(1, "Open", new FiniteStateMachineTransitionReason("1", "Opened"), this.closedState, this.openState);
this.closeTransition = new FiniteStateTransition(2, "Close", new FiniteStateMachineTransitionReason("2", "Closed"), this.openState, this.closedState);
// Add our transitions to our states...
this.openState.RegisterTransition(this.closeTransition);
this.closedState.RegisterTransition(this.openTransition);
// Create our machine...
this.machine = new FiniteStateMachine.FiniteStateMachine(this.startTransition);
// Add our states...
this.machine.RegisterState(this.openState);
this.machine.RegisterState(this.closedState);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Collections.Generic;
namespace System.Collections
{
/// <summary>
/// A generic interface providing a generically typed indexer. Allows passing of object instances implementing interface
/// without explicit knowledge of the object implementation specifics.
/// </summary>
/// <typeparam name="TKey">Generic type of the key for the indexed object instance.</typeparam>
/// <typeparam name="TValue">Generic type for the value in the indexed object instance.</typeparam>
#if !COREINTERNAL
public
#endif
interface IDictionaryIndexer<TKey, TValue> : IIndexer<TKey, TValue>
{
/// <summary>
/// Clears this instance.
/// </summary>
void Clear();
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
int Count { get; }
/// <summary>
/// Determines whether the specified key exists.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key exists; otherwise, <c>false</c>.
/// </returns>
bool ContainsKey(TKey key);
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
bool Remove(TKey key);
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
bool TryGetValue(TKey key, out TValue value);
/// <summary>
/// Tries the get value at.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
bool TryGetValueAt(int index, out TValue value);
/// <summary>
/// Gets the ICollection instance containing the Keys for the collection.
/// </summary>
/// <value>The key enum.</value>
ICollection<TKey> Keys { get; }
/// <summary>
/// Gets the ICollection instance containing the Values for the collection.
/// </summary>
/// <value>The value enum.</value>
ICollection<TValue> Values { get; }
}
/// <summary>
/// Provides dictionary-based collection and indexer functionality using generic types.
/// </summary>
/// <typeparam name="TKey">Generic type of a key</typeparam>
/// <typeparam name="TValue">Generic type of a value in the collection</typeparam>
#if !COREINTERNAL
public
#endif
class DictionaryIndexer<TKey, TValue> : IDictionaryIndexer<TKey, TValue>
{
/// <summary>
/// Protected Member variable that exposes the the IDictionary instance used as the underlying storage object for this type.
/// </summary>
protected IDictionary<TKey, TValue> _dictionary;
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryIndexer<TKey, TValue>"/> class.
/// </summary>
public DictionaryIndexer()
: this(new Dictionary<TKey, TValue>(), null) { }
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryIndexer<TKey, TValue>"/> class.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
public DictionaryIndexer(IDictionary<TKey, TValue> dictionary)
: this(dictionary, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryIndexer<TKey, TValue>"/> class.
/// </summary>
/// <param name="dictionary">The hash.</param>
/// <param name="factory">The factory.</param>
public DictionaryIndexer(IDictionary<TKey, TValue> dictionary, Func<TKey, TValue> factory)
{
_dictionary = dictionary;
Factory = factory;
}
/// <summary>
/// Gets or sets the value (of generic parameter type TValue) associated with the specified key.
/// </summary>
/// <value>Value associate with key provided.</value>
public virtual TValue this[TKey key]
{
get
{
if (_dictionary == null)
throw new InvalidOperationException("_hash is null");
TValue value;
if (_dictionary.TryGetValue(key, out value))
return value;
if (Factory != null)
{
_dictionary.Add(key, value = Factory(key));
return value;
}
throw new ArgumentException(string.Format(Local.UndefinedItemAB, "Dictionary", key), "key");
}
set
{
if (_dictionary == null)
throw new InvalidOperationException("_hash is null");
_dictionary[key] = value;
}
}
/// <summary>
/// Allows creation of instances of the type originally associated with keys used by this generic collection class.
/// </summary>
public Func<TKey, TValue> Factory { get; private set; }
/// <summary>
/// Clears this instance.
/// </summary>
public virtual void Clear()
{
if (_dictionary != null)
_dictionary.Clear();
}
/// <summary>
/// Gets the count of the items in collection.
/// </summary>
/// <value>The count.</value>
public virtual int Count
{
get { return (_dictionary != null ? _dictionary.Count : 0); }
}
/// <summary>
/// Exposes the the IDictionary instance used as the underlying storage object for this type.
/// </summary>
/// <value>
/// The hash.
/// </value>
public IDictionary<TKey, TValue> Dictionary
{
get { return _dictionary; }
}
/// <summary>
/// Gets the generic <typeparamref name="TValue"/> value associated with the specified <c>key</c>.
/// </summary>
/// <param name="index">The index whose value to get or set.</param>
/// <returns></returns>
/// <value>Returns the generic <typeparamref name="TValue"/> value associated with the specified <c>key</c>.</value>
public virtual TValue GetValueAt(int index)
{
if (_dictionary == null)
throw new InvalidOperationException("_dictionary is null");
if (index >= _dictionary.Count)
throw new ArgumentOutOfRangeException("key");
//return m_hash.GetValue(index);
throw new NotSupportedException();
}
/// <summary>
/// Gets the generic <typeparamref name="TValue"/> value associated with the specified <c>key</c>.
/// </summary>
/// <param name="key">The key whose value to get or set.</param>
/// <param name="defaultValue">The default value to return if no value is found associated with <c>key</c>.</param>
/// <returns></returns>
/// <value>Returns the generic <typeparamref name="TValue"/> value associated with the specified <c>key</c>.</value>
public virtual TValue GetValue(TKey key, TValue defaultValue)
{
if (_dictionary == null)
throw new InvalidOperationException("_hash is null");
TValue value = _dictionary[key];
if (value != null)
return value;
throw new ArgumentNullException(string.Format(Local.UndefinedKeyA, key), "key");
}
/// <summary>
/// Determines whether the item in collection with specified key exists.
/// </summary>
/// <param name="key">The key to check.</param>
/// <returns>
/// <c>true</c> if the specified item exists; otherwise, <c>false</c>.
/// </returns>
public virtual bool ContainsKey(TKey key)
{
return (_dictionary != null ? _dictionary.ContainsKey(key) : false);
}
/// <summary>
/// Removes the item with the specified key.
/// </summary>
/// <param name="key">The key to use.</param>
/// <returns></returns>
public virtual bool Remove(TKey key)
{
return (_dictionary != null ? _dictionary.Remove(key) : false);
}
/// <summary>
/// Return an instance of <see cref="System.Collections.Generic.ICollection{TKey}"/> representing the collection of
/// keys in the indexed collection.
/// </summary>
/// <value>
/// The <see cref="System.Collections.Generic.ICollection{TKey}"/> instance containing the collection of keys.
/// </value>
public virtual ICollection<TKey> Keys
{
get { return (_dictionary != null ? _dictionary.Keys : null); }
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public virtual bool TryGetValue(TKey key, out TValue value)
{
if (_dictionary != null)
return _dictionary.TryGetValue(key, out value);
value = default(TValue);
return false;
}
/// <summary>
/// Tries the get value at.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public virtual bool TryGetValueAt(int index, out TValue value)
{
value = default(TValue);
return false;
}
/// <summary>
/// Return an instance of <see cref="System.Collections.Generic.ICollection{TValue}"/> representing the collection of
/// values in the indexed collection.
/// </summary>
/// <value>
/// The <see cref="System.Collections.Generic.ICollection{TValue}"/> instance containing the collection of values.
/// </value>
public virtual ICollection<TValue> Values
{
get { return (_dictionary != null ? _dictionary.Values : null); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
namespace NQuery
{
/// <summary>
/// Represents an element in an execution plan of <see cref="Query"/>.
/// </summary>
public sealed class ShowPlanElement : ICustomTypeDescriptor
{
private ShowPlanOperator _operator;
private ShowPlanPropertyCollection _properties;
private ShowPlanElementCollection _children;
private PathElement _root = new PathElement();
internal ShowPlanElement(ShowPlanOperator op, IList<ShowPlanProperty> properties, params ShowPlanElement[] children)
: this(op, properties, (IList<ShowPlanElement>)children)
{
}
internal ShowPlanElement(ShowPlanOperator op, IList<ShowPlanProperty> properties, IList<ShowPlanElement> children)
{
_operator = op;
_properties = new ShowPlanPropertyCollection(properties);
_children = new ShowPlanElementCollection(children);
BuildPathElementRoot();
}
/// <summary>
/// Gets the physical operator represented by this node.
/// </summary>
public ShowPlanOperator Operator
{
get { return _operator; }
}
/// <summary>
/// Gets a collection of properties representing the configuration of this node.
/// </summary>
public ShowPlanPropertyCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Gets a collection with all children of this execution plan node.
/// </summary>
public ShowPlanElementCollection Children
{
get { return _children; }
}
#region Property Grid Magic
private void BuildPathElementRoot()
{
Dictionary<string, PathElement> propertyDictionary = new Dictionary<string, PathElement>();
foreach (ShowPlanProperty planProperty in _properties)
{
string currentPath = null;
PathElement property = _root;
foreach (string pathPart in planProperty.PathElements)
{
if (currentPath == null)
currentPath = pathPart;
else
currentPath = currentPath + "." + pathPart;
PathElement currentProperty;
if (!propertyDictionary.TryGetValue(currentPath, out currentProperty))
{
currentProperty = new PathElement();
currentProperty.Name = pathPart;
property.Children.Add(currentProperty);
propertyDictionary.Add(currentPath, currentProperty);
}
property = currentProperty;
}
property.Value = planProperty.Value;
}
}
private class PathElementPropertyDescriptor : PropertyDescriptor
{
private PathElement _pathElement;
public PathElementPropertyDescriptor(PathElement pathElement)
: base(pathElement.Name, new Attribute[0])
{
_pathElement = pathElement;
}
public override bool CanResetValue(object component)
{
return false;
}
public override object GetValue(object component)
{
if (_pathElement.Children.Count == 0)
return _pathElement.Value;
return _pathElement;
}
public override void ResetValue(object component)
{
}
public override void SetValue(object component, object value)
{
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override Type ComponentType
{
get { return typeof(PathElement); }
}
public override bool IsReadOnly
{
get { return true; }
}
public override Type PropertyType
{
get
{
if (_pathElement.Children.Count == 0)
return typeof (string);
return typeof (PathElement);
}
}
}
private class PathElementTypeConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
{
if (destinationType == typeof(string))
{
PathElement propertyTable = (PathElement) value;
return propertyTable.Value;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
[TypeConverter(typeof(PathElementTypeConverter))]
private class PathElement : ICustomTypeDescriptor
{
public string Name;
public string Value;
public List<PathElement> Children = new List<PathElement>();
#region ICustomTypeDescriptor Implementation
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public string GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return null;
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public PropertyDescriptorCollection GetProperties()
{
return GetProperties(new Attribute[0]);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
List<PathElementPropertyDescriptor> customProperties = new List<PathElementPropertyDescriptor>();
foreach (PathElement child in Children)
{
PathElementPropertyDescriptor showPlanPropertyDescriptor = new PathElementPropertyDescriptor(child);
customProperties.Add(showPlanPropertyDescriptor);
}
return new PropertyDescriptorCollection(customProperties.ToArray());
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
#region ICustomTypeDescriptor Implementation
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return _root.GetAttributes();
}
string ICustomTypeDescriptor.GetClassName()
{
return Resources.ShowPlanElemenClassName;
}
string ICustomTypeDescriptor.GetComponentName()
{
return _operator.ToString();
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return _root.GetConverter();
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return _root.GetDefaultEvent();
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return _root.GetDefaultProperty();
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return _root.GetEditor(editorBaseType);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return _root.GetEvents();
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return _root.GetEvents(attributes);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return _root.GetProperties();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return _root.GetProperties(attributes);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return _root.GetPropertyOwner(pd);
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.ContentManagement;
using Orchard.Core.Settings.Models;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Users.Services;
using Orchard.Users.ViewModels;
using Orchard.Utility.Extensions;
namespace Orchard.Users.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly IMembershipService _membershipService;
private readonly IUserService _userService;
private readonly IUserEventHandler _userEventHandlers;
private readonly ISiteService _siteService;
public AdminController(
IOrchardServices services,
IMembershipService membershipService,
IUserService userService,
IShapeFactory shapeFactory,
IUserEventHandler userEventHandlers,
ISiteService siteService) {
Services = services;
_membershipService = membershipService;
_userService = userService;
_userEventHandlers = userEventHandlers;
_siteService = siteService;
T = NullLocalizer.Instance;
Shape = shapeFactory;
}
dynamic Shape { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(UserIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to list users")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new UserIndexOptions();
var users = Services.ContentManager
.Query<UserPart, UserPartRecord>();
switch (options.Filter) {
case UsersFilter.Approved:
users = users.Where(u => u.RegistrationStatus == UserStatus.Approved);
break;
case UsersFilter.Pending:
users = users.Where(u => u.RegistrationStatus == UserStatus.Pending);
break;
case UsersFilter.EmailPending:
users = users.Where(u => u.EmailStatus == UserStatus.Pending);
break;
}
if(!string.IsNullOrWhiteSpace(options.Search)) {
users = users.Where(u => u.UserName.Contains(options.Search) || u.Email.Contains(options.Search));
}
var pagerShape = Shape.Pager(pager).TotalItemCount(users.Count());
switch (options.Order) {
case UsersOrder.Name:
users = users.OrderBy(u => u.UserName);
break;
case UsersOrder.Email:
users = users.OrderBy(u => u.Email);
break;
case UsersOrder.CreatedUtc:
users = users.OrderBy(u => u.CreatedUtc);
break;
case UsersOrder.LastLoginUtc:
users = users.OrderBy(u => u.LastLoginUtc);
break;
}
var results = users
.Slice(pager.GetStartIndex(), pager.PageSize)
.ToList();
var model = new UsersIndexViewModel {
Users = results
.Select(x => new UserEntry { User = x.Record })
.ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
[HttpPost]
[FormValueRequired("submit.BulkEdit")]
public ActionResult Index(FormCollection input) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var viewModel = new UsersIndexViewModel {Users = new List<UserEntry>(), Options = new UserIndexOptions()};
UpdateModel(viewModel);
var checkedEntries = viewModel.Users.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case UsersBulkAction.None:
break;
case UsersBulkAction.Approve:
foreach (var entry in checkedEntries) {
Approve(entry.User.Id);
}
break;
case UsersBulkAction.Disable:
foreach (var entry in checkedEntries) {
Moderate(entry.User.Id);
}
break;
case UsersBulkAction.ChallengeEmail:
foreach (var entry in checkedEntries) {
SendChallengeEmail(entry.User.Id);
}
break;
case UsersBulkAction.Delete:
foreach (var entry in checkedEntries) {
Delete(entry.User.Id);
}
break;
}
return RedirectToAction("Index", ControllerContext.RouteData.Values);
}
public ActionResult Create() {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.New<IUser>("User");
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: new UserCreateViewModel(), Prefix: null);
editor.Metadata.Position = "2";
var model = Services.ContentManager.BuildEditor(user);
model.Content.Add(editor);
return View(model);
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePOST(UserCreateViewModel createModel) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
if (!string.IsNullOrEmpty(createModel.UserName)) {
if (!_userService.VerifyUserUnicity(createModel.UserName, createModel.Email)) {
AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
}
}
if (!Regex.IsMatch(createModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) {
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
ModelState.AddModelError("Email", T("You must specify a valid email address."));
}
if (createModel.Password != createModel.ConfirmPassword) {
AddModelError("ConfirmPassword", T("Password confirmation must match"));
}
IDictionary<string, LocalizedString> validationErrors;
if (!_userService.PasswordMeetsPolicies(createModel.Password, out validationErrors)) {
ModelState.AddModelErrors(validationErrors);
}
var user = Services.ContentManager.New<IUser>("User");
if (ModelState.IsValid) {
user = _membershipService.CreateUser(new CreateUserParams(
createModel.UserName,
createModel.Password,
createModel.Email,
null, null, true));
}
var model = Services.ContentManager.UpdateEditor(user, this);
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: createModel, Prefix: null);
editor.Metadata.Position = "2";
model.Content.Add(editor);
return View(model);
}
Services.Notifier.Success(T("User created"));
return RedirectToAction("Index");
}
public ActionResult Edit(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<UserPart>(id);
if (user == null)
return HttpNotFound();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: new UserEditViewModel {User = user}, Prefix: null);
editor.Metadata.Position = "2";
var model = Services.ContentManager.BuildEditor(user);
model.Content.Add(editor);
return View(model);
}
[HttpPost, ActionName("Edit")]
public ActionResult EditPOST(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<UserPart>(id, VersionOptions.DraftRequired);
if (user == null)
return HttpNotFound();
string previousName = user.UserName;
var model = Services.ContentManager.UpdateEditor(user, this);
var editModel = new UserEditViewModel { User = user };
if (TryUpdateModel(editModel)) {
if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email)) {
AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
}
else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) {
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
ModelState.AddModelError("Email", T("You must specify a valid email address."));
}
else {
// also update the Super user if this is the renamed account
if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal)) {
_siteService.GetSiteSettings().As<SiteSettingsPart>().SuperUser = editModel.UserName;
}
user.NormalizedUserName = editModel.UserName.ToLowerInvariant();
}
}
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null);
editor.Metadata.Position = "2";
model.Content.Add(editor);
return View(model);
}
Services.ContentManager.Publish(user.ContentItem);
Services.Notifier.Success(T("User information updated"));
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("The Super user can't be removed. Please disable this account or specify another Super user account."));
}
else if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("You can't remove your own account. Please log in with another account."));
}
else {
Services.ContentManager.Remove(user.ContentItem);
Services.Notifier.Success(T("User {0} deleted", user.UserName));
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult SendChallengeEmail(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
var siteUrl = Services.WorkContext.CurrentSite.BaseUrl;
if (string.IsNullOrWhiteSpace(siteUrl)) {
siteUrl = HttpContext.Request.ToRootUrlString();
}
_userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
Services.Notifier.Success(T("Challenge email sent to {0}", user.UserName));
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Approve(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
user.As<UserPart>().RegistrationStatus = UserStatus.Approved;
Services.Notifier.Success(T("User {0} approved", user.UserName));
_userEventHandlers.Approved(user);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Moderate(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("You can't disable your own account. Please log in with another account"));
}
else {
user.As<UserPart>().RegistrationStatus = UserStatus.Pending;
Services.Notifier.Success(T("User {0} disabled", user.UserName));
}
return RedirectToAction("Index");
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace System.ComponentModel
{
/// <summary>
/// Declares an array of attributes for a member and defines
/// the properties and methods that give you access to the attributes in the array.
/// All attributes must derive from <see cref='System.Attribute'/>.
/// </summary>
public abstract class MemberDescriptor
{
private readonly string _name;
private readonly string _displayName;
private readonly int _nameHash;
private AttributeCollection _attributeCollection;
private Attribute[] _attributes;
private Attribute[] _originalAttributes;
private bool _attributesFiltered;
private bool _attributesFilled;
private int _metadataVersion;
private string _category;
private string _description;
private readonly object _lockCookie = new object();
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and no attributes.
/// </summary>
protected MemberDescriptor(string name) : this(name, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and <paramref name="attributes "/> array.
/// </summary>
protected MemberDescriptor(string name, Attribute[] attributes)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.InvalidMemberName, nameof(name));
}
_name = name;
_displayName = name;
_nameHash = name.GetHashCode();
if (attributes != null)
{
_attributes = attributes;
_attributesFiltered = false;
}
_originalAttributes = _attributes;
}
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <see cref='System.ComponentModel.MemberDescriptor'/>.
/// </summary>
protected MemberDescriptor(MemberDescriptor descr)
{
if (descr == null)
{
throw new ArgumentNullException(nameof(descr));
}
_name = descr.Name;
_displayName = _name;
_nameHash = _name?.GetHashCode() ?? 0;
_attributes = new Attribute[descr.Attributes.Count];
descr.Attributes.CopyTo(_attributes, 0);
_attributesFiltered = true;
_originalAttributes = _attributes;
}
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the name in the specified
/// <see cref='System.ComponentModel.MemberDescriptor'/> and the attributes
/// in both the old <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array.
/// </summary>
protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes)
{
if (oldMemberDescriptor == null)
{
throw new ArgumentNullException(nameof(oldMemberDescriptor));
}
_name = oldMemberDescriptor.Name;
_displayName = oldMemberDescriptor.DisplayName;
_nameHash = _name.GetHashCode();
List<Attribute> newList = new List<Attribute>();
if (oldMemberDescriptor.Attributes.Count != 0)
{
foreach (Attribute o in oldMemberDescriptor.Attributes)
{
newList.Add(o);
}
}
if (newAttributes != null)
{
foreach (Attribute o in newAttributes)
{
newList.Add(o);
}
}
_attributes = new Attribute[newList.Count];
newList.CopyTo(_attributes, 0);
_attributesFiltered = false;
_originalAttributes = _attributes;
}
/// <summary>
/// Gets or sets an array of attributes.
/// </summary>
protected virtual Attribute[] AttributeArray
{
get
{
CheckAttributesValid();
FilterAttributesIfNeeded();
return _attributes;
}
set
{
lock (_lockCookie)
{
_attributes = value;
_originalAttributes = value;
_attributesFiltered = false;
_attributeCollection = null;
}
}
}
/// <summary>
/// Gets the collection of attributes for this member.
/// </summary>
public virtual AttributeCollection Attributes
{
get
{
CheckAttributesValid();
AttributeCollection attrs = _attributeCollection;
if (attrs == null)
{
lock (_lockCookie)
{
attrs = CreateAttributeCollection();
_attributeCollection = attrs;
}
}
return attrs;
}
}
/// <summary>
/// Gets the name of the category that the member belongs to, as specified
/// in the <see cref='System.ComponentModel.CategoryAttribute'/>.
/// </summary>
public virtual string Category => _category ?? (_category = ((CategoryAttribute) Attributes[typeof(CategoryAttribute)]).Category);
/// <summary>
/// Gets the description of the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>.
/// </summary>
public virtual string Description => _description ??
(_description = ((DescriptionAttribute) Attributes[typeof(DescriptionAttribute)]).Description);
/// <summary>
/// Gets a value indicating whether the member is browsable as specified in the
/// <see cref='System.ComponentModel.BrowsableAttribute'/>.
/// </summary>
public virtual bool IsBrowsable => ((BrowsableAttribute)Attributes[typeof(BrowsableAttribute)]).Browsable;
/// <summary>
/// Gets the name of the member.
/// </summary>
public virtual string Name => _name ?? "";
/// <summary>
/// Gets the hash code for the name of the member as specified in <see cref='System.String.GetHashCode()'/>.
/// </summary>
protected virtual int NameHashCode => _nameHash;
/// <summary>
/// Determines whether this member should be set only at
/// design time as specified in the <see cref='System.ComponentModel.DesignOnlyAttribute'/>.
/// </summary>
public virtual bool DesignTimeOnly => (DesignOnlyAttribute.Yes.Equals(Attributes[typeof(DesignOnlyAttribute)]));
/// <summary>
/// Gets the name that can be displayed in a window like a properties window.
/// </summary>
public virtual string DisplayName
{
get
{
if (!(Attributes[typeof(DisplayNameAttribute)] is DisplayNameAttribute displayNameAttr) || displayNameAttr.IsDefaultAttribute())
{
return _displayName;
}
return displayNameAttr.DisplayName;
}
}
/// <summary>
/// Called each time we access the attributes on
/// this member descriptor to give deriving classes
/// a chance to change them on the fly.
/// </summary>
private void CheckAttributesValid()
{
if (_attributesFiltered)
{
if (_metadataVersion != TypeDescriptor.MetadataVersion)
{
_attributesFilled = false;
_attributesFiltered = false;
_attributeCollection = null;
}
}
}
/// <summary>
/// Creates a collection of attributes using the
/// array of attributes that you passed to the constructor.
/// </summary>
protected virtual AttributeCollection CreateAttributeCollection()
{
return new AttributeCollection(AttributeArray);
}
/// <summary>
/// Compares this instance to the specified <see cref='System.ComponentModel.MemberDescriptor'/> to see if they are equivalent.
/// NOTE: If you make a change here, you likely need to change GetHashCode() as well.
/// </summary>
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj.GetType() != GetType())
{
return false;
}
MemberDescriptor mdObj = (MemberDescriptor)obj;
FilterAttributesIfNeeded();
mdObj.FilterAttributesIfNeeded();
if (mdObj._nameHash != _nameHash)
{
return false;
}
if ((mdObj._category == null) != (_category == null) ||
(_category != null && !mdObj._category.Equals(_category)))
{
return false;
}
if ((mdObj._description == null) != (_description == null) ||
(_description != null && !mdObj._description.Equals(_description)))
{
return false;
}
if ((mdObj._attributes == null) != (_attributes == null))
{
return false;
}
bool sameAttrs = true;
if (_attributes != null)
{
if (_attributes.Length != mdObj._attributes.Length)
{
return false;
}
for (int i = 0; i < _attributes.Length; i++)
{
if (!_attributes[i].Equals(mdObj._attributes[i]))
{
sameAttrs = false;
break;
}
}
}
return sameAttrs;
}
/// <summary>
/// In an inheriting class, adds the attributes of the inheriting class to the
/// specified list of attributes in the parent class. For duplicate attributes,
/// the last one added to the list will be kept.
/// </summary>
protected virtual void FillAttributes(IList attributeList)
{
if (attributeList == null)
{
throw new ArgumentNullException(nameof(attributeList));
}
if (_originalAttributes != null)
{
foreach (Attribute attr in _originalAttributes)
{
attributeList.Add(attr);
}
}
}
private void FilterAttributesIfNeeded()
{
if (!_attributesFiltered)
{
List<Attribute> list;
if (!_attributesFilled)
{
list = new List<Attribute>();
try
{
FillAttributes(list);
}
catch (Exception)
{
}
}
else
{
list = new List<Attribute>(_attributes);
}
var map = new Dictionary<object, int>();
for (int i = 0; i < list.Count;)
{
int savedIndex = -1;
object typeId = list[i]?.TypeId;
if (typeId == null)
{
list.RemoveAt(i);
}
else if (!map.TryGetValue(typeId, out savedIndex))
{
map.Add(typeId, i);
i++;
}
else
{
list[savedIndex] = list[i];
list.RemoveAt(i);
}
}
Attribute[] newAttributes = list.ToArray();
lock (_lockCookie)
{
_attributes = newAttributes;
_attributesFiltered = true;
_attributesFilled = true;
_metadataVersion = TypeDescriptor.MetadataVersion;
}
}
}
/// <summary>
/// Finds the given method through reflection. This method only looks for public methods.
/// </summary>
protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType)
{
return FindMethod(componentClass, name, args, returnType, true);
}
/// <summary>
/// Finds the given method through reflection.
/// </summary>
protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly)
{
if (componentClass == null)
{
throw new ArgumentNullException(nameof(componentClass));
}
MethodInfo result = null;
if (publicOnly)
{
result = componentClass.GetMethod(name, args);
}
else
{
result = componentClass.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null);
}
if (result != null && !result.ReturnType.IsEquivalentTo(returnType))
{
result = null;
}
return result;
}
/// <summary>
/// Try to keep this reasonable in [....] with Equals(). Specifically,
/// if A.Equals(B) returns true, A & B should have the same hash code.
/// </summary>
public override int GetHashCode() => _nameHash;
/// <summary>
/// This method returns the object that should be used during invocation of members.
/// Normally the return value will be the same as the instance passed in. If
/// someone associated another object with this instance, or if the instance is a
/// custom type descriptor, GetInvocationTarget may return a different value.
/// </summary>
protected virtual object GetInvocationTarget(Type type, object instance)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
return TypeDescriptor.GetAssociation(type, instance);
}
/// <summary>
/// Gets a component site for the given component.
/// </summary>
protected static ISite GetSite(object component) => (component as IComponent)?.Site;
[Obsolete("This method has been deprecated. Use GetInvocationTarget instead. https://go.microsoft.com/fwlink/?linkid=14202")]
protected static object GetInvokee(Type componentClass, object component) {
if (componentClass == null)
{
throw new ArgumentNullException(nameof(componentClass));
}
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
return TypeDescriptor.GetAssociation(componentClass, component);
}
}
}
| |
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
namespace Thinktecture.Tools.Web.Services.ContractFirst
{
public sealed class ConfigurationManager
{
private XmlDocument xml;
private XmlDocument xmlOriginal;
private string fileName;
private IsolatedStorageFile isoStore;
private static ConfigurationManager singleton;
public static ConfigurationManager GetConfigurationManager(string applicationName)
{
if (singleton == null)
{
singleton = new ConfigurationManager(applicationName);
}
return singleton;
}
private ConfigurationManager(string applicationName)
{
this.InitializeConfiguration(applicationName);
}
public string Read(string section)
{
return Read(section, String.Empty);
}
public string Read(string section, string defaultValue)
{
try
{
if (this.xml == null)
{
return String.Empty;
}
XmlNode sectionNode = this.xml.SelectSingleNode((@"/configuration/" + section));
if (sectionNode == null)
{
return defaultValue;
}
return sectionNode.FirstChild.Value;
}
catch
{
return defaultValue;
}
}
public int ReadInteger(string section)
{
return ReadInteger(section, 0);
}
public int ReadInteger(string section, int defaultValue)
{
string valuestring = Read(section);
if (valuestring.Length <= 0)
{
return defaultValue;
}
try
{
int value = Convert.ToInt32(valuestring);
return value;
}
catch
{
return defaultValue;
}
}
public bool ReadBoolean(string section)
{
return ReadBoolean(section, false);
}
public bool ReadBoolean(string section, bool defaultValue)
{
string value = this.Read(section);
if (value.Length <= 0)
{
return defaultValue;
}
try
{
return Boolean.Parse(value);
}
catch
{
return defaultValue;
}
}
public void Write(string section, string value)
{
try
{
if (this.xml == null)
{
this.xml = new XmlDocument();
XmlNode configurationRootNode = this.xml.CreateElement(@"configuration");
this.xml.AppendChild(configurationRootNode);
}
XmlNode sectionNode = this.xml.SelectSingleNode((@"/configuration/" + section));
if (sectionNode == null)
{
sectionNode = this.xml.CreateElement(section);
XmlNode configurationRootNode = this.xml.SelectSingleNode(@"/configuration");
configurationRootNode.AppendChild(sectionNode);
}
sectionNode.InnerText = value;
}
catch{}
}
public void ReadFormSettings(System.Windows.Forms.Form form)
{
string windowStateString = this.Read(form.Name + "WindowState");
System.Windows.Forms.FormWindowState windowState = System.Windows.Forms.FormWindowState.Normal;
if (windowStateString.Length > 0)
{
windowState = (System.Windows.Forms.FormWindowState)Convert.ToInt32(windowStateString);
}
if (windowState == System.Windows.Forms.FormWindowState.Maximized)
{
form.WindowState = windowState;
}
else
{
string valuesString = this.Read(form.Name);
if (valuesString.Length > 0)
{
string[] values = valuesString.Split(Convert.ToChar(","));
form.Top = Convert.ToInt16(values[0]);
form.Left = Convert.ToInt16(values[1]);
int width = Convert.ToInt16(values[2]);
if (width > 0) form.Width = width;
int height = Convert.ToInt16(values[3]);
if (height > 0) form.Height = height;
}
}
}
public void WriteFormSettings(System.Windows.Forms.Form form)
{
this.Write(form.Name + "WindowState", ((int)form.WindowState).ToString());
if (form.WindowState == System.Windows.Forms.FormWindowState.Normal)
{
string valuesstring = form.Top.ToString() + "," + form.Left.ToString() + "," + form.Width.ToString() + "," + form.Height.ToString();
this.Write(form.Name, valuesstring);
}
}
public void Persist()
{
try
{
this.WriteBackConfiguration();
}
catch
{
}
finally
{
singleton = null;
}
}
private void InitializeConfiguration(string applicationName)
{
this.fileName = applicationName + ".config";
this.isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
string[] storeFileNames;
storeFileNames = this.isoStore.GetFileNames(this.fileName);
foreach(string storeFile in storeFileNames)
{
if (storeFile == this.fileName)
{
//Create isoStorage StreamReader
StreamReader streamReader = new StreamReader(new IsolatedStorageFileStream(this.fileName, FileMode.Open, this.isoStore));
this.xml = new XmlDocument();
this.xml.Load(streamReader);
this.xmlOriginal = new XmlDocument();
this.xmlOriginal.LoadXml(this.xml.OuterXml);
streamReader.Close();
}
}
}
private void WriteBackConfiguration()
{
if (this.xml == null) return;
if (this.xmlOriginal != null)
{
if (this.xml.OuterXml == this.xmlOriginal.OuterXml) return;
}
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(new IsolatedStorageFileStream(this.fileName, FileMode.Create, this.isoStore));
this.xml.Save(streamWriter);
streamWriter.Flush();
streamWriter.Close();
if (this.xmlOriginal == null) this.xmlOriginal = new XmlDocument();
this.xmlOriginal.LoadXml(this.xml.OuterXml);
}
catch
{
//throw;
}
finally
{
if (streamWriter != null)
{
streamWriter.Flush();
streamWriter.Close();
}
}
}
}
}
| |
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc.">
// Copyright (C) Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Google Play Game Services Setup dialog for Android.
/// </summary>
public class GPGSAndroidSetupUI : EditorWindow
{
/// <summary>
/// The configuration data from the play games console "resource data"
/// </summary>
private string mConfigData = string.Empty;
/// <summary>
/// The name of the class to generate containing the resource constants.
/// </summary>
private string mClassName = "GPGSIds";
/// <summary>
/// The scroll position
/// </summary>
private Vector2 scroll;
/// <summary>
/// The directory for the constants class.
/// </summary>
private string mConstantDirectory = "Assets";
/// <summary>
/// The web client identifier.
/// </summary>
private string mWebClientId = string.Empty;
/// <summary>
/// Menus the item for GPGS android setup.
/// </summary>
[MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)]
public static void MenuItemFileGPGSAndroidSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title);
window.minSize = new Vector2(500, 400);
}
[MenuItem("Window/Google Play Games/Setup/Android setup...", true)]
public static bool EnableAndroidMenuItem() {
#if UNITY_ANDROID
return true;
#else
return false;
#endif
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="clientId">The web client id.</param>
/// <param name="classDirectory">the directory to write the constants file to.</param>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">Indicates this app requires G+</param>
public static bool PerformSetup(
string clientId,
string classDirectory,
string className,
string resourceXmlData,
string nearbySvcId)
{
if (string.IsNullOrEmpty(resourceXmlData) &&
!string.IsNullOrEmpty(nearbySvcId))
{
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId);
}
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory);
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData);
// check the bundle id and set it if needed.
CheckBundleId();
GPGSUtil.CheckAndFixDependencies();
GPGSUtil.CheckAndFixVersionedAssestsPaths();
AssetDatabase.Refresh();
Google.VersionHandler.VerboseLoggingEnabled = true;
Google.VersionHandler.UpdateVersionedAssets(forceUpdate: true);
Google.VersionHandler.Enabled = true;
AssetDatabase.Refresh();
Google.VersionHandler.InvokeStaticMethod(
Google.VersionHandler.FindClass(
"Google.JarResolver",
"GooglePlayServices.PlayServicesResolver"),
"MenuResolve", null);
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId);
}
return false;
}
/// <summary>
/// Provide static access to setup for facilitating automated builds.
/// </summary>
/// <param name="webClientId">The oauth2 client id for the game. This is only
/// needed if the ID Token or access token are needed.</param>
/// <param name="appId">App identifier.</param>
/// <param name="nearbySvcId">Optional nearby connection serviceId</param>
/// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param>
/// <returns>true if successful</returns>
public static bool PerformSetup(string webClientId, string appId, string nearbySvcId)
{
if (!string.IsNullOrEmpty(webClientId))
{
if (!GPGSUtil.LooksLikeValidClientId(webClientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
string serverAppId = webClientId.Split('-')[0];
if (!serverAppId.Equals(appId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch);
return false;
}
}
// check for valid app id
if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdError);
return false;
}
if (nearbySvcId != null) {
#if UNITY_ANDROID
if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true))
{
return false;
}
#endif
}
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Save();
GPGSUtil.UpdateGameInfo();
// check that Android SDK is there
if (!GPGSUtil.HasAndroidSdk())
{
Debug.LogError("Android SDK not found.");
EditorUtility.DisplayDialog(
GPGSStrings.AndroidSetup.SdkNotFound,
GPGSStrings.AndroidSetup.SdkNotFoundBlurb,
GPGSStrings.Ok);
return false;
}
// Generate AndroidManifest.xml
GPGSUtil.GenerateAndroidManifest();
// refresh assets, and we're done
AssetDatabase.Refresh();
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
return true;
}
/// <summary>
/// Called when this object is enabled by Unity editor.
/// </summary>
public void OnEnable()
{
GPGSProjectSettings settings = GPGSProjectSettings.Instance;
mConstantDirectory = settings.Get(GPGSUtil.CLASSDIRECTORYKEY, mConstantDirectory);
mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY, mClassName);
mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY);
mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY);
}
/// <summary>
/// Called when the GUI should be rendered.
/// </summary>
public void OnGUI()
{
GUI.skin.label.wordWrap = true;
GUILayout.BeginVertical();
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(0f, 0f, 1f);
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.AndroidSetup.Blurb);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mConstantDirectory = EditorGUILayout.TextField(
"Directory to save constants",
mConstantDirectory,
GUILayout.MinWidth(480));
mClassName = EditorGUILayout.TextField(
"Constants class name",
mClassName,
GUILayout.MinWidth(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Android Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(
mConfigData,
GUILayout.MinWidth(475),
GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb);
mWebClientId = EditorGUILayout.TextField(
GPGSStrings.Setup.ClientId,
mWebClientId,
GUILayout.MinWidth(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100)))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
return;
}
}
catch (Exception e)
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button("Cancel", GUILayout.Width(100)))
{
Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Starts the setup process.
/// </summary>
public void DoSetup()
{
if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null))
{
CheckBundleId();
EditorUtility.DisplayDialog(
GPGSStrings.Success,
GPGSStrings.AndroidSetup.SetupComplete,
GPGSStrings.Ok);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
Close();
}
else
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid or missing XML resource data. Make sure the data is" +
" valid and contains the app_id element");
}
}
/// <summary>
/// Checks the bundle identifier.
/// </summary>
/// <remarks>
/// Check the package id. If one is set the gpgs properties,
/// and the player settings are the default or empty, set it.
/// if the player settings is not the default, then prompt before
/// overwriting.
/// </remarks>
public static void CheckBundleId()
{
string packageName = GPGSProjectSettings.Instance.Get(
GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty);
string currentId;
#if UNITY_5_6_OR_NEWER
currentId = PlayerSettings.GetApplicationIdentifier(
BuildTargetGroup.Android);
#else
currentId = PlayerSettings.bundleIdentifier;
#endif
if (!string.IsNullOrEmpty(packageName))
{
if (string.IsNullOrEmpty(currentId) ||
currentId == "com.Company.ProductName")
{
#if UNITY_5_6_OR_NEWER
PlayerSettings.SetApplicationIdentifier(
BuildTargetGroup.Android, packageName);
#else
PlayerSettings.bundleIdentifier = packageName;
#endif
}
else if (currentId != packageName)
{
if (EditorUtility.DisplayDialog(
"Set Bundle Identifier?",
"The server configuration is using " +
packageName + ", but the player settings is set to " +
currentId + ".\nSet the Bundle Identifier to " +
packageName + "?",
"OK",
"Cancel"))
{
#if UNITY_5_6_OR_NEWER
PlayerSettings.SetApplicationIdentifier(
BuildTargetGroup.Android, packageName);
#else
PlayerSettings.bundleIdentifier = packageName;
#endif
}
}
}
else
{
Debug.Log("NULL package!!");
}
}
/// <summary>
/// Parses the resources xml and set the properties. Also generates the
/// constants file.
/// </summary>
/// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="res">Res. the data to parse.</param>
private static bool ParseResources(string classDirectory, string className, string res)
{
XmlTextReader reader = new XmlTextReader(new StringReader(res));
bool inResource = false;
string lastProp = null;
Hashtable resourceKeys = new Hashtable();
string appId = null;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "string")
{
lastProp = reader.GetAttribute("name");
}
else if (inResource && !string.IsNullOrEmpty(lastProp))
{
if (reader.HasValue)
{
if (lastProp == "app_id")
{
appId = reader.Value;
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
}
else if (lastProp == "package_name")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value);
}
else
{
resourceKeys[lastProp] = reader.Value;
}
lastProp = null;
}
}
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
return appId != null;
}
}
}
| |
namespace FakeItEasy.Tests.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using FakeItEasy.Core;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xunit;
public class CallWriterTests
{
private readonly List<IFakeObjectCall> calls;
private readonly StringBuilderOutputWriter writer;
private readonly IEqualityComparer<IFakeObjectCall> callComparer;
private readonly IFakeObjectCallFormatter callFormatter;
public CallWriterTests()
{
this.callComparer = A.Fake<IEqualityComparer<IFakeObjectCall>>();
this.callFormatter = A.Fake<IFakeObjectCallFormatter>();
A.CallTo(() => this.callFormatter.GetDescription(A<IFakeObjectCall>._))
.Returns("Default call description");
this.calls = new List<IFakeObjectCall>();
this.writer = ServiceLocator.Resolve<StringBuilderOutputWriter.Factory>().Invoke();
}
[Fact]
public void WriteCalls_should_list_the_calls_in_the_calls_collection()
{
this.StubCalls(10);
int callNumber = 1;
foreach (var call in this.calls)
{
var boundCallNumber = callNumber;
A.CallTo(() => this.callFormatter.GetDescription(call)).Returns("Fake call " + boundCallNumber);
callNumber++;
}
var callWriter = this.CreateWriter();
callWriter.WriteCalls(this.calls, this.writer);
var message = this.writer.Builder.ToString();
var expectedMessage =
@"1: Fake call 1
2: Fake call 2
3: Fake call 3
4: Fake call 4
5: Fake call 5
6: Fake call 6
7: Fake call 7
8: Fake call 8
9: Fake call 9
10: Fake call 10";
message.Should().ContainModuloLineEndings(expectedMessage);
}
[Fact]
public void WriteCalls_should_skip_duplicate_calls_in_row()
{
// Arrange
this.StubCalls(10);
A.CallTo(() => this.callFormatter.GetDescription(A<IFakeObjectCall>._)).Returns("Fake call");
A.CallTo(() => this.callFormatter.GetDescription(this.calls[9])).Returns("Other call");
A.CallTo(() => this.callComparer.Equals(A<IFakeObjectCall>.That.Not.IsEqualTo(this.calls[9]), A<IFakeObjectCall>.That.Not.IsEqualTo(this.calls[9]))).Returns(true);
var callWriter = this.CreateWriter();
// Act
callWriter.WriteCalls(this.calls, this.writer);
// Assert
var message = this.writer.Builder.ToString();
var expectedMessage =
@"1: Fake call 9 times
...
10: Other call";
message.Should().ContainModuloLineEndings(expectedMessage);
}
[Fact]
public void WriteCalls_should_not_skip_duplicate_messages_that_are_not_in_row()
{
this.StubCalls(4);
foreach (var call in this.calls.Where((x, i) => i % 2 == 0))
{
A.CallTo(() => this.callFormatter.GetDescription(call)).Returns("odd");
}
foreach (var call in this.calls.Where((x, i) => i % 2 != 0))
{
A.CallTo(() => this.callFormatter.GetDescription(call)).Returns("even");
}
var callWriter = this.CreateWriter();
callWriter.WriteCalls(this.calls, this.writer);
var message = this.writer.Builder.ToString();
var expectedMessage =
@"1: odd
2: even
3: odd
4: even";
message.Should().ContainModuloLineEndings(expectedMessage);
}
[Fact]
public void WriteCalls_should_truncate_calls_list_when_more_than_a_hundred_call_lines_are_printed()
{
this.StubCalls(30);
foreach (var call in this.calls)
{
A.CallTo(() => this.callFormatter.GetDescription(call)).Returns("Fake call " + Guid.NewGuid());
}
A.CallTo(() => this.callFormatter.GetDescription(this.calls[18])).Returns("Last call");
var callWriter = this.CreateWriter();
callWriter.WriteCalls(this.calls, this.writer);
var message = this.writer.Builder.ToString();
var expectedMessage =
@"19: Last call
... Found 11 more calls not displayed here.";
message.Should().ContainModuloLineEndings(expectedMessage);
}
[Fact]
public void WriteCalls_should_indent_values_with_new_lines_correctly()
{
// Arrange
this.StubCalls(10);
var text = string.Join(Environment.NewLine, "first line", "second line");
var callIndex = 0;
A.CallTo(() => this.callFormatter.GetDescription(A<IFakeObjectCall>._)).ReturnsLazily(() => text + ++callIndex);
var callWriter = this.CreateWriter();
// Act
using (this.writer.Indent())
{
callWriter.WriteCalls(this.calls, this.writer);
}
// Assert
var message = this.writer.Builder.ToString();
var expectedText1 =
@"1: first line
second line";
var expectedText2 =
@"10: first line
second line";
message.Should().ContainModuloLineEndings(expectedText1).And.ContainModuloLineEndings(expectedText2);
}
[Fact]
public void WriteCalls_should_write_new_line_at_end()
{
// Arrange
this.StubCalls(1);
var callWriter = this.CreateWriter();
// Act
callWriter.WriteCalls(this.calls, this.writer);
// Assert
this.writer.Builder.ToString().Should().EndWith(Environment.NewLine);
}
[Fact]
public void Should_write_nothing_if_call_list_is_empty()
{
// Arrange
var callWriter = this.CreateWriter();
// Act
callWriter.WriteCalls(Enumerable.Empty<IFakeObjectCall>(), this.writer);
// Assert
this.writer.Builder.ToString().Should().BeEmpty();
}
private CallWriter CreateWriter()
{
return new CallWriter(this.callFormatter, this.callComparer);
}
private void StubCalls(int numberOfCalls)
{
for (int i = 0; i < numberOfCalls; i++)
{
this.calls.Add(A.Fake<IFakeObjectCall>());
}
}
}
}
| |
using HTTPlease;
using HTTPlease.Formatters;
using HTTPlease.Formatters.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Raven.Client.Documents;
using Raven.Client.Documents.Session;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using StatusCodes = Microsoft.AspNetCore.Http.StatusCodes;
namespace DaaSDemo.Api.Controllers
{
using Data;
using Data.Indexes;
using Models.Api;
using Models.Data;
/// <summary>
/// Controller for the servers API.
/// </summary>
[Route("api/v1/servers")]
public class ServersController
: Controller
{
/// <summary>
/// Create a new servers API controller.
/// </summary>
/// <param name="documentSession">
/// The RavenDB document session for the current request.
/// </param>
/// <param name="logger">
/// The controller's log facility.
/// </param>
public ServersController(IDocumentSession documentSession, ILogger<ServersController> logger)
{
if (documentSession == null)
throw new ArgumentNullException(nameof(documentSession));
if (logger == null)
throw new ArgumentNullException(nameof(logger));
DocumentSession = documentSession;
Log = logger;
}
/// <summary>
/// The RavenDB document session for the current request.
/// </summary>
IDocumentSession DocumentSession { get; }
/// <summary>
/// The controller's log facility.
/// </summary>
ILogger Log { get; }
/// <summary>
/// Get all servers.
/// </summary>
[HttpGet]
public IActionResult List()
{
return Json(
DocumentSession.Query<DatabaseServer, DatabaseServerDetails>()
.OrderBy(server => server.Name)
.ProjectFromIndexFieldsInto<DatabaseServerDetail>()
);
}
/// <summary>
/// Get a server by Id.
/// </summary>
/// <param name="serverId">
/// The server Id.
/// </param>
[HttpGet("{serverId}")]
public IActionResult GetById(string serverId)
{
DatabaseServer server = DocumentSession
.Include<DatabaseServer>(databaseServer => databaseServer.TenantId)
.Load<DatabaseServer>(serverId);
if (server == null)
{
return NotFound(new
{
Id = serverId,
EntityType = "DatabaseServer",
Message = $"No server found with Id {serverId}."
});
}
Tenant tenant = DocumentSession.Load<Tenant>(server.TenantId);
if (tenant == null)
{
return NotFound(new
{
Id = server.TenantId,
EntityType = "Tenant",
Message = $"No tenant found with Id {server.TenantId} (referenced by server {serverId})."
});
}
return Json(
new DatabaseServerDetail(server, tenant)
);
}
/// <summary>
/// Get events for the specified database server.
/// </summary>
[HttpGet("{serverId}/events")]
public IActionResult GetEvents(string serverId)
{
DatabaseServer server = DocumentSession.Load<DatabaseServer>(serverId);
if (server == null)
{
return NotFound(new
{
Id = serverId,
EntityType = "DatabaseServer",
Message = $"No server found with Id {serverId}."
});
}
return Ok(
server.Events.OrderBy(evt => evt.Timestamp)
);
}
/// <summary>
/// Provision an SQL Server instance for a tenant.
/// </summary>
/// <param name="newDatabaseServer">
/// The request body as a <see cref="NewSqlServer"/>.
/// </param>
[HttpPost("create/sql")]
public IActionResult CreateSqlServer([FromBody] NewSqlServer newDatabaseServer)
{
if (newDatabaseServer == null)
{
return BadRequest(new
{
EntityType = "DatabaseServer",
Reason = "InvalidRequest",
Message = "Must supply database details in the request body."
});
}
Tenant tenant = DocumentSession.Load<Tenant>(newDatabaseServer.TenantId);
if (tenant == null)
{
return NotFound(new
{
Id = newDatabaseServer.TenantId,
EntityType = "Tenant",
Message = $"No tenant found with Id {newDatabaseServer.TenantId}."
});
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
var databaseServer = new DatabaseServer
{
Name = newDatabaseServer.Name,
Kind = DatabaseServerKind.SqlServer,
Settings = new SqlServerSettings
{
AdminPassword = newDatabaseServer.AdminPassword,
Storage =
{
SizeMB = newDatabaseServer.SizeMB
}
},
TenantId = tenant.Id,
Action = ProvisioningAction.Provision,
Status = ProvisioningStatus.Pending,
};
DocumentSession.Store(databaseServer);
databaseServer.AddProvisioningEvent($"Provisioning requested for '${databaseServer.Id}'.");
DocumentSession.SaveChanges();
return StatusCode(StatusCodes.Status202Accepted, new
{
Id = databaseServer.Id,
Name = databaseServer.Name,
Message = $"SQL Server instance {databaseServer.Id} queued for creation."
});
}
/// <summary>
/// Provision a RavenDB instance for a tenant.
/// </summary>
/// <param name="newDatabaseServer">
/// The request body as a <see cref="NewRavenServer"/>.
/// </param>
[HttpPost("create/ravendb")]
public IActionResult CreateRavenServer([FromBody] NewRavenServer newDatabaseServer)
{
if (newDatabaseServer == null)
{
return BadRequest(new
{
EntityType = "DatabaseServer",
Reason = "InvalidRequest",
Message = "Must supply database details in the request body."
});
}
Tenant tenant = DocumentSession.Load<Tenant>(newDatabaseServer.TenantId);
if (tenant == null)
{
return NotFound(new
{
Id = newDatabaseServer.TenantId,
EntityType = "Tenant",
Message = $"No tenant found with Id {newDatabaseServer.TenantId}."
});
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
var databaseServer = new DatabaseServer
{
Name = newDatabaseServer.Name,
Kind = DatabaseServerKind.RavenDB,
Settings = new RavenServerSettings
{
Storage =
{
SizeMB = newDatabaseServer.SizeMB
}
},
TenantId = tenant.Id,
Action = ProvisioningAction.Provision,
Status = ProvisioningStatus.Pending,
};
DocumentSession.Store(databaseServer);
databaseServer.AddProvisioningEvent($"Provisioning requested for '${databaseServer.Id}'.");
DocumentSession.SaveChanges();
return StatusCode(StatusCodes.Status202Accepted, new
{
Id = databaseServer.Id,
Name = databaseServer.Name,
Message = $"RavenDB instance {databaseServer.Id} queued for creation."
});
}
/// <summary>
/// Reconfigure / repair a database server.
/// </summary>
/// <param name="serverId">
/// The tenant Id.
/// </param>
[HttpPost("{serverId}/reconfigure")]
public IActionResult ReconfigureServer(string serverId)
{
DatabaseServer targetServer = DocumentSession.GetDatabaseServerById(serverId);
if (targetServer == null)
{
return NotFound(new
{
Id = serverId,
EntityType = "DatabaseServer",
Message = $"No database server found with Id '{serverId}'."
});
}
if (targetServer.Action != ProvisioningAction.None)
{
return StatusCode(StatusCodes.Status409Conflict, new
{
Id = targetServer.Id,
TenantId = serverId,
EntityType = "DatabaseServer",
RequestedAction = ProvisioningAction.Reconfigure,
Action = targetServer.Action,
Status = targetServer.Status,
Message = $"Cannot reconfigure database server {targetServer.Id} because another server-level action is already in progress."
});
}
targetServer.Action = ProvisioningAction.Reconfigure;
targetServer.Status = ProvisioningStatus.Pending;
targetServer.AddProvisioningEvent($"Reconfiguration requested for '${targetServer.Id}'.");
DocumentSession.SaveChanges();
return StatusCode(StatusCodes.Status202Accepted, new
{
Id = serverId,
Message = $"Database server {targetServer.Id} queued for reconfiguration.",
EntityType = "DatabaseServer"
});
}
/// <summary>
/// Deprovision a tenant's database server.
/// </summary>
/// <param name="serverId">
/// The server Id.
/// </param>
[HttpDelete("{serverId}")]
public IActionResult DestroyServer(string serverId)
{
DatabaseServer targetServer = DocumentSession.GetDatabaseServerById(serverId);
if (targetServer == null)
{
return NotFound(new
{
Id = serverId,
EntityType = "DatabaseServer",
Message = $"No database server found with Id '{serverId}'."
});
}
if (DocumentSession.DoesServerHaveDatabases(targetServer.Id))
{
return StatusCode(StatusCodes.Status400BadRequest, new
{
Id = targetServer.Id,
TenantId = serverId,
EntityType = "DatabaseServer",
RequestedAction = ProvisioningAction.Deprovision,
Action = targetServer.Action,
Status = targetServer.Status,
Message = $"Cannot de-provision database server {targetServer.Id} because it still hosts one or more databases. First de-provision these databases and then retry the operation."
});
}
if (targetServer.Action != ProvisioningAction.None)
{
return StatusCode(StatusCodes.Status409Conflict, new
{
Id = targetServer.Id,
TenantId = serverId,
EntityType = "DatabaseServer",
RequestedAction = ProvisioningAction.Deprovision,
Action = targetServer.Action,
Status = targetServer.Status,
Message = $"Cannot de-provision database server {targetServer.Id} because an action ({targetServer.Action}) is already in progress for this server."
});
}
targetServer.Action = ProvisioningAction.Deprovision;
targetServer.Status = ProvisioningStatus.Pending;
targetServer.AddProvisioningEvent($"De-provisioning requested for '${targetServer.Id}'.");
DocumentSession.SaveChanges();
return StatusCode(StatusCodes.Status202Accepted, new
{
Id = serverId,
Message = $"Database server {targetServer.Id} queued for deletion.",
EntityType = "DatabaseServer"
});
}
/// <summary>
/// Get all databases hosted by the specified server.
/// </summary>
/// <param name="serverId">
/// The server Id.
/// </param>
[HttpGet("{serverId}/databases")]
public IActionResult GetDatabases(string serverId)
{
return Json(
DocumentSession.Query<DatabaseInstance, DatabaseInstanceDetails>()
.Where(database => database.ServerId == serverId)
.OrderBy(database => database.Name)
.ProjectFromIndexFieldsInto<DatabaseInstanceDetail>()
);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.db.Core;
using bv.common.win.BaseForms;
using bv.winclient.Core;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using EIDSS;
using eidss.avr.db.DBService.QueryBuilder;
using eidss.avr.PivotComponents;
using EIDSS.Core;
using eidss.model.Resources;
namespace eidss.avr.QueryBuilder
{
public partial class QuerySearchObjectInfo : BaseAvrDetailPanel
{
//old filter//private readonly FilterControlHelper m_FilterControlHelper;
public static readonly long m_DefaultSearchObject = 10082000; // "sobHumanCases"
private long m_SearchObject = -1L;
private int m_Order;
private bool m_IsFFObject;
private HACode m_ObjectHACode = HACode.None;
private object m_ReportType = DBNull.Value;
#region Init
public QuerySearchObjectInfo()
{
InitializeComponent();
QuerySearchObjectDbService = new QuerySearchObject_DB();
DbService = QuerySearchObjectDbService;
SearchObject = m_DefaultSearchObject;
Order = 0;
//old filter//m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter);
//old filter//m_FilterControlHelper.OnFilterChanged += DisplayFilter;
qsoFilter.OnFilterChanged += DisplayFilter;
splitContainerFilters.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel"));
imlbcAvailableField.ImageList = AvrFieldIcons.ImageList;
imTypeImage.SmallImages = AvrFieldIcons.ImageList;
}
public QuerySearchObjectInfo(long aSearchObject)
{
InitializeComponent();
QuerySearchObjectDbService = new QuerySearchObject_DB();
DbService = QuerySearchObjectDbService;
SearchObject = aSearchObject;
Order = 0;
//old filter//m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter);
//old filter//m_FilterControlHelper.OnFilterChanged += DisplayFilter;
qsoFilter.OnFilterChanged += DisplayFilter;
splitContainerFilters.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel"));
imlbcAvailableField.ImageList = AvrFieldIcons.ImageList;
imTypeImage.SmallImages = AvrFieldIcons.ImageList;
}
public QuerySearchObjectInfo(long aSearchObject, int aOrder)
{
InitializeComponent();
QuerySearchObjectDbService = new QuerySearchObject_DB();
DbService = QuerySearchObjectDbService;
SearchObject = aSearchObject;
Order = aOrder >= 0 ? aOrder : 0;
//old filter//m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter);
//old filter//m_FilterControlHelper.OnFilterChanged += DisplayFilter;
qsoFilter.OnFilterChanged += DisplayFilter;
splitContainerFilters.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel"));
imlbcAvailableField.ImageList = AvrFieldIcons.ImageList;
imTypeImage.SmallImages = AvrFieldIcons.ImageList;
}
public QuerySearchObjectInfo(long aSearchObject, object aReportType, int aOrder)
{
InitializeComponent();
QuerySearchObjectDbService = new QuerySearchObject_DB();
DbService = QuerySearchObjectDbService;
SearchObject = aSearchObject;
Order = aOrder >= 0 ? aOrder : 0;
ReportType = aReportType;
//old filter//m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter);
//old filter//m_FilterControlHelper.OnFilterChanged += DisplayFilter;
qsoFilter.OnFilterChanged += DisplayFilter;
splitContainerFilters.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel"));
imlbcAvailableField.ImageList = AvrFieldIcons.ImageList;
imTypeImage.SmallImages = AvrFieldIcons.ImageList;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
try
{
// if (Utils.IsCalledFromUnitTest())
// return;
//old filter//m_FilterControlHelper.OnFilterChanged -= DisplayFilter;
//TODO: Is the next line needed?
if (qsoFilter != null) qsoFilter.OnFilterChanged -= DisplayFilter;
//old filter//m_FilterControlHelper.Dispose();
eventManager.ClearAllReferences();
if (disposing && (components != null))
{
components.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion
#region Keys
public override object GetKey(string tableName = null, string keyFieldName = null)
{
return QuerySearchObjectDbService.ID;
}
#endregion
#region Properties
[Browsable(false), DefaultValue(-1L), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public long SearchObject
{
get { return m_SearchObject; }
set
{
if (m_SearchObject != value)
{
m_SearchObject = value;
UpdateQuerySearchObjectID();
}
}
}
[Browsable(false), DefaultValue(-1L), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public QuerySearchObject_DB QuerySearchObjectDbService { get; set; }
[Browsable(false), DefaultValue(0), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int Order
{
get { return m_Order; }
set
{
if (m_Order != value)
{
m_Order = value;
UpdateQuerySearchObjectOrder();
}
}
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFFObject
{
get { return m_IsFFObject; }
}
private long m_FormType = -1L;
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new long FormType
{
get { return m_FormType; }
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HACode ObjectHACode
{
get { return m_ObjectHACode; }
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public object ReportType
{
get { return m_ReportType; }
set
{
if (m_ReportType != value)
{
m_ReportType = value;
}
}
}
[Browsable(false), DefaultValue(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ShowReportType
{
get
{
if (((m_SearchObject == 10082020) || // Vet Case
(m_SearchObject == 10082021) || // Vet Case Sample
(m_SearchObject == 10082022) || // Vet Case Test
(m_SearchObject == 10082038) // Zoonotic disease
) &&
(m_Order == 0)
)
{
return true;
}
else
{
return false;
}
}
}
[Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string CaptionText
{
get
{
if (Utils.IsEmpty(m_SearchObject) == false)
{
if (m_Order > 0)
{
return string.Format(
"{0} # {1}",
LookupCache.GetLookupValue(
m_SearchObject, LookupTables.SearchObject, "Name"),
m_Order);
}
return LookupCache.GetLookupValue(
m_SearchObject, LookupTables.SearchObject, "Name");
}
return ("");
}
}
private string GetFieldGroupCaption
{
get
{
string caption = CaptionText;
if (Utils.IsEmpty(caption) == false)
{
caption = string.Format("{0} - {1}", caption, EidssMessages.Get("msgFieldGroupSuffix", "Fields"));
}
return caption;
}
}
private string GetFilterGroupCaption
{
get
{
string caption = CaptionText;
if (Utils.IsEmpty(caption) == false)
{
caption = string.Format("{0} - {1}", caption, EidssMessages.Get("msgFilterGroupSuffix", "Filters"));
}
return caption;
}
}
public override bool ReadOnly
{
get { return base.ReadOnly; }
set
{
base.ReadOnly = value;
btnAdd.Enabled = (!value);
btnAddAll.Enabled = (!value);
btnRemove.Enabled = (!value);
btnRemoveAll.Enabled = (!value);
cbFilterByDiagnosis.Enabled = (!value);
gvSelectedField.OptionsBehavior.Editable = (!value);
cbReportType.Enabled = (!value);
//old filter//QuerySearchFilter.Enabled = (!value);
qsoFilter.Enabled = (!value);
}
}
#endregion
#region Bindings
private void BindAvailableFieldList()
{
string filterByDiagnosis = "";
if (m_IsFFObject)
{
//Core.LookupBinder.BindParameterForFFTypeLookup(lbcAvailableField);
LookupBinder.BindParameterForFFTypeLookup(imlbcAvailableField);
if ((m_FormType == 10034010) || //Human Clinical Signs
(m_FormType == 10034011)) //Human Epi Investigations
{
LookupBinder.BindDiagnosisHACodeLookup(cbFilterByDiagnosis, baseDataSet, LookupTables.HumanStandardDiagnosis, null);
filterByDiagnosis = " and DiagnosisString like '%'";
}
}
else
{
//Core.LookupBinder.BindSearchFieldLookup(lbcAvailableField);
LookupBinder.BindSearchFieldLookup(imlbcAvailableField);
}
//DataView dv = (DataView)lbcAvailableField.DataSource;
var dv = (DataView)imlbcAvailableField.DataSource;
dv.RowFilter = string.Format("idfsSearchObject = '{0}' and blnAvailable = 1 {1}", m_SearchObject, filterByDiagnosis);
}
private void BindSelectedFieldList()
{
gcSelectedField.DataSource = null;
gcSelectedField.DataSource = new DataView(
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField],
"",
"FieldCaption",
DataViewRowState.CurrentRows);
imTypeImage.BorderStyle = BorderStyles.NoBorder;
imTypeImage.Items.Clear();
imTypeImage.Items.AddRange(new[]
{
new ImageComboBoxItem("", 0, 0),
new ImageComboBoxItem("", 1, 1),
new ImageComboBoxItem("", 2, 2),
new ImageComboBoxItem("", 3, 3),
new ImageComboBoxItem("", 4, 4),
new ImageComboBoxItem("", 5, 5),
new ImageComboBoxItem("", 6, 6),
new ImageComboBoxItem("", 7, 7),
new ImageComboBoxItem("", 8, 8)
});
if (ReadOnly)
{
gvSelectedField.OptionsBehavior.Editable = false;
}
}
private void UpdateFieldList()
{
//if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null))
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null))
{
var dvSelectedField = (DataView)gcSelectedField.DataSource;
//DataView dvAvailableField = (DataView)lbcAvailableField.DataSource;
var dvAvailableField = (DataView)imlbcAvailableField.DataSource;
int ind;
foreach (DataRow r in dvAvailableField.Table.Rows)
{
if (Utils.Str(r["idfsSearchObject"]) == Utils.Str(m_SearchObject))
{
r["blnAvailable"] = true;
}
}
for (ind = 0; ind < dvSelectedField.Count; ind++)
{
DataRowView rSelected = dvSelectedField[ind];
DataRow rAvailable;
if (m_IsFFObject)
{
string fieldKey = Utils.Str(rSelected["FieldAlias"]);
rAvailable = dvAvailableField.Table.Rows.Find(fieldKey);
}
else
{
rAvailable = dvAvailableField.Table.Rows.Find(rSelected["idfsSearchField"]);
}
if (rAvailable != null)
{
rAvailable.BeginEdit();
rAvailable["blnAvailable"] = false;
rAvailable.EndEdit();
}
}
if (dvAvailableField.Count >= 0)
{
//lbcAvailableField.SelectedIndex = 0;
imlbcAvailableField.SelectedIndex = 0;
}
}
}
private void BindReportType()
{
LookupBinder.BindBaseLookup(cbReportType, baseDataSet, QuerySearchObject_DB.tasQuerySearchObject + ".idfsReportType", bv.common.db.BaseReferenceType.rftCaseReportType, false);
}
private void BindFilterTree()
{
//if (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))
//{
// m_FilterControlHelper.Bind(
// (long) baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"],
// baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].DefaultView,
// baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].DefaultView);
//}
//else
//{
// m_FilterControlHelper.Bind(
// (long) baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"], null,
// baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].DefaultView);
//}
// TODO: check if new filter control shall be binded in two different ways
qsoFilter.Bind((long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"], baseDataSet);
}
protected override void DefineBinding()
{
if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) &&
(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0) &&
(Utils.IsEmpty(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"]) == false) &&
(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] is long) &&
((long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] != -1L))
{
m_SearchObject =
(long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"];
}
BindAvailableFieldList();
BindSelectedFieldList();
BindFilterTree();
BindReportType();
}
private void QuerySearchObjectInfo_AfterLoadData(object sender, EventArgs e)
{
UpdateQuerySearchObjectID();
UpdateFieldList();
UpdateConditionText();
}
#endregion
#region Update Methods
private void UpdateConditionList(object aQuerySearchFieldID)
{
if (Utils.IsEmpty(aQuerySearchFieldID))
{
return;
}
if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup)))
{
UpdateConditionText();
}
}
/// <summary>
/// Updates visibility of Report Type control and location of other controls depending on specified Search Object Id.
/// </summary>
/// <param name="searchObjectId">Search Object Identifier to determine state of visibility.</param>
/// <param name="order">Search Object order in the tree to determine state of visibility.</param>
private void UpdateVisibilityOfReportTypeBySearchObject
(
long searchObjectId,
int order
)
{
bool isVisible = ((searchObjectId == 10082020) || // Vet Case
(searchObjectId == 10082021) || // Vet Case Sample
(searchObjectId == 10082022) || // Vet Case Test
(searchObjectId == 10082038) // Zoonotic disease
) &&
(order == 0);
if (lblReportType != null)
{
lblReportType.Visible = isVisible;
}
if (cbReportType != null)
{
cbReportType.Visible = isVisible;
}
if (isVisible)
{
if ((cbReportType.Tag == null) || ((cbReportType.Tag != null) && (cbReportType.Tag.ToString() != "{M}")))
{
cbReportType.Tag = "{M}";
SetControlMandatoryState(cbReportType);
}
if (lblFilter != null)
{
lblFilter.Top = 30;
}
//old filter//if ((QuerySearchFilter != null) && (splitContainerFilters.Panel1 != null))
//old filter//{
//old filter// QuerySearchFilter.Top = 48;
//old filter// QuerySearchFilter.Height = splitContainerFilters.Panel1.Height - 48;
//old filter//}
if ((qsoFilter != null) && (splitContainerFilters.Panel1 != null))
{
qsoFilter.Top = 48;
qsoFilter.Height = splitContainerFilters.Panel1.Height - 48;
}
}
else
{
if ((cbReportType.Tag == null) || ((cbReportType.Tag != null) && (!string.IsNullOrWhiteSpace(cbReportType.Tag.ToString()))))
{
cbReportType.Tag = "";
}
if (lblFilter != null)
{
lblFilter.Top = 2;
}
//old filter//if ((QuerySearchFilter != null) && (splitContainerFilters.Panel1 != null))
//old filter//{
//old filter// QuerySearchFilter.Top = 22;
//old filter// QuerySearchFilter.Height = splitContainerFilters.Panel1.Height - 22;
//old filter//}
if ((qsoFilter != null) && (splitContainerFilters.Panel1 != null))
{
qsoFilter.Top = 22;
qsoFilter.Height = splitContainerFilters.Panel1.Height - 22;
}
}
}
/// <summary>
/// Updates visibility of diagnosis controls and location of other controls depending on specified form type.
/// </summary>
/// <param name="formType">Form type to determine state of visibility.</param>
private void UpdateVisibilityOfDiagnosisByFormType
(
long formType
)
{
bool isVisible = (formType == 10034010) || // Human Clinical Signs
(formType == 10034011); // Human Epi Investigations
bool ret = false;
if (lblFilterByDiagnosis != null)
{
if (lblFilterByDiagnosis.Visible == isVisible)
{
ret = true;
}
lblFilterByDiagnosis.Visible = isVisible;
}
if (cbFilterByDiagnosis != null)
{
cbFilterByDiagnosis.Visible = isVisible;
}
if (ret)
{
return;
}
if (isVisible)
{
if (splitContainerFields != null)
{
splitContainerFields.Top = 26;
splitContainerFields.Height = navSearchFields.Height - 64;
// Height of Navigator bar is greater that 64. Validaion is not needed.
}
}
else
{
if (splitContainerFields != null)
{
splitContainerFields.Top = 0;
splitContainerFields.Height = navSearchFields.Height - 38;
// Height of Navigator bar is greater that 38. Validaion is not needed.
}
}
}
private void UpdateFFType()
{
DataView dvObject = LookupCache.Get(LookupTables.SearchObject);
if (dvObject != null)
{
dvObject.RowFilter = string.Format("idfsSearchObject = {0}", m_SearchObject);
if ((dvObject.Count > 0) && (Utils.IsEmpty(dvObject[0]["idfsFormType"]) == false) &&
(dvObject[0]["idfsFormType"] is long) && ((long)dvObject[0]["idfsFormType"] != -1L))
{
//if ((m_IsFFObject == false) && (lbcAvailableField.DataSource != null))
if ((m_IsFFObject == false) && (imlbcAvailableField.DataSource != null))
{
BindAvailableFieldList();
}
m_IsFFObject = true;
m_FormType = (long)dvObject[0]["idfsFormType"];
UpdateVisibilityOfDiagnosisByFormType(m_FormType);
return;
}
}
//if (m_IsFFObject && lbcAvailableField.DataSource != null)
if (m_IsFFObject && imlbcAvailableField.DataSource != null)
{
BindAvailableFieldList();
}
m_IsFFObject = false;
m_FormType = -1L;
UpdateVisibilityOfDiagnosisByFormType(m_FormType);
}
private void UpdateObjectHACode()
{
DataView dvObject = LookupCache.Get(LookupTables.SearchObject);
if (dvObject != null)
{
dvObject.RowFilter = string.Format("idfsSearchObject = {0}", m_SearchObject);
if ((dvObject.Count > 0) && (Utils.IsEmpty(dvObject[0]["intHACode"]) == false))
{
m_ObjectHACode = (HACode)dvObject[0]["intHACode"];
//old filter//if (m_FilterControlHelper != null)
//old filter//{
//old filter// m_FilterControlHelper.ObjectHACode = m_ObjectHACode;
//old filter//}
if (qsoFilter != null)
{
qsoFilter.ObjectHACode = m_ObjectHACode;
}
return;
}
}
m_ObjectHACode = HACode.None;
//old filter//if (m_FilterControlHelper != null)
//old filter//{
//old filter// m_FilterControlHelper.ObjectHACode = m_ObjectHACode;
//old filter//}
if (qsoFilter != null)
{
qsoFilter.ObjectHACode = m_ObjectHACode;
}
}
private void UpdateQuerySearchObjectID()
{
if (IsDesignMode())
{
return;
}
grpSearchFields.Caption = GetFieldGroupCaption;
grcQueryObjectFiltration.Text = GetFilterGroupCaption;
UpdateVisibilityOfReportTypeBySearchObject(m_SearchObject, m_Order);
UpdateFFType();
UpdateObjectHACode();
if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) &&
(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0))
{
if (Utils.Str(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"]) !=
Utils.Str(m_SearchObject))
{
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsReportType"] = DBNull.Value;
if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)) &&
(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count > 0))
{
int ind;
for (ind = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count - 1; ind >= 0; ind--)
{
if (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind].RowState != DataRowState.Deleted)
{
UpdateConditionList(
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind]["idfQuerySearchField"]);
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind].Delete();
//old filter//m_FilterControlHelper.Refresh();
}
}
}
UpdateFieldList();
if (Utils.IsEmpty(m_SearchObject))
{
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] = DBNull.Value;
}
else
{
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] = m_SearchObject;
}
qsoFilter.RefreshNodes();
}
}
//if (lbcAvailableField.DataSource != null)
if (imlbcAvailableField.DataSource != null)
{
//DataView dv = (DataView)lbcAvailableField.DataSource;
var dv = (DataView)imlbcAvailableField.DataSource;
dv.RowFilter = string.Format("idfsSearchObject = {0} and blnAvailable = 1 ", m_SearchObject);
}
}
private void UpdateQuerySearchObjectOrder()
{
grpSearchFields.Caption = GetFieldGroupCaption;
grcQueryObjectFiltration.Text = GetFilterGroupCaption;
if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) &&
(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0))
{
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["intOrder"] = m_Order;
}
UpdateVisibilityOfReportTypeBySearchObject(m_SearchObject, m_Order);
}
private string GetConditionText(long aQueryConditionGroupID, bool addOperation)
{
if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false))
{
return "";
}
DataRow rGroup = baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Find(aQueryConditionGroupID);
if ((rGroup == null) || (rGroup.RowState == DataRowState.Deleted))
{
return "";
}
string strOr = "";
string strNot = "";
if (addOperation)
{
if (Utils.IsEmpty(rGroup["blnJoinByOr"]) == false)
{
if ((bool)rGroup["blnJoinByOr"])
{
strOr = " " + EidssMessages.Get("msgOR", "OR");
}
else
{
strOr = " " + EidssMessages.Get("msgAND", "AND");
}
}
if (!Utils.IsEmpty(rGroup["blnUseNot"]) && ((bool)rGroup["blnUseNot"]))
{
strNot = " " + EidssMessages.Get("msgNOT", "NOT");
}
}
string cond = strOr + strNot;
if (cond.Length > 0)
{
cond = cond + " ";
}
cond = cond + "{0}";
if (Utils.IsEmpty(rGroup["idfQuerySearchFieldCondition"]) == false)
{
return string.Format(cond, rGroup["SearchFieldConditionText"]);
}
cond = string.Format(cond, "({0})");
DataRow[] dr =
baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Select(
string.Format("idfParentQueryConditionGroup = {0} ", aQueryConditionGroupID), "intOrder", DataViewRowState.CurrentRows);
foreach (DataRow r in dr)
{
cond = string.Format(cond, GetConditionText((long)r["idfQueryConditionGroup"], true) + "{0}");
}
return string.Format(cond, "");
}
private void UpdateConditionText()
{
if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false))
{
return;
}
foreach (DataRow r in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows)
{
if (r.RowState != DataRowState.Deleted)
{
if (r["idfQueryConditionGroup"] != DBNull.Value)
r["SearchFieldConditionText"] = GetConditionText((long)r["idfQueryConditionGroup"], false);
else if (r["idfParentQueryConditionGroup"] != DBNull.Value)
r["SearchFieldConditionText"] = GetConditionText((long)r["idfParentQueryConditionGroup"], false);
}
}
}
#endregion
#region Handlers
private void btnAdd_Click(object sender, EventArgs e)
{
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
if ((imlbcAvailableField.SelectedIndices != null) &&
(imlbcAvailableField.SelectedIndices.Count >= 0))
{
int i = 0;
object[] selectedItems = new object[1];
Array.Resize(ref selectedItems, imlbcAvailableField.SelectedIndices.Count);
foreach (object it in imlbcAvailableField.SelectedIndices)
{
selectedItems.SetValue(it, i);
i++;
}
i = 0;
foreach (object it in selectedItems)
{
if ((it == null) || !(it is int))
{
continue;
}
int selectedInd = ((int)(it)) - i;
if ((selectedInd < 0) || (selectedInd >= dvAvailable.Count))
{
continue;
}
DataRow rAvailable = dvAvailable[selectedInd].Row;
if (rAvailable == null)
{
continue;
}
rAvailable.BeginEdit();
rAvailable["blnAvailable"] = false;
rAvailable.EndEdit();
long querySearchFieldID = -1L;
DataRow[] r = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Select(
string.Format("idfQuerySearchField <= {0}", querySearchFieldID), "idfQuerySearchField");
if (r.Length > 0)
{
if (r[0].RowState != DataRowState.Deleted)
{
querySearchFieldID = (long)(r[0]["idfQuerySearchField"]) - 1;
}
else
{
querySearchFieldID = (long)(r[0]["idfQuerySearchField", DataRowVersion.Original]) - 1;
}
}
DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].NewRow();
rSelected["idfQuerySearchField"] = querySearchFieldID;
rSelected["idfQuerySearchObject"] =
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"];
rSelected["idfsSearchField"] = rAvailable["idfsSearchField"];
if (m_IsFFObject)
{
rSelected["FieldCaption"] = rAvailable["ParameterName"];
rSelected["blnShow"] = 1;
rSelected["idfsParameter"] = rAvailable["idfsParameter"];
rSelected["FieldAlias"] = rAvailable["FieldAlias"];
rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
}
else
{
rSelected["FieldCaption"] = rAvailable["FieldCaption"];
rSelected["blnShow"] = 1;
rSelected["idfsParameter"] = DBNull.Value;
rSelected["FieldAlias"] = rAvailable["strSearchFieldAlias"];
rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
}
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Add(rSelected);
//m_FilterControlHelper.Refresh();
qsoFilter.RefreshNodes();
i++;
}
}
//if ((imlbcAvailableField.SelectedIndex >= 0) &&
// (imlbcAvailableField.SelectedIndex < dvAvailable.Count))
//{
// //DataRow rAvailable = dvAvailable[lbcAvailableField.SelectedIndex].Row;
// DataRow rAvailable = dvAvailable[imlbcAvailableField.SelectedIndex].Row;
// rAvailable.BeginEdit();
// rAvailable["blnAvailable"] = false;
// rAvailable.EndEdit();
// long querySearchFieldID = -1L;
// DataRow[] r = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Select(
// string.Format("idfQuerySearchField <= {0}", querySearchFieldID), "idfQuerySearchField");
// if (r.Length > 0)
// {
// if (r[0].RowState != DataRowState.Deleted)
// {
// querySearchFieldID = (long) (r[0]["idfQuerySearchField"]) - 1;
// }
// else
// {
// querySearchFieldID = (long) (r[0]["idfQuerySearchField", DataRowVersion.Original]) - 1;
// }
// }
// DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].NewRow();
// rSelected["idfQuerySearchField"] = querySearchFieldID;
// rSelected["idfQuerySearchObject"] =
// baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"];
// rSelected["idfsSearchField"] = rAvailable["idfsSearchField"];
// if (m_IsFFObject)
// {
// rSelected["FieldCaption"] = rAvailable["ParameterName"];
// rSelected["blnShow"] = 1;
// rSelected["idfsParameter"] = rAvailable["idfsParameter"];
// rSelected["FieldAlias"] = rAvailable["FieldAlias"];
// rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
// }
// else
// {
// rSelected["FieldCaption"] = rAvailable["FieldCaption"];
// rSelected["blnShow"] = 1;
// rSelected["idfsParameter"] = DBNull.Value;
// rSelected["FieldAlias"] = rAvailable["strSearchFieldAlias"];
// rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
// }
// baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Add(rSelected);
// m_FilterControlHelper.Refresh();
// qsoFilter.RefreshNodes();
//}
}
}
private void imlbcAvailableField_MouseDoubleClick(object sender, MouseEventArgs e)
{
if ((!ReadOnly) &&
(e.Button == MouseButtons.Left) &&
(imlbcAvailableField.SelectedIndex >= 0) &&
imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Contains(e.Location))
{
btnAdd_Click(sender, new EventArgs());
}
}
private void imlbcAvailableField_MouseMove(object sender, MouseEventArgs e)
{
var listBoxControl = sender as ImageListBoxControl;
if (listBoxControl != null)
{
int index = listBoxControl.IndexFromPoint(new Point(e.X, e.Y));
string item = "";
var point = new Point(e.X, e.Y);
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
DataRowView r = null;
if (index != -1)
{
r = listBoxControl.GetItem(index) as DataRowView;
}
else if ((imlbcAvailableField.SelectedIndex >= 0) &&
(imlbcAvailableField.SelectedIndex < dvAvailable.Count))
{
r = dvAvailable[imlbcAvailableField.SelectedIndex];
point = new Point(
imlbcAvailableField.Right,
imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Top);
}
if (r != null)
{
if (m_IsFFObject)
{
item = r["ParameterName"] as string;
}
else
{
item = r["FieldCaption"] as string;
}
}
}
if (Utils.IsEmpty(item) == false)
{
ttcAvailableField.ShowHint(item, listBoxControl.PointToScreen(point));
}
else
{
ttcAvailableField.HideHint();
}
}
}
private void imlbcAvailableField_MouseLeave(object sender, EventArgs e)
{
ttcAvailableField.HideHint();
}
private void imlbcAvailableField_SelectedIndexChanged(object sender, EventArgs e)
{
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
string item = "";
if ((imlbcAvailableField.SelectedIndex >= 0) &&
(imlbcAvailableField.SelectedIndex < dvAvailable.Count))
{
DataRowView r = dvAvailable[imlbcAvailableField.SelectedIndex];
if (r != null)
{
if (m_IsFFObject)
{
item = r["ParameterName"] as string;
}
else
{
item = r["FieldCaption"] as string;
}
}
}
if (Utils.IsEmpty(item) == false)
{
ttcAvailableField.ShowHint(item, imlbcAvailableField.PointToScreen(new Point(
imlbcAvailableField.Right,
imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Top)));
}
else
{
ttcAvailableField.HideHint();
}
}
}
private object[] GetSelectedValues(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName)
{
int[] selectedRows = view.GetSelectedRows();
object[] result = new object[selectedRows.Length];
for (int i = 0; i < selectedRows.Length; i++)
{
int rowHandle = selectedRows[i];
if (!view.IsGroupRow(rowHandle))
{
result[i] = view.GetRowCellValue(rowHandle, fieldName);
}
else
result[i] = DBNull.Value; // default value
}
return result;
}
private void btnRemove_Click(object sender, EventArgs e)
{
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
var dvSelected = (DataView)gcSelectedField.DataSource;
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
if ((gvSelectedField.FocusedRowHandle >= 0) &&
(gvSelectedField.FocusedRowHandle < dvSelected.Count) &&
(gvSelectedField.GetSelectedRows() != null) &&
(gvSelectedField.GetSelectedRows().Length > 0))
{
object[] selectedItems = GetSelectedValues(gvSelectedField, "idfQuerySearchField");
foreach (object it in selectedItems)
{
if ((it == null) || ((!(it is long)) && (!(it is int))))
{
continue;
}
long selectedValue = ((long)(it));
DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Find(selectedValue);
if ((rSelected != null) && (rSelected.RowState != DataRowState.Deleted))
{
DataRow rAvailable;
if (m_IsFFObject)
{
string fieldKey = Utils.Str(rSelected["FieldAlias"]);
rAvailable = dvAvailable.Table.Rows.Find(fieldKey);
}
else
{
rAvailable = dvAvailable.Table.Rows.Find(rSelected["idfsSearchField"]);
}
if (rAvailable != null)
{
rAvailable.BeginEdit();
rAvailable["blnAvailable"] = true;
rAvailable.EndEdit();
}
UpdateConditionList(rSelected["idfQuerySearchField"]);
rSelected.Delete();
//old filter//m_FilterControlHelper.Refresh();
qsoFilter.RefreshNodes();
}
}
//DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Find(
// gvSelectedField.GetFocusedRowCellValue("idfQuerySearchField"));
//if ((rSelected != null) && (rSelected.RowState != DataRowState.Deleted))
//{
// //DataView dvAvailable = (DataView)lbcAvailableField.DataSource;
// var dvAvailable = (DataView) imlbcAvailableField.DataSource;
// DataRow rAvailable;
// if (m_IsFFObject)
// {
// string fieldKey = Utils.Str(rSelected["FieldAlias"]);
// rAvailable = dvAvailable.Table.Rows.Find(fieldKey);
// }
// else
// {
// rAvailable = dvAvailable.Table.Rows.Find(rSelected["idfsSearchField"]);
// }
// if (rAvailable != null)
// {
// rAvailable.BeginEdit();
// rAvailable["blnAvailable"] = true;
// rAvailable.EndEdit();
// }
// UpdateConditionList(rSelected["idfQuerySearchField"]);
// rSelected.Delete();
// m_FilterControlHelper.Refresh();
// qsoFilter.RefreshNodes();
//}
}
}
}
private void gvSelectedField_RowCellClick(object sender, RowCellClickEventArgs e)
{
if ((!ReadOnly) &&
(e.Button == MouseButtons.Left) &&
(e.Clicks == 2) &&
(e.RowHandle >= 0) &&
(e.Column.FieldName == "FieldCaption"))
{
btnRemove_Click(sender, new EventArgs());
}
}
private void btnAddAll_Click(object sender, EventArgs e)
{
//if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
//DataView dvAvailable = (DataView)lbcAvailableField.DataSource;
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
long querySearchFieldID = -1L;
if (dvAvailable.Count > 0)
{
int ind;
DataRow[] r = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Select(
string.Format("idfQuerySearchField <= {0}", querySearchFieldID), "idfQuerySearchField");
if (r.Length > 0)
{
if (r[0].RowState != DataRowState.Deleted)
{
querySearchFieldID = (long)(r[0]["idfQuerySearchField"]) - 1;
}
else
{
querySearchFieldID = (long)(r[0]["idfQuerySearchField", DataRowVersion.Original]) - 1;
}
}
for (ind = dvAvailable.Count - 1; ind >= 0; ind--)
{
DataRow rAvailable = dvAvailable[ind].Row;
rAvailable.BeginEdit();
rAvailable["blnAvailable"] = false;
rAvailable.EndEdit();
DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].NewRow();
rSelected["idfQuerySearchField"] = querySearchFieldID;
rSelected["idfQuerySearchObject"] =
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"];
rSelected["idfsSearchField"] = rAvailable["idfsSearchField"];
if (m_IsFFObject)
{
rSelected["FieldCaption"] = rAvailable["ParameterName"];
rSelected["blnShow"] = 1;
rSelected["idfsParameter"] = rAvailable["idfsParameter"];
rSelected["FieldAlias"] = rAvailable["FieldAlias"];
rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
}
else
{
rSelected["FieldCaption"] = rAvailable["FieldCaption"];
rSelected["blnShow"] = 1;
rSelected["idfsParameter"] = DBNull.Value;
rSelected["FieldAlias"] = rAvailable["strSearchFieldAlias"];
rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"];
}
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Add(rSelected);
querySearchFieldID = querySearchFieldID - 1;
}
//old filter//m_FilterControlHelper.Refresh();
qsoFilter.RefreshNodes();
}
}
}
private void btnRemoveAll_Click(object sender, EventArgs e)
{
//if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) &&
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)))
{
for (int ind = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count - 1; ind >= 0; ind--)
{
DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind];
if (rSelected.RowState != DataRowState.Deleted)
{
//DataView dvAvailable = (DataView)lbcAvailableField.DataSource;
var dvAvailable = (DataView)imlbcAvailableField.DataSource;
DataRow rAvailable;
if (m_IsFFObject)
{
string fieldKey = Utils.Str(rSelected["FieldAlias"]);
rAvailable = dvAvailable.Table.Rows.Find(fieldKey);
}
else
{
rAvailable = dvAvailable.Table.Rows.Find(rSelected["idfsSearchField"]);
}
if (rAvailable != null)
{
rAvailable.BeginEdit();
rAvailable["blnAvailable"] = true;
rAvailable.EndEdit();
}
UpdateConditionList(rSelected["idfQuerySearchField"]);
rSelected.Delete();
}
}
//old filter//m_FilterControlHelper.Refresh();
qsoFilter.RefreshNodes();
}
}
private void cbFilterByDiagnosis_EditValueChanged(object sender, EventArgs e)
{
if ((m_FormType != 10034010) && //Human Clinical Signs
(m_FormType != 10034011)) //Human Epi Investigations
{
return;
}
if (imlbcAvailableField.DataSource == null)
{
return;
}
string filterByDiagnosis = " and DiagnosisString like '{0}'";
filterByDiagnosis = string.Format(filterByDiagnosis, Utils.IsEmpty(cbFilterByDiagnosis.EditValue)
? "%"
: string.Format("%{0};%", Utils.Str(cbFilterByDiagnosis.EditValue)));
var dv = (DataView)imlbcAvailableField.DataSource;
dv.RowFilter = string.Format("idfsSearchObject = '{0}' and blnAvailable = 1 {1}", m_SearchObject, filterByDiagnosis);
}
#endregion
#region Special Methods
private void DisplayFilter(object sender, FilterChangedEventArgs e)
{
//old filter//txtFilterText.Lines = m_FilterControlHelper.FilterLines;
txtFilterText.Lines = qsoFilter.FilterLines;
}
//public void SaveQuerySearchObjectInfo()
//{
// if (baseDataSet == null)
// {
// m_DataSet = null;
// return;
// }
// m_DataSet = baseDataSet.Copy();
//}
private static long GetNewNegativeID(long[] oldList, long idEx)
{
for (int i = 0; i < oldList.Length; i++)
{
if (oldList[i] == idEx)
{
return -(i + 1);
}
}
return 0;
}
//public void RestoreQuerySearchObjectInfo(long qsoID)
//{
// if (m_DataSet == null)
// {
// return;
// }
// object id = qsoID;
// LoadData(ref id);
// foreach (DataTable dt in baseDataSet.Tables)
// {
// dt.Rows.Clear();
// }
// baseDataSet.Merge(m_DataSet);
// baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"] = QuerySearchObjectDbService.ID;
// long fieldID = -1L;
// var fieldList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count];
// foreach (DataRow rField in baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows)
// {
// if (rField.RowState != DataRowState.Deleted)
// {
// fieldList[-fieldID - 1] = (long)rField["idfnQuerySearchField"];
// rField["idfQuerySearchField"] = fieldID;
// rField["idfQuerySearchObject"] = QuerySearchObjectDbService.ID;
// fieldID = fieldID - 1;
// }
// }
// long groupID = -1L;
// var groupList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Count];
// foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows)
// {
// if (rGroup.RowState != DataRowState.Deleted)
// {
// rGroup["idfQueryConditionGroup"] = groupID;
// rGroup["idfQuerySearchObject"] = QuerySearchObjectDbService.ID;
// groupID = groupID - 1;
// }
// }
// foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows)
// {
// if (rGroup.RowState != DataRowState.Deleted)
// {
// if (Utils.IsEmpty(rGroup["idfParentQueryConditionGroup"]) == false)
// {
// long groupIDNew = GetNewNegativeID(groupList, (long)rGroup["idfParentQueryConditionGroup"]);
// rGroup["idfParentQueryConditionGroup"] = groupIDNew;
// }
// }
// }
// DefineBinding();
// AfterLoad();
// m_DataSet = null;
//}
public void Copy(long qsoID, long queryID)
{
var mainQsoIdEx = (long)QuerySearchObjectDbService.ID;
QuerySearchObjectDbService.Copy(baseDataSet, qsoID, queryID);
long fieldId = -1L;
var fieldList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count];
foreach (DataRow rField in baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows)
{
if (rField.RowState != DataRowState.Deleted)
{
fieldList[(int)(-fieldId - 1)] = (long)rField["idfQuerySearchField"];
rField["idfQuerySearchField"] = fieldId;
rField["idfQuerySearchObject"] = QuerySearchObjectDbService.ID;
fieldId = fieldId - 1;
}
}
long subqueryId = -1L;
var subQueryList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasSubquery].Rows.Count];
foreach (DataRow rSubQuery in baseDataSet.Tables[QuerySearchObject_DB.tasSubquery].Rows)
{
if (rSubQuery.RowState != DataRowState.Deleted)
{
subQueryList[(int)(-subqueryId - 1)] = (long)rSubQuery["idfQuerySearchObject"];
rSubQuery["idflQuery"] = subqueryId;
rSubQuery["idfQuerySearchObject"] = subqueryId - 10000;
subqueryId = subqueryId - 1;
}
}
fieldId = -1L;
var subQueryFieldList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasSubquerySearchField].Rows.Count];
foreach (DataRow rSubQueryField in baseDataSet.Tables[QuerySearchObject_DB.tasSubquerySearchField].Rows)
{
if (rSubQueryField.RowState != DataRowState.Deleted)
{
subQueryFieldList[(int)(-fieldId - 1)] = (long)rSubQueryField["idfQuerySearchField"];
rSubQueryField["idfQuerySearchField"] = fieldId - 100000;
rSubQueryField["idfQuerySearchObject"] = GetNewNegativeID(subQueryList, (long)rSubQueryField["idfQuerySearchObject"]) - 10000;
fieldId = fieldId - 1;
}
}
long groupId = 0;
var groupList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Count];
long lastGroupId = 0;
foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows)
{
if (rGroup.RowState != DataRowState.Deleted)
{
if (Utils.IsEmpty(rGroup["idfQueryConditionGroup"]) == false)
{
var groupIdEx = (long)rGroup["idfQueryConditionGroup"];
if (groupIdEx != lastGroupId)
{
groupId = groupId - 1;
lastGroupId = groupIdEx;
groupList[(int)(-groupId - 1)] = groupIdEx;
}
rGroup["idfQueryConditionGroup"] = groupId;
}
if (Utils.IsEmpty(rGroup["idfSubQuerySearchObject"]) == false)
{
rGroup["idfSubQuerySearchObject"] = GetNewNegativeID(subQueryList, (long)rGroup["idfSubQuerySearchObject"]) - 10000;
}
if (Utils.IsEmpty(rGroup["idfQuerySearchObject"]) == true)
continue;
var groupQsoIdEx = (long)rGroup["idfQuerySearchObject"];
if (groupQsoIdEx == mainQsoIdEx)
{
rGroup["idfQuerySearchObject"] = QuerySearchObjectDbService.ID;
if (Utils.IsEmpty(rGroup["idfQuerySearchField"]) == false)
{
rGroup["idfQuerySearchField"] = GetNewNegativeID(fieldList, (long)rGroup["idfQuerySearchField"]);
}
}
else
{
rGroup["idfQuerySearchObject"] = GetNewNegativeID(subQueryList, groupQsoIdEx) - 10000;
if (Utils.IsEmpty(rGroup["idfQuerySearchField"]) == false)
{
rGroup["idfQuerySearchField"] = GetNewNegativeID(subQueryFieldList, (long)rGroup["idfQuerySearchField"]) - 100000;
}
}
}
}
foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows)
{
if (rGroup.RowState != DataRowState.Deleted)
{
if (Utils.IsEmpty(rGroup["idfParentQueryConditionGroup"]) == false)
{
long groupIdNew = GetNewNegativeID(groupList, (long)rGroup["idfParentQueryConditionGroup"]);
rGroup["idfParentQueryConditionGroup"] = groupIdNew;
}
}
}
BindFilterTree();
}
private void splitContainer_SplitGroupPanelCollapsed(object sender, SplitGroupPanelCollapsedEventArgs e)
{
UserConfigWriter.Instance.SetItem("CollapseFilterPanel", e.Collapsed.ToString());
UserConfigWriter.Instance.Save();
Config.ReloadSettings();
}
#endregion
#region Validate Methods
public bool ValidateQSOInfo()
{
if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject) == false))
{
return true;
}
var dvField = new DataView(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "", DataViewRowState.CurrentRows);
if (dvField.Count == 0)
{
return false;
}
//return m_FilterControlHelper.Validate();
return qsoFilter.Validate(true);
}
public void ShowQSOInfoError()
{
var dvField = new DataView(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "", DataViewRowState.CurrentRows);
if (dvField.Count == 0)
{
MessageForm.Show(EidssMessages.Get("msgNoSearchField",
"No fields are selected. Remove this search object or select some available fields."));
}
}
#endregion
#region Post Methods
public override bool HasChanges()
{
//old filter//return m_FilterControlHelper.HasChanges || base.HasChanges();
return qsoFilter.HasChanges || base.HasChanges();
}
private void QuerySearchObjectInfo_OnAfterPost(object sender, EventArgs e)
{
if ((baseDataSet == null) ||
(baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false))
{
return;
}
baseDataSet.AcceptChanges();
//old filter//m_FilterControlHelper.UpdateFieldInfo();
//old filter//m_FilterControlHelper.HasChanges = false;
qsoFilter.UpdateFieldInfo();
qsoFilter.HasChanges = false;
}
private void QuerySearchObjectInfo_OnBeforePost(object sender, EventArgs e)
{
//m_FilterControlHelper.Flush(null, 0);
qsoFilter.Flush();
}
#endregion
#region Get Functions
internal DataView GetQuerySearchFieldView()
{
DataView dvField = null;
if ((baseDataSet != null) && baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))
{
dvField = new DataView(
baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField],
"",
"idfQuerySearchField",
DataViewRowState.CurrentRows);
if (dvField.Count == 0)
{
dvField = null;
}
}
return dvField;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
/// <summary>
/// Reflection helpers for accessing properties.
/// </summary>
internal static class PropertyHelper
{
private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> DefaultPropertyConversionMapper = BuildPropertyConversionMapper();
#pragma warning disable S1144 // Unused private types or members should be removed. BUT they help CoreRT to provide config through reflection
private static readonly RequiredParameterAttribute _requiredParameterAttribute = new RequiredParameterAttribute();
private static readonly ArrayParameterAttribute _arrayParameterAttribute = new ArrayParameterAttribute(null, string.Empty);
private static readonly DefaultParameterAttribute _defaultParameterAttribute = new DefaultParameterAttribute();
private static readonly NLogConfigurationIgnorePropertyAttribute _ignorePropertyAttribute = new NLogConfigurationIgnorePropertyAttribute();
private static readonly NLogConfigurationItemAttribute _configPropertyAttribute = new NLogConfigurationItemAttribute();
private static readonly FlagsAttribute _flagsAttribute = new FlagsAttribute();
#pragma warning restore S1144 // Unused private types or members should be removed
private static Dictionary<Type, Func<string, ConfigurationItemFactory, object>> BuildPropertyConversionMapper()
{
return new Dictionary<Type, Func<string, ConfigurationItemFactory, object>>()
{
{ typeof(Layout), TryParseLayoutValue },
{ typeof(SimpleLayout), TryParseLayoutValue },
{ typeof(ConditionExpression), TryParseConditionValue },
{ typeof(Encoding), TryParseEncodingValue },
{ typeof(string), (stringvalue, factory) => stringvalue },
{ typeof(int), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Int32, CultureInfo.InvariantCulture) },
{ typeof(bool), (stringvalue, factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Boolean, CultureInfo.InvariantCulture) },
{ typeof(CultureInfo), (stringvalue, factory) => TryParseCultureInfo(stringvalue) },
{ typeof(Type), (stringvalue, factory) => Type.GetType(stringvalue.Trim(), true) },
{ typeof(LineEndingMode), (stringvalue, factory) => LineEndingMode.FromString(stringvalue.Trim()) },
{ typeof(Uri), (stringvalue, factory) => new Uri(stringvalue.Trim()) }
};
}
/// <summary>
/// Set value parsed from string.
/// </summary>
/// <param name="obj">object instance to set with property <paramref name="propertyName"/></param>
/// <param name="propertyName">name of the property on <paramref name="obj"/></param>
/// <param name="value">The value to be parsed.</param>
/// <param name="configurationItemFactory"></param>
internal static void SetPropertyFromString(object obj, string propertyName, string value, ConfigurationItemFactory configurationItemFactory)
{
var objType = obj.GetType();
InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", objType, propertyName, value);
if (!TryGetPropertyInfo(objType, propertyName, out var propInfo))
{
throw new NLogConfigurationException($"Unknown property '{propertyName}'='{value}' for '{objType.Name}'");
}
SetPropertyFromString(obj, propertyName, value, propInfo, configurationItemFactory);
}
internal static void SetPropertyFromString(object obj, string propertyName, string value, PropertyInfo propInfo, ConfigurationItemFactory configurationItemFactory)
{
try
{
Type propertyType = propInfo.PropertyType;
if (!TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out var newValue))
{
if (propInfo.IsDefined(_arrayParameterAttribute.GetType(), false))
{
throw new NotSupportedException($"Property {propertyName} on {obj.GetType().Name} is an array, and cannot be assigned a scalar value: '{value}'.");
}
propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;
if (!(TryGetEnumValue(propertyType, value, out newValue, true)
|| TryImplicitConversion(propertyType, value, out newValue)
|| TryFlatListConversion(obj, propInfo, value, configurationItemFactory, out newValue)
|| TryTypeConverterConversion(propertyType, value, out newValue)))
newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
propInfo.SetValue(obj, newValue, null);
}
catch (TargetInvocationException ex)
{
throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}'='{value}' on {obj.GetType().Name}", ex.InnerException);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
throw new NLogConfigurationException($"Error when setting property '{propInfo.Name}'='{value}' on {obj.GetType().Name}", exception);
}
}
/// <summary>
/// Get property info
/// </summary>
/// <param name="obj">object which could have property <paramref name="propertyName"/></param>
/// <param name="propertyName">property name on <paramref name="obj"/></param>
/// <param name="result">result when success.</param>
/// <returns>success.</returns>
internal static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result)
{
return TryGetPropertyInfo(obj.GetType(), propertyName, out result);
}
internal static Type GetArrayItemType(PropertyInfo propInfo)
{
var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>();
return arrayParameterAttribute?.ItemType;
}
internal static bool IsConfigurationItemType(Type type)
{
if (type is null || IsSimplePropertyType(type))
return false;
if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(type))
return true;
if (typeof(Layout).IsAssignableFrom(type))
return true;
// NLog will register no properties for types that are not marked with NLogConfigurationItemAttribute
return TryLookupConfigItemProperties(type) != null;
}
internal static Dictionary<string, PropertyInfo> GetAllConfigItemProperties(Type type)
{
// NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute
return TryLookupConfigItemProperties(type) ?? new Dictionary<string, PropertyInfo>();
}
private static Dictionary<string, PropertyInfo> TryLookupConfigItemProperties(Type type)
{
lock (parameterInfoCache)
{
// NLog will ignore all properties marked with NLogConfigurationIgnorePropertyAttribute
if (!parameterInfoCache.TryGetValue(type, out var cache))
{
if (TryCreatePropertyInfoDictionary(type, out cache))
{
parameterInfoCache[type] = cache;
}
else
{
parameterInfoCache[type] = null; // Not config item type
}
}
return cache;
}
}
internal static void CheckRequiredParameters(object o)
{
foreach (var configProp in GetAllConfigItemProperties(o.GetType()))
{
var propInfo = configProp.Value;
if (propInfo.IsDefined(_requiredParameterAttribute.GetType(), false))
{
object value = propInfo.GetValue(o, null);
if (value is null)
{
throw new NLogConfigurationException(
$"Required parameter '{propInfo.Name}' on '{o}' was not specified.");
}
}
}
}
internal static bool IsSimplePropertyType(Type type)
{
#if !NETSTANDARD1_3
if (Type.GetTypeCode(type) != TypeCode.Object)
#else
if (type.IsPrimitive() || type == typeof(string))
#endif
return true;
if (type == typeof(CultureInfo))
return true;
if (type == typeof(Type))
return true;
if (type == typeof(Encoding))
return true;
return false;
}
private static bool TryImplicitConversion(Type resultType, string value, out object result)
{
try
{
if (IsSimplePropertyType(resultType))
{
result = null;
return false;
}
MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { value.GetType() }, null);
if (operatorImplicitMethod is null || !resultType.IsAssignableFrom(operatorImplicitMethod.ReturnType))
{
result = null;
return false;
}
result = operatorImplicitMethod.Invoke(null, new object[] { value });
return true;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", value, resultType);
}
result = null;
return false;
}
private static bool TryNLogSpecificConversion(Type propertyType, string value, ConfigurationItemFactory configurationItemFactory, out object newValue)
{
if (DefaultPropertyConversionMapper.TryGetValue(propertyType, out var objectConverter))
{
newValue = objectConverter.Invoke(value, configurationItemFactory);
return true;
}
if (propertyType.IsGenericType() && propertyType.GetGenericTypeDefinition() == typeof(Layout<>))
{
var simpleLayout = new SimpleLayout(value, configurationItemFactory);
var concreteType = typeof(Layout<>).MakeGenericType(propertyType.GetGenericArguments());
newValue = Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public, null, new object[] { simpleLayout }, null);
return true;
}
newValue = null;
return false;
}
private static bool TryGetEnumValue(Type resultType, string value, out object result, bool flagsEnumAllowed)
{
if (!resultType.IsEnum())
{
result = null;
return false;
}
if (flagsEnumAllowed && resultType.IsDefined(_flagsAttribute.GetType(), false))
{
ulong union = 0;
foreach (string v in value.SplitAndTrimTokens(','))
{
FieldInfo enumField = resultType.GetField(v, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField is null)
{
throw new NLogConfigurationException($"Invalid enumeration value '{value}'.");
}
union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture);
}
result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture);
result = Enum.ToObject(resultType, result);
return true;
}
else
{
FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField is null)
{
throw new NLogConfigurationException($"Invalid enumeration value '{value}'.");
}
result = enumField.GetValue(null);
return true;
}
}
private static object TryParseCultureInfo(string stringValue)
{
stringValue = stringValue?.Trim();
if (string.IsNullOrEmpty(stringValue))
return CultureInfo.InvariantCulture;
else
return new CultureInfo(stringValue);
}
private static object TryParseEncodingValue(string stringValue, ConfigurationItemFactory configurationItemFactory)
{
_ = configurationItemFactory; // Discard unreferenced parameter
stringValue = stringValue.Trim();
if (string.Equals(stringValue, nameof(Encoding.UTF8), StringComparison.OrdinalIgnoreCase))
stringValue = Encoding.UTF8.WebName; // Support utf8 without hyphen (And not just Utf-8)
return Encoding.GetEncoding(stringValue);
}
private static object TryParseLayoutValue(string stringValue, ConfigurationItemFactory configurationItemFactory)
{
return new SimpleLayout(stringValue, configurationItemFactory);
}
private static object TryParseConditionValue(string stringValue, ConfigurationItemFactory configurationItemFactory)
{
return ConditionParser.ParseExpression(stringValue, configurationItemFactory);
}
/// <summary>
/// Try parse of string to (Generic) list, comma separated.
/// </summary>
/// <remarks>
/// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape
/// </remarks>
private static bool TryFlatListConversion(object obj, PropertyInfo propInfo, string valueRaw, ConfigurationItemFactory configurationItemFactory, out object newValue)
{
if (propInfo.PropertyType.IsGenericType() && TryCreateCollectionObject(obj, propInfo, valueRaw, out var newList, out var collectionAddMethod, out var propertyType))
{
var values = valueRaw.SplitQuoted(',', '\'', '\\');
foreach (var value in values)
{
if (!(TryGetEnumValue(propertyType, value, out newValue, false)
|| TryNLogSpecificConversion(propertyType, value, configurationItemFactory, out newValue)
|| TryImplicitConversion(propertyType, value, out newValue)
|| TryTypeConverterConversion(propertyType, value, out newValue)))
{
newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
collectionAddMethod.Invoke(newList, new object[] { newValue });
}
newValue = newList;
return true;
}
newValue = null;
return false;
}
private static bool TryCreateCollectionObject(object obj, PropertyInfo propInfo, string valueRaw, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType)
{
var collectionType = propInfo.PropertyType;
var typeDefinition = collectionType.GetGenericTypeDefinition();
#if !NET35
var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>);
#else
var isSet = typeDefinition == typeof(HashSet<>);
#endif
//not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive
if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc
{
object hashsetComparer = isSet ? ExtractHashSetComparer(obj, propInfo) : null;
//note: type.GenericTypeArguments is .NET 4.5+
collectionItemType = collectionType.GetGenericArguments()[0];
collectionObject = CreateCollectionObjectInstance(isSet ? typeof(HashSet<>) : typeof(List<>), collectionItemType, hashsetComparer);
//no support for array
if (collectionObject is null)
{
throw new NLogConfigurationException("Cannot create instance of {0} for value {1}", collectionType.ToString(), valueRaw);
}
collectionAddMethod = collectionObject.GetType().GetMethod("Add", BindingFlags.Instance | BindingFlags.Public);
if (collectionAddMethod is null)
{
throw new NLogConfigurationException("Add method on type {0} for value {1} not found", collectionType.ToString(), valueRaw);
}
return true;
}
collectionObject = null;
collectionAddMethod = null;
collectionItemType = null;
return false;
}
private static object CreateCollectionObjectInstance(Type collectionType, Type collectionItemType, object hashSetComparer)
{
var concreteType = collectionType.MakeGenericType(collectionItemType);
if (hashSetComparer != null)
{
var constructor = concreteType.GetConstructor(new[] { hashSetComparer.GetType() });
if (constructor != null)
return constructor.Invoke(new[] { hashSetComparer });
}
return Activator.CreateInstance(concreteType);
}
/// <summary>
/// Attempt to reuse the HashSet.Comparer from the original HashSet-object (Ex. StringComparer.OrdinalIgnoreCase)
/// </summary>
private static object ExtractHashSetComparer(object obj, PropertyInfo propInfo)
{
var exitingValue = propInfo.IsValidPublicProperty() ? propInfo.GetPropertyValue(obj) : null;
if (exitingValue != null)
{
// Found original HashSet-object. See if we can extract the Comparer
var comparerPropInfo = exitingValue.GetType().GetProperty("Comparer", BindingFlags.Instance | BindingFlags.Public);
if (comparerPropInfo.IsValidPublicProperty())
{
return comparerPropInfo.GetPropertyValue(exitingValue);
}
}
return null;
}
internal static bool TryTypeConverterConversion(Type type, string value, out object newValue)
{
try
{
var converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
newValue = converter.ConvertFromInvariantString(value);
return true;
}
newValue = null;
return false;
}
catch (MissingMethodException ex)
{
InternalLogger.Error(ex, "Error in lookup of TypeDescriptor for type={0} to convert value '{1}'", type, value);
newValue = null;
return false;
}
}
private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result)
{
if (!string.IsNullOrEmpty(propertyName))
{
PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
result = propInfo;
return true;
}
}
// NLog has special property-lookup handling for default-parameters (and array-properties)
var configProperties = GetAllConfigItemProperties(targetType);
return configProperties.TryGetValue(propertyName, out result);
}
private static bool TryCreatePropertyInfoDictionary(Type t, out Dictionary<string, PropertyInfo> result)
{
result = null;
try
{
if (!t.IsDefined(_configPropertyAttribute.GetType(), true))
{
return false;
}
result = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
foreach (PropertyInfo propInfo in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
try
{
var parameterName = LookupPropertySymbolName(propInfo);
if (string.IsNullOrEmpty(parameterName))
{
continue;
}
result[parameterName] = propInfo;
if (propInfo.IsDefined(_defaultParameterAttribute.GetType(), false))
{
// define a property with empty name (Default property name)
result[string.Empty] = propInfo;
}
}
catch (Exception ex)
{
InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", propInfo.Name, t);
}
}
}
catch (Exception ex)
{
InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", t);
}
return result != null;
}
private static string LookupPropertySymbolName(PropertyInfo propInfo)
{
if (propInfo.PropertyType is null)
return null;
if (IsSimplePropertyType(propInfo.PropertyType))
return propInfo.Name;
if (typeof(LayoutRenderers.LayoutRenderer).IsAssignableFrom(propInfo.PropertyType))
return propInfo.Name;
if (typeof(Layout).IsAssignableFrom(propInfo.PropertyType))
return propInfo.Name;
if (propInfo.IsDefined(_ignorePropertyAttribute.GetType(), false))
return null;
var arrayParameterAttribute = propInfo.GetFirstCustomAttribute<ArrayParameterAttribute>();
if (arrayParameterAttribute != null)
{
return arrayParameterAttribute.ElementName;
}
return propInfo.Name;
}
}
}
| |
//
// ProjectPackage.cs: A pkg-config package
//
// Authors:
// Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com>
//
// Copyright (C) 2008 Levi Bard
// Based on CBinding by Marcos David Marin Amador <MarcosMarin@gmail.com>
//
// This source code is licenced under The 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.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Mono.Addins;
using MonoDevelop.Core.Serialization;
namespace MonoDevelop.ValaBinding
{
public class ProjectPackage
{
[ItemProperty ("file")]
private string file;
[ItemProperty ("name")]
private string name;
[ItemProperty ("IsProject")]
private bool is_project;
public string Description {
get{ return description; }
set{ description = value; }
}
private string description;
public string Version {
get{ return version; }
set{ version = value; }
}
private string version;
public List<string> Requires {
get { return requires; }
}
private List<string> requires;
private static string[] packagePaths;
static ProjectPackage () {
packagePaths = ScanPackageDirs ();
}
protected ProjectPackage() {
requires = new List<string>();
description = string.Empty;
version = string.Empty;
}
public ProjectPackage (string file): this()
{
this.file = file;
this.name = Path.GetFileNameWithoutExtension(file);
this.is_project = false;
ParsePackage();
ParseRequires();
}
public ProjectPackage (ValaProject project): this()
{
name = project.Name;
ValaProjectConfiguration vpc = (ValaProjectConfiguration)(project.DefaultConfiguration);
file = Path.Combine (vpc.OutputDirectory, name + ".vapi");
is_project = true;
}
public string File {
get { return file; }
set { file = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public bool IsProject {
get { return is_project; }
set { is_project = value; }
}
public override bool Equals (object o)
{
ProjectPackage other = o as ProjectPackage;
if (other == null) return false;
return other.File.Equals (file);
}
public override int GetHashCode ()
{
return (file + name).GetHashCode ();
}
/// <summary>
/// Insert '\n's to make sure string isn't too long.
/// </summary>
/// <param name="desc">
/// The unprocessed description.
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// The processed description.
/// A <see cref="System.String"/>
/// </returns>
public static string ProcessDescription (string desc)
{
return Regex.Replace(desc, @"(.{1,80} )", "$&" + Environment.NewLine, RegexOptions.Compiled);
}
/// <summary>
/// Search for a .pc file for this package, and parse its relevant attributes
/// </summary>
protected void ParsePackage ()
{
string line, pcfile;
try {
foreach(string path in packagePaths) {
pcfile = Path.Combine (path, Path.ChangeExtension (Path.GetFileName (file), ".pc"));
if (!System.IO.File.Exists (pcfile)){ continue; }
using (StreamReader reader = new StreamReader (pcfile)) {
if (null == reader){ continue; }
while ((line = reader.ReadLine ()) != null) {
if (Regex.IsMatch(line, @"^\s*#", RegexOptions.Compiled))
continue;
// if (line.IndexOf ('=') >= 0)
// ParseVar (line);
if (line.IndexOf (':') >= 0)
ParseProperty (line);
}
return;
}
}
} catch (FileNotFoundException) {
// We just won't populate some fields
} catch (IOException) {
// We just won't populate some fields
}
}
protected void ParseProperty (string line)
{
string[] tokens = line.Split(new char[]{':'}, 2);
if(2 != tokens.Length){ return; }
string key = tokens[0];
string value = tokens[1].Trim();
if (value.Length <= 0)
return;
switch (key) {
case "Description":;
description = ProcessDescription (value);
break;
case "Version":
version = value;
break;
}
}
protected void ParseRequires ()
{
string line;
try {
using (StreamReader reader = new StreamReader (Path.ChangeExtension(file, ".deps"))) {
if(null == reader){ return; }
for(; null != (line = reader.ReadLine()); requires.Add(line));
}
} catch (FileNotFoundException) {
// We just won't populate requires
} catch (IOException) {
// We just won't populate requires
}
}
/// <summary>
/// Scans PKG_CONFIG_PATH and a few static directories
/// for potential pkg-config repositories
/// </summary>
/// <returns>
/// A <see cref="System.String"/> array: The potential directories
/// </returns>
private static string[] ScanPackageDirs ()
{
List<string> dirs = new List<string> ();
string pkg_var = Environment.GetEnvironmentVariable ("PKG_CONFIG_PATH");
string[] staticPaths = { "/usr/lib/pkgconfig",
"/usr/lib64/pkgconfig",
"/usr/share/pkgconfig",
"/usr/local/lib/pkgconfig",
"/usr/local/share/pkgconfig"
};
if (null != pkg_var){ dirs.AddRange(pkg_var.Split(new char[]{System.IO.Path.PathSeparator}, StringSplitOptions.RemoveEmptyEntries)); }
foreach(string dir in staticPaths) {
if(!dirs.Contains(dir)){ dirs.Add(dir); }
}
return dirs.ToArray ();
}
/// <summary>
/// Converts an absolute path to a relative one
/// </summary>
/// <param name="absolutePath">
/// A <see cref="System.String"/>: The absolute path
/// </param>
/// <param name="relativeTo">
/// A <see cref="System.String"/>: The path to which the output path shall be relative
/// </param>
/// <returns>
/// A <see cref="System.String"/>: The relative path from relativeTo to absolutePath
/// </returns>
public static string ToRelativePath (string absolutePath, string relativeTo) {
List<string> fileTokens = new List<string> (absolutePath.Split (Path.DirectorySeparatorChar)),
anchorTokens = new List<string> (relativeTo.Split (Path.DirectorySeparatorChar));
StringBuilder builder = new StringBuilder ();
int length = 0;
if (!Path.IsPathRooted(absolutePath)){ return absolutePath; }
if (absolutePath == relativeTo){ return Path.GetFileName (absolutePath); }
if (absolutePath.StartsWith (relativeTo) && Directory.Exists (relativeTo)) {
builder.AppendFormat (".{0}", Path.DirectorySeparatorChar);
}// if absolutePath is inside relativeTo
for (;0 != fileTokens.Count && 0 != anchorTokens.Count;) {
if (fileTokens[0] == anchorTokens[0]) {
fileTokens.RemoveAt (0);
anchorTokens.RemoveAt (0);
} else { break; }
}// strip identical leading path
for (int i=0; i < anchorTokens.Count-1; ++i) {
builder.AppendFormat ("..{0}", Path.DirectorySeparatorChar);
}// navigate out of anchor subdir
foreach (string token in fileTokens) {
builder.AppendFormat ("{0}{1}", token, Path.DirectorySeparatorChar);
}// append filepath
length = builder.Length;
if (0 < builder.Length && Path.DirectorySeparatorChar == builder[builder.Length-1]) {
--length;
}// check for trailing separator
return builder.ToString (0, length);
}// ToRelativePath
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace CloudBox.Controller
{
public class ColorWheel : Control
{
public event EventHandler SelectedColorChanged;
Color m_frameColor = Color.CadetBlue;
HSLColor m_selectedColor = new HSLColor(Color.BlanchedAlmond);
PathGradientBrush m_brush = null;
List<PointF> m_path = new List<PointF>();
List<Color> m_colors = new List<Color>();
double m_wheelLightness = 0.5;
public HSLColor SelectedHSLColor
{
get { return m_selectedColor; }
set
{
if (m_selectedColor == value)
return;
Invalidate(Util.Rect(ColorSelectorRectangle));
m_selectedColor = value;
if (SelectedColorChanged != null)
SelectedColorChanged(this, null);
Refresh();//Invalidate(Util.Rect(ColorSelectorRectangle));
}
}
public ColorWheel()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
using (SolidBrush b = new SolidBrush(BackColor))
{
e.Graphics.FillRectangle(b, ClientRectangle);
}
RectangleF wheelrect = WheelRectangle;
Util.DrawFrame(e.Graphics, wheelrect, 6, m_frameColor);
wheelrect = ColorWheelRectangle;
PointF center = Util.Center(wheelrect);
e.Graphics.SmoothingMode = SmoothingMode.HighSpeed;
if (m_brush == null)
{
m_brush = new PathGradientBrush(m_path.ToArray(), WrapMode.Clamp);
m_brush.CenterPoint = center;
m_brush.CenterColor = Color.White;
m_brush.SurroundColors = m_colors.ToArray();
}
e.Graphics.FillPie(m_brush, Util.Rect(wheelrect), 0, 360);
DrawColorSelector(e.Graphics);
if (Focused)
{
RectangleF r = WheelRectangle;
r.Inflate(-2,-2);
ControlPaint.DrawFocusRectangle(e.Graphics, Util.Rect(r));
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (m_brush != null)
m_brush.Dispose();
m_brush = null;
RecalcWheelPoints();
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
PointF mousepoint = new PointF(e.X, e.Y);
if (e.Button == MouseButtons.Left)
SetColor(mousepoint);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Focus();
PointF mousepoint = new PointF(e.X, e.Y);
if (e.Button == MouseButtons.Left)
SetColor(mousepoint);
}
protected override bool ProcessDialogKey(Keys keyData)
{
HSLColor c = SelectedHSLColor;
double hue = c.Hue;
int step = 1;
if ((keyData & Keys.Control) == Keys.Control)
step = 5;
if ((keyData & Keys.Up) == Keys.Up)
hue += step;
if ((keyData & Keys.Down) == Keys.Down)
hue -= step;
if (hue >= 360)
hue = 0;
if (hue < 0)
hue = 359;
if (hue != c.Hue)
{
c.Hue = hue;
SelectedHSLColor = c;
return true;
}
return base.ProcessDialogKey(keyData);
}
RectangleF ColorSelectorRectangle
{
get
{
HSLColor color = m_selectedColor;
double angleR = color.Hue * Math.PI / 180;
PointF center = Util.Center(ColorWheelRectangle);
double radius = Radius(ColorWheelRectangle);
radius *= color.Saturation;
double x = center.X + Math.Cos(angleR) * radius;
double y = center.Y - Math.Sin(angleR) * radius;
Rectangle colrect = new Rectangle(new Point((int)x, (int)y), new Size(0, 0));
colrect.Inflate(12, 12);
return colrect;
}
}
void DrawColorSelector(Graphics dc)
{
Rectangle r = Util.Rect(ColorSelectorRectangle);
PointF center = Util.Center(r);
Image image = SelectorImages.Image(SelectorImages.eIndexes.Donut);
dc.DrawImageUnscaled(image, (int)(center.X-image.Width/2), (int)(center.Y-image.Height/2));
}
RectangleF WheelRectangle
{
get
{
Rectangle r = ClientRectangle;
r.Width -= 1;
r.Height -= 1;
return r;
}
}
RectangleF ColorWheelRectangle
{
get
{
RectangleF r = WheelRectangle;
r.Inflate(-5, -5);
return r;
}
}
float Radius(RectangleF r)
{
PointF center = Util.Center(r);
float radius = Math.Min((r.Width / 2), (r.Height / 2));
return radius;
}
void RecalcWheelPoints()
{
m_path.Clear();
m_colors.Clear();
PointF center = Util.Center(ColorWheelRectangle);
float radius = Radius(ColorWheelRectangle);
double angle = 0;
double fullcircle = 360;
double step = 5;
while (angle < fullcircle)
{
double angleR = angle * (Math.PI/180);
double x = center.X + Math.Cos(angleR) * radius;
double y = center.Y - Math.Sin(angleR) * radius;
m_path.Add(new PointF((float)x,(float)y));
m_colors.Add(new HSLColor(angle, 1, m_wheelLightness).Color);
angle += step;
}
}
void SetColor(PointF mousepoint)
{
if (WheelRectangle.Contains(mousepoint) == false)
return;
PointF center = Util.Center(ColorWheelRectangle);
double radius = Radius(ColorWheelRectangle);
double dx = Math.Abs(mousepoint.X - center.X);
double dy = Math.Abs(mousepoint.Y - center.Y);
double angle = Math.Atan(dy / dx) / Math.PI * 180;
double dist = Math.Pow((Math.Pow(dx, 2) + (Math.Pow(dy, 2))), 0.5);
double saturation = dist/radius;
//if (dist > radius + 5) // give 5 pixels slack
// return;
if (dist < 6)
saturation = 0; // snap to center
if (mousepoint.X < center.X)
angle = 180 - angle;
if (mousepoint.Y > center.Y)
angle = 360 - angle;
SelectedHSLColor = new HSLColor(angle, saturation, SelectedHSLColor.Lightness);
}
}
}
| |
using UnityEngine;
using System.Collections;
public class battleGUI : MonoBehaviour {
string turnButtonName = "Turn Ship";
bool undoTurnVisible;
bool specialOrdersVisible;
bool weaponsVisible;
bool weapon1Selected;
bool weapon2Selected;
bool weapon3Selected;
bool weapon4Selected;
bool weaponsReady;
int buttonsCount = 0;
private int buttonWidth = 110;
private int buttonHeight = 20;
void OnGUI () {
if (BattleManager.instance.playersLoaded == true) {
Ship currentShip = BattleManager.instance.players [GameData.instance.battleData.currentPlayerIndex].selectedShip;
Player currentPlayer = BattleManager.instance.players [GameData.instance.battleData.currentPlayerIndex];
#region Next Ship Button
if(currentPlayer.phaze !=2){
// Make the first button. If it is pressed, next ship will be selected
if (GUI.Button (new Rect (20, 40, buttonWidth, buttonHeight), "Next Ship")) {
//if game not Paused
if(Time.timeScale != 0){
//for each of the players ships
for (int i = 0; i < currentPlayer.remainingShips.Count; i ++) {
//if the ship is the currently selected ship
if (currentPlayer.remainingShips [i] == currentShip) {
//if the next ship is on the list
if (i + 1 < currentPlayer.remainingShips.Count) {
//make the next ship the selected ship
BattleManager.instance.players[GameData.instance.battleData.currentPlayerIndex].selectedShip = currentPlayer.remainingShips [i + 1];
currentShip = currentPlayer.remainingShips [i+1];
//dont check the rest of the ships
break;
//if no next ship on list
} else {
//make first ship on list selected ship
BattleManager.instance.players[GameData.instance.battleData.currentPlayerIndex].selectedShip = currentPlayer.remainingShips [0];
currentShip = currentPlayer.remainingShips [0];
//dont check any more ships
break;
}
}
}
//Ste camera to selected ship
Camera.main.transform.position = new Vector3(currentShip.transform.position.x,Camera.main.transform.position.y,currentShip.transform.position.z);
//set so ship is moving not turning
currentPlayer.moving = true;
//set buttons to initial visability
undoTurnVisible = false;
weaponsVisible = false;
specialOrdersVisible = false;
//set weapon buttons to inital viability
weapon1Selected = false;
weapon2Selected = false;
weapon3Selected = false;
weapon4Selected = false;
weaponsReady = false;
//clear any weapons chosen to fire
currentPlayer.selectedWeaponsType = -1;
currentPlayer.weaponsSelected.Clear ();
currentPlayer.weaponsAvailable.Clear ();
}
}
}
#endregion
#region Movement Phase Main Buttons
if(currentPlayer.phaze == 0){
buttonsCount = 4;
#region Move/Turn Button
// If not moved enough to turn gray out turn button
GUI.color = Color.grey;
if (currentPlayer.moving == true) {
turnButtonName = "Turn Ship";
} else {
turnButtonName = "Move Ship";
}
//when moved enough turn back to white
if ((currentShip.movedThisTurn >= currentShip.minTurnDistance && currentShip.turnsRemaining > 0 || currentPlayer.moving == false) && currentShip.moveComplete == false) {
GUI.color = Color.white;
}
//button to alow a turn to be made
if (GUI.Button (new Rect (20, 70, buttonWidth, buttonHeight), turnButtonName)) {
//if not paused
if(Time.timeScale != 0){
//if in move mode
if (currentPlayer.moving == true) {
//if moved enough to turn
if (currentShip.movedThisTurn >= currentShip.minTurnDistance && currentShip.turnsRemaining > 0 && currentShip.moveComplete == false) {
//set to in turn mode
currentPlayer.moving = false;
currentShip.rotated = 0;
//reduce amount of turns available by 1
currentShip.turnsRemaining -= 1;
currentShip.turnsUsed += 1;
//modify the distance until next turn is alowwed to be made
currentShip.minTurnDistance = Mathf.RoundToInt (currentShip.movedThisTurn + currentShip.baseMinTurnDistance);
//record position of turn and angle turned from
currentShip.turnDistance.Add (currentShip.movedThisTurn);
currentShip.originalBearing .Add (currentShip.bearing);
//alow undo turn
undoTurnVisible = true;
}
} else {
currentPlayer.moving = true;
}
}
}
#endregion
#region Special Orders button
if (currentPlayer.specialOrdersAlowed && currentShip.specialOrderAllowed && currentShip.movedThisTurn == 0) {
GUI.color = Color.white;
} else {
GUI.color = Color.grey;
}
if (GUI.Button (new Rect (20, 100, buttonWidth, buttonHeight), "Special Orders")) {
if(Time.timeScale != 0 ){
if (specialOrdersVisible) {
specialOrdersVisible = false;
} else if (currentPlayer.specialOrdersAlowed && currentShip.specialOrderAllowed && currentShip.movedThisTurn == 0) {
specialOrdersVisible = true;
}
}
}
#endregion
#region Complete Move Button
if (currentShip.movedThisTurn < currentShip.minMove) {
GUI.color = Color.grey;
} else if(currentShip.moveComplete == false){
GUI.color = Color.white;
}else{
GUI.color = Color.grey;
}
if (GUI.Button (new Rect (20, 130, buttonWidth, buttonHeight), "Complete Move")) {
if(Time.timeScale != 0){
if (currentShip.movedThisTurn >= currentShip.minMove && currentShip.moveComplete == false) {
currentShip.moveComplete = true;
currentPlayer.shipUnMoved -= 1;
undoTurnVisible = false;
}
}
}
#endregion
}
#endregion
#region End Phase button
if (currentPlayer.shipUnMoved > 0) {
GUI.color = Color.grey;
} else {
GUI.color = Color.white;
}
if (GUI.Button (new Rect (20, 40 + buttonsCount * 30, buttonWidth, buttonHeight), "End Phase")) {
if(Time.timeScale != 0){
if (currentPlayer.phaze == 0) {
for(int i =0; i < currentPlayer.remainingShips.Count; i++){
currentPlayer.remainingShips[i].forwardVector = new Vector3 ( Mathf.Sin (currentPlayer.remainingShips[i].bearing * Mathf.Deg2Rad),0, Mathf.Cos (currentPlayer.remainingShips[i].bearing * Mathf.Deg2Rad));
}
if (currentPlayer.shipUnMoved == 0) {
BattleManager.instance.NextPhaze ();
}
} else if (currentPlayer.phaze == 1) {
weapon1Selected = false;
weapon2Selected = false;
weapon3Selected = false;
weapon4Selected = false;
weaponsReady = false;
currentPlayer.weaponsAvailable.Clear ();
currentPlayer.weaponsSelected.Clear ();
currentPlayer.selectedWeaponsType = -1;
BattleManager.instance.NextPhaze ();
} else if (currentPlayer.phaze == 2) {
BattleManager.instance.NextPhaze ();
} else {
BattleManager.instance.NextTurn ();
}
}
}
#endregion
#region Movement Phase Optional Buttons
#region Undo turn button
GUI.color = Color.white;
if (undoTurnVisible && currentShip.movedThisTurn == currentShip.turnDistance [currentShip.turnDistance.Count - 1]) {
if (GUI.Button (new Rect (buttonWidth + 30, 70, buttonWidth, buttonHeight), "Undo Turn")) {
if(Time.timeScale != 0){
currentShip.turnsRemaining += 1;
currentShip.turnsUsed -= 1;
currentShip.minTurnDistance -= Mathf.RoundToInt (currentShip.movedThisTurn);
currentShip.bearing = currentShip.originalBearing [currentShip.originalBearing.Count - 1];
currentShip.rotated = 0;
currentShip.originalBearing.RemoveAt (currentShip.originalBearing.Count - 1);
currentShip.turnDistance.RemoveAt (currentShip.turnDistance.Count - 1);
currentPlayer.moving = true;
}
}
}
#endregion
#region Special Orders
if (specialOrdersVisible) {
if (BattleManager.instance.playersLoaded) {
//when moved enough turn back to white
if (currentShip.specialOrderAllowed == false || currentPlayer.specialOrdersAlowed == false || currentShip.movedThisTurn > 0) {
GUI.color = Color.grey;
} else {
GUI.color = Color.white;
}
}
if (GUI.Button (new Rect (buttonWidth + 30, 100, buttonWidth, buttonHeight), "All Ahead")) {
if(Time.timeScale != 0){
currentShip.AheadFull ();
specialOrdersVisible = false;
}
}
if (GUI.Button (new Rect (buttonWidth + 30, 130, buttonWidth, buttonHeight), "New Heading")) {
if(Time.timeScale != 0){
currentShip.ComeToNewHeading ();
specialOrdersVisible = false;
}
}
if (GUI.Button (new Rect (buttonWidth + 30, 160, buttonWidth, buttonHeight), "Burn Retros")) {
if(Time.timeScale != 0){
currentShip.BurnRetros ();
specialOrdersVisible = false;
}
}
if (GUI.Button (new Rect (buttonWidth + 30, 190, buttonWidth, buttonHeight), "Lock On")) {
if(Time.timeScale != 0){
currentShip.LockOn ();
specialOrdersVisible = false;
}
}
if (GUI.Button (new Rect (buttonWidth + 30, 220, buttonWidth, buttonHeight), "Reload")) {
if(Time.timeScale != 0){
currentShip.Reload ();
specialOrdersVisible = false;
}
}
}
#endregion
#endregion
#region Shooting Phase Main Buttons
if(currentPlayer.phaze ==1){
buttonsCount = 7;
#region Next Target button
if(GUI.Button (new Rect(20, 70, buttonWidth, buttonHeight), "Next Target")){
if(Time.timeScale != 0){
for (int i = 0; i < currentPlayer.enemyShips.Count; i ++) {
if (currentPlayer.enemyShips [i] == currentShip.target) {
if (i + 1 < currentPlayer.enemyShips.Count) {
currentShip.target = currentPlayer.enemyShips [i + 1];
PlayerLog.instance.AddEvent ("Targeting " + currentShip.target.shipName);
break;
} else {
currentShip.target = currentPlayer.enemyShips [0];
PlayerLog.instance.AddEvent ("Targeting " + currentShip.target.shipName);
break;
}
}
}
currentPlayer.FindWeaponsAvailable();
weaponsVisible = false;
weapon1Selected = false;
weapon2Selected = false;
weapon3Selected = false;
weapon4Selected = false;
weaponsReady = false;
currentPlayer.selectedWeaponsType = -1;
currentPlayer.weaponsSelected.Clear ();
}
}
#endregion
#region Target Ordnance Button
if(GUI.Button (new Rect(20, 100, buttonWidth, buttonHeight), "Target Ordnance")){
if(Time.timeScale != 0){
}
}
#endregion
#region Select weapons button
if(currentPlayer.weaponsAvailable.Count == 0){
GUI.color = Color.grey;
}else{
GUI.color = Color.white;
}
if(GUI.Button (new Rect(20, 130, buttonWidth, buttonHeight), "Select Weapons")){
if(Time.timeScale != 0){
if(weaponsVisible == false){
if(currentPlayer.weaponsAvailable.Count != 0){
weaponsVisible = true;
}
}else{
weaponsVisible = false;
}
}
}
#endregion
#region Fire Button
if(weaponsReady == false){
GUI.color = Color.grey;
}else{
GUI.color = Color.white;
}
if(GUI.Button (new Rect(20, 160, buttonWidth, buttonHeight), "Fire")){
if(Time.timeScale != 0){
if(weaponsReady){
currentPlayer.Fire();
}
weapon1Selected = false;
weapon2Selected = false;
weapon3Selected = false;
weapon4Selected = false;
weaponsReady = false;
currentPlayer.weaponsSelected.Clear ();
currentPlayer.selectedWeaponsType = -1;
}
}
#endregion
#region Fire Nova Cannon
GUI.color = Color.white;
if(GUI.Button (new Rect(20, 190, buttonWidth, buttonHeight), "Fire Nova Can.")){
if(Time.timeScale != 0){
}
}
#endregion
#region Launch Ordnance Button
if(GUI.Button (new Rect(20, 220, buttonWidth, buttonHeight), "Launch Ord.")){
if(Time.timeScale != 0){
}
}
#endregion
}
#endregion
#region optional Shooting Phase Buttons
#region Weapons buttons
if(weaponsVisible){
if(currentPlayer.weaponsAvailable.Count >= 1){
if(weapon1Selected){
GUI.color = Color.green;
}else if((currentPlayer.weaponsAvailable[0].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[0].fired == false ){
GUI.color = Color.white;
}else{
GUI.color = Color.grey;
}
if(GUI.Button (new Rect(buttonWidth + 30, 130, buttonWidth + 50, buttonHeight), currentPlayer.weaponsAvailable[0].weaponName)){
if(Time.timeScale != 0){
if(weapon1Selected){
weapon1Selected = false;
currentPlayer.weaponsSelected.Remove(currentPlayer.weaponsAvailable[0]);
if(weapon1Selected == false && weapon2Selected == false && weapon3Selected == false && weapon4Selected == false){
currentPlayer.selectedWeaponsType = -1;
weaponsReady = false;
}
}else if((currentPlayer.weaponsAvailable[0].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[0].fired == false){
weapon1Selected = true;
weaponsReady = true;
currentPlayer.selectedWeaponsType = currentPlayer.weaponsAvailable[0].type;
currentPlayer.weaponsSelected.Add (currentPlayer.weaponsAvailable[0]);
}
}
}
}
if(currentPlayer.weaponsAvailable.Count >= 2){
if(weapon2Selected){
GUI.color = Color.green;
}else if((currentPlayer.weaponsAvailable[1].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[1].fired == false){
GUI.color = Color.white;
}else{
GUI.color = Color.grey;
}
if(GUI.Button (new Rect(buttonWidth + 30, 160, buttonWidth + 50, buttonHeight), currentPlayer.weaponsAvailable[1].weaponName)){
if(weapon2Selected){
weapon2Selected = false;
currentPlayer.weaponsSelected.Remove(currentPlayer.weaponsAvailable[1]);
if(weapon1Selected == false && weapon2Selected == false && weapon3Selected == false && weapon4Selected == false){
currentPlayer.selectedWeaponsType = -1;
weaponsReady = false;
}
}else if((currentPlayer.weaponsAvailable[1].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[1].fired == false){
weapon2Selected = true;
weaponsReady = true;
currentPlayer.weaponsSelected.Add (currentPlayer.weaponsAvailable[1]);
currentPlayer.selectedWeaponsType = currentPlayer.weaponsAvailable[1].type;
}
}
}
if(currentPlayer.weaponsAvailable.Count >= 3){
if(weapon3Selected){
GUI.color = Color.green;
}else if((currentPlayer.weaponsAvailable[2].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[2].fired == false){
GUI.color = Color.white;
}else{
GUI.color = Color.grey;
}
if(GUI.Button (new Rect(buttonWidth + 30, 190, buttonWidth + 50, buttonHeight), currentPlayer.weaponsAvailable[2].weaponName)){
if(weapon3Selected){
weapon3Selected = false;
currentPlayer.weaponsSelected.Remove(currentPlayer.weaponsAvailable[2]);
if(weapon1Selected == false && weapon2Selected == false && weapon3Selected == false && weapon4Selected == false){
currentPlayer.selectedWeaponsType = -1;
weaponsReady = false;
}
}else if((currentPlayer.weaponsAvailable[2].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[2].fired == false){
weapon3Selected = true;
weaponsReady = true;
currentPlayer.weaponsSelected.Add (currentPlayer.weaponsAvailable[2]);
currentPlayer.selectedWeaponsType = currentPlayer.weaponsAvailable[2].type;
}
}
}
if(currentPlayer.weaponsAvailable.Count >= 4){
if(weapon4Selected){
GUI.color = Color.green;
}else if((currentPlayer.weaponsAvailable[3].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[3].fired == false){
GUI.color = Color.white;
}else{
GUI.color = Color.grey;
}
if(GUI.Button (new Rect(buttonWidth + 30, 220, buttonWidth + 50, buttonHeight), currentPlayer.weaponsAvailable[3].weaponName)){
if(weapon4Selected){
weapon4Selected = false;
currentPlayer.weaponsSelected.Remove(currentPlayer.weaponsAvailable[3]);
if(weapon1Selected == false && weapon2Selected == false && weapon3Selected == false && weapon4Selected == false){
currentPlayer.selectedWeaponsType = -1;
weaponsReady = false;
}
}else if((currentPlayer.weaponsAvailable[3].type == currentPlayer.selectedWeaponsType || currentPlayer.selectedWeaponsType == -1) && currentPlayer.weaponsAvailable[3].fired == false){
weapon2Selected = true;
weaponsReady = true;
currentPlayer.weaponsSelected.Add (currentPlayer.weaponsAvailable[3]);
currentPlayer.selectedWeaponsType = currentPlayer.weaponsAvailable[3].type;
}
}
}
}
#endregion
#endregion
}
#region Pause menu buttons
if(BattleManager.instance.GetComponent<PauseMenu>().paused ){
int pButtonWidth = 200;
int pButtonHeight = 50;
int pGroupWidth = 200;
int pGroupHeight = 170;
GUI.BeginGroup(new Rect(((Screen.width/2) - (pGroupWidth/2)),((Screen.height/2)),pGroupWidth, pGroupHeight));
if(GUI.Button(new Rect(0,0,pButtonWidth,pButtonHeight),"Main Menu")){
Application.LoadLevel(0);
}
if(GUI.Button(new Rect(0,60,pButtonWidth,pButtonHeight),"Restart Level")){
Application.LoadLevel(Application.loadedLevelName);
}
if(GUI.Button(new Rect(0,120,pButtonWidth,pButtonHeight),"Save Game")){
GameData.instance.Save("save");
}
if(GUI.Button(new Rect(0,180,pButtonWidth,pButtonHeight),"Quit Game")){
Application.Quit();
}
GUI.EndGroup();
}
#endregion
}
}
| |
//
// System.Web.UI.WebControls.TreeNodeBinding.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
#if NET_2_0
using System;
using System.Collections;
using System.Web.UI;
using System.ComponentModel;
namespace System.Web.UI.WebControls
{
[DefaultProperty ("TextField")]
public sealed class TreeNodeBinding: IStateManager, ICloneable, IDataSourceViewSchemaAccessor
{
StateBag ViewState = new StateBag ();
[DefaultValue ("")]
public string DataMember {
get {
object o = ViewState ["DataMember"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["DataMember"] = value;
}
}
[DefaultValue (-1)]
public int Depth {
get {
object o = ViewState ["Depth"];
if (o != null) return (int) o;
return -1;
}
set {
ViewState ["Depth"] = value;
}
}
[Localizable (true)]
[DefaultValue ("")]
[UrlProperty]
public string FormatString {
get {
object o = ViewState ["FormatString"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["FormatString"] = value;
}
}
[Localizable (true)]
[DefaultValue ("")]
public string ImageToolTip {
get {
object o = ViewState ["ImageToolTip"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["ImageToolTip"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string ImageToolTipField {
get {
object o = ViewState ["ImageToolTipField"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["ImageToolTipField"] = value;
}
}
[DefaultValue ("")]
[UrlProperty]
[Editor ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
public string ImageUrl {
get {
object o = ViewState ["ImageUrl"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["ImageUrl"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string ImageUrlField {
get {
object o = ViewState ["ImageUrlField"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["ImageUrlField"] = value;
}
}
[DefaultValue ("")]
[UrlProperty]
[Editor ("System.Web.UI.Design.UrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
public string NavigateUrl {
get {
object o = ViewState ["NavigateUrl"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["NavigateUrl"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string NavigateUrlField {
get {
object o = ViewState ["NavigateUrlField"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["NavigateUrlField"] = value;
}
}
[DefaultValue (false)]
public bool PopulateOnDemand {
get {
object o = ViewState ["PopulateOnDemand"];
if (o != null) return (bool) o;
return false;
}
set {
ViewState ["PopulateOnDemand"] = value;
}
}
[DefaultValue (TreeNodeSelectAction.Select)]
public TreeNodeSelectAction SelectAction {
get {
object o = ViewState ["SelectAction"];
if (o != null) return (TreeNodeSelectAction)o;
return TreeNodeSelectAction.Select;
}
set {
ViewState ["SelectAction"] = value;
}
}
[DefaultValue (false)]
public bool ShowCheckBox {
get {
object o = ViewState ["ShowCheckBox"];
if (o != null) return (bool)o;
return false;
}
set {
ViewState ["ShowCheckBox"] = value;
}
}
[DefaultValue ("")]
public string Target {
get {
object o = ViewState ["Target"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["Target"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string TargetField {
get {
object o = ViewState ["TargetField"];
if (o != null) return (string) o;
return "";
}
set {
ViewState ["TargetField"] = value;
}
}
[Localizable (true)]
[DefaultValue ("")]
[WebSysDescription ("The display text of the tree node.")]
public string Text {
get {
object o = ViewState ["Text"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["Text"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string TextField {
get {
object o = ViewState ["TextField"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["TextField"] = value;
}
}
[DefaultValue ("")]
[Localizable (true)]
public string ToolTip {
get {
object o = ViewState ["ToolTip"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["ToolTip"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string ToolTipField {
get {
object o = ViewState ["ToolTipField"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["ToolTipField"] = value;
}
}
[DefaultValue ("")]
[Localizable (true)]
public string Value {
get {
object o = ViewState ["Value"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["Value"] = value;
}
}
[DefaultValue ("")]
[TypeConverter ("System.Web.UI.Design.DataSourceViewSchemaConverter, " + Consts.AssemblySystem_Design)]
public string ValueField {
get {
object o = ViewState ["ValueField"];
if(o != null) return (string)o;
return "";
}
set {
ViewState ["ValueField"] = value;
}
}
void IStateManager.LoadViewState (object savedState)
{
ViewState.LoadViewState (savedState);
}
object IStateManager.SaveViewState ()
{
return ViewState.SaveViewState();
}
void IStateManager.TrackViewState ()
{
ViewState.TrackViewState ();
}
bool IStateManager.IsTrackingViewState {
get { return ViewState.IsTrackingViewState; }
}
[MonoTODO]
object IDataSourceViewSchemaAccessor.DataSourceViewSchema {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
object ICloneable.Clone ()
{
TreeNodeBinding bin = new TreeNodeBinding ();
foreach (DictionaryEntry e in ViewState)
bin.ViewState [(string)e.Key] = e.Value;
return bin;
}
internal void SetDirty ()
{
foreach (string key in ViewState.Keys)
ViewState.SetItemDirty (key, true);
}
}
}
#endif
| |
//
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// 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.Drawing;
using System.ComponentModel;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;
namespace MonoMac.OpenGL
{
public class MonoMacGameView : MonoMac.AppKit.NSView, IGameWindow
{
bool disposed;
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
CVDisplayLink displayLink;
NSObject notificationProxy;
NSTimer animationTimer;
bool animating;
bool displayLinkSupported = false;
WindowState windowState = WindowState.Normal;
DateTime prevUpdateTime;
DateTime prevRenderTime;
FrameEventArgs updateEventArgs = new FrameEventArgs ();
FrameEventArgs renderEventArgs = new FrameEventArgs ();
[Export("initWithFrame:")]
public MonoMacGameView (RectangleF frame) : this(frame, null)
{
}
public MonoMacGameView (RectangleF frame, NSOpenGLContext context) : base(frame)
{
var attribs = new object [] {
NSOpenGLPixelFormatAttribute.Accelerated,
NSOpenGLPixelFormatAttribute.NoRecovery,
NSOpenGLPixelFormatAttribute.DoubleBuffer,
NSOpenGLPixelFormatAttribute.ColorSize, 24,
NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// default the swap interval and displaylink
SwapInterval = true;
DisplaylinkSupported = true;
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape);
}
[Preserve (Conditional=true)]
public override void DrawRect (RectangleF dirtyRect)
{
if (animating) {
if (displayLinkSupported) {
// Render Scene only if the display link is running
if (displayLink.IsRunning)
RenderScene ();
} else {
RenderScene ();
}
}
}
[Preserve (Conditional=true)]
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
NSViewController GetViewController ()
{
NSResponder r = this;
while (r != null) {
var c = r as NSViewController;
if (c != null)
return c;
r = r.NextResponder;
}
return null;
}
protected void UpdateView ()
{
Size = new Size ((int)Bounds.Width, (int)Bounds.Height);
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
private void StartAnimation (double updatesPerSecond)
{
if (!animating) {
if (displayLinkSupported) {
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
} else {
// Can't use TimeSpan.FromSeconds() as that only has 1ms
// resolution, and we need better (e.g. 60fps doesn't fit nicely
// in 1ms resolution, but does in ticks).
var timeout = new TimeSpan ((long)(((1.0 * TimeSpan.TicksPerSecond) / updatesPerSecond) + 0.5));
if (SwapInterval) {
animationTimer = NSTimer.CreateRepeatingScheduledTimer (timeout,
delegate {
NeedsDisplay = true;
});
} else {
animationTimer = NSTimer.CreateRepeatingScheduledTimer (timeout,
delegate {
RenderScene ();
});
}
NSRunLoop.Current.AddTimer (animationTimer, NSRunLoopMode.Default);
NSRunLoop.Current.AddTimer (animationTimer, NSRunLoopMode.EventTracking);
}
}
animating = true;
}
public void Stop ()
{
if (animating) {
if (displayLinkSupported) {
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
} else {
animationTimer.Invalidate ();
animationTimer = null;
}
}
animating = false;
}
// Clean up the notifications
private void DeAllocate ()
{
Stop ();
displayLink = null;
NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy);
}
void AssertValid ()
{
if (disposed)
throw new ObjectDisposedException ("");
}
void AssertContext ()
{
if (OpenGLContext == null)
throw new InvalidOperationException ("Operation requires an OpenGLContext, which hasn't been created yet.");
}
public virtual string Title {
get {
AssertValid ();
if (Window != null)
return Window.Title;
else
throw new NotSupportedException();
}
set {
AssertValid ();
if (Window != null)
Window.Title = value;
else
throw new NotSupportedException();
}
}
protected virtual void OnTitleChanged (EventArgs e)
{
var h = TitleChanged;
if (h != null)
h (this, EventArgs.Empty);
}
bool INativeWindow.Focused {
get { throw new NotImplementedException ();}
}
public virtual bool Visible {
get {
AssertValid ();
return !base.Hidden;
}
set {
AssertValid ();
if (base.Hidden != !value) {
base.Hidden = !value;
OnVisibleChanged (EventArgs.Empty);
}
}
}
protected virtual void OnVisibleChanged (EventArgs e)
{
var h = VisibleChanged;
if (h != null)
h (this, EventArgs.Empty);
}
bool INativeWindow.Exists {
get { throw new NotImplementedException ();}
}
public virtual WindowState WindowState {
get {
AssertValid ();
return windowState;
}
set {
AssertValid ();
if (windowState != value) {
windowState = value;
OnWindowStateChanged (EventArgs.Empty);
}
}
}
protected virtual void OnWindowStateChanged (EventArgs e)
{
var h = WindowStateChanged;
if (h != null)
h (this, EventArgs.Empty);
}
public virtual WindowBorder WindowBorder {
get {
AssertValid ();
return WindowBorder.Hidden;
}
set {}
}
Rectangle INativeWindow.Bounds {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
Point INativeWindow.Location {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
Icon INativeWindow.Icon {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
Size size;
public Size Size {
get {
AssertValid ();
return size;
}
set {
AssertValid ();
if (size != value) {
size = value;
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
OnResize (EventArgs.Empty);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
}
}
protected virtual void OnResize (EventArgs e)
{
var h = Resize;
if (h != null)
h (this, e);
}
int INativeWindow.X {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
int INativeWindow.Y {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
int INativeWindow.Width {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
int INativeWindow.Height {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
Rectangle INativeWindow.ClientRectangle {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
Size INativeWindow.ClientSize {
get { throw new NotSupportedException ();}
set { throw new NotSupportedException ();}
}
public virtual void Close ()
{
AssertValid ();
OnClosed (EventArgs.Empty);
}
protected virtual void OnClosed (EventArgs e)
{
var h = Closed;
if (h != null)
h (this, e);
}
protected override void Dispose (bool disposing)
{
if (disposed)
return;
if (disposing) {
DeAllocate ();
//DestroyFrameBuffer ();
}
base.Dispose (disposing);
disposed = true;
if (disposing)
OnDisposed (EventArgs.Empty);
}
protected virtual void OnDisposed (EventArgs e)
{
var h = Disposed;
if (h != null)
h (this, e);
}
void INativeWindow.ProcessEvents ()
{
throw new NotSupportedException ();
}
Point INativeWindow.PointToClient (Point point)
{
return point;
}
Point INativeWindow.PointToScreen (Point point)
{
return point;
}
public virtual void MakeCurrent ()
{
AssertValid ();
AssertContext ();
OpenGLContext.MakeCurrentContext ();
}
public virtual void SwapBuffers ()
{
AssertValid ();
AssertContext ();
// basically SwapBuffers is the same as FlushBuffer on OSX
OpenGLContext.FlushBuffer ();
}
private bool SwapInterval { get; set; }
private bool DisplaylinkSupported {
get { return displayLinkSupported; }
set {
displayLinkSupported = value;
}
}
public void Run ()
{
AssertValid ();
OnLoad (EventArgs.Empty);
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = SwapInterval;
if (displayLinkSupported)
SetupDisplayLink ();
StartAnimation (0.0);
}
public void Run (double updatesPerSecond)
{
AssertValid ();
if (updatesPerSecond == 0.0) {
Run ();
return;
}
OnLoad (EventArgs.Empty);
// Here we set these to false for now and let the main logic continue
// in the future we may open up these properties to the public
SwapInterval = false;
DisplaylinkSupported = false;
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = SwapInterval;
if (displayLinkSupported)
SetupDisplayLink ();
StartAnimation (updatesPerSecond);
}
private void RenderScene ()
{
// This method will be called on both the main thread (through DrawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, Reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
var curUpdateTime = DateTime.Now;
if (prevUpdateTime.Ticks == 0) {
prevUpdateTime = curUpdateTime;
}
var t = (curUpdateTime - prevUpdateTime).TotalSeconds;
// This fixes a potential error
if (t <= 0) t = Double.Epsilon;
updateEventArgs.Time = t;
OnUpdateFrame (updateEventArgs);
prevUpdateTime = curUpdateTime;
var curRenderTime = DateTime.Now;
if (prevRenderTime.Ticks == 0) {
prevRenderTime = curRenderTime;
}
t = (curRenderTime - prevRenderTime).TotalSeconds;
// This fixes a potential error
if (t <= 0) t = Double.Epsilon;
renderEventArgs.Time = t;
OnRenderFrame (renderEventArgs);
prevRenderTime = curRenderTime;
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
}
private void SetupDisplayLink ()
{
if (displayLink != null)
return;
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
// Private Callback function for CVDisplayLink
private CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
//CVReturn result = GetFrameForTime (inOutputTime);
CVReturn result = CVReturn.Error;
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
BeginInvokeOnMainThread (RenderScene);
result = CVReturn.Success;
}
return result;
}
protected virtual void OnLoad (EventArgs e)
{
var h = Load;
if (h != null)
h (this, e);
}
protected virtual void OnUnload (EventArgs e)
{
var h = Unload;
Stop ();
if (h != null)
h (this, e);
}
protected virtual void OnUpdateFrame (FrameEventArgs e)
{
var h = UpdateFrame;
if (h != null)
h (this, e);
}
protected virtual void OnRenderFrame (FrameEventArgs e)
{
var h = RenderFrame;
if (h != null)
h (this, e);
}
event EventHandler<EventArgs> INativeWindow.Move {
add { throw new NotSupportedException ();}
remove { throw new NotSupportedException ();}
}
public event EventHandler<EventArgs> Resize;
event EventHandler<CancelEventArgs> INativeWindow.Closing {
add { throw new NotSupportedException ();}
remove { throw new NotSupportedException ();}
}
public event EventHandler<EventArgs> Closed;
public event EventHandler<EventArgs> Disposed;
public event EventHandler<EventArgs> TitleChanged;
public event EventHandler<EventArgs> VisibleChanged;
event EventHandler<EventArgs> INativeWindow.FocusedChanged {
add { throw new NotSupportedException ();}
remove { throw new NotSupportedException ();}
}
event EventHandler<EventArgs> INativeWindow.WindowBorderChanged {
add { throw new NotSupportedException ();}
remove { throw new NotSupportedException ();}
}
public event EventHandler<EventArgs> WindowStateChanged;
// event EventHandler<KeyPressEventArgs> INativeWindow.KeyPress {
// add { throw new NotSupportedException ();}
// remove { throw new NotSupportedException ();}
// }
event EventHandler<EventArgs> INativeWindow.IconChanged {
add { throw new NotSupportedException ();}
remove { throw new NotSupportedException ();}
}
public event EventHandler<EventArgs> Load;
public event EventHandler<EventArgs> Unload;
public event EventHandler<FrameEventArgs> UpdateFrame;
public event EventHandler<FrameEventArgs> RenderFrame;
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Xml;
namespace Axiom.SceneManagers.Multiverse
{
public delegate void AngleMovedHandler( object sender, Guid pairId, float oldAngle, float newAngle );
public delegate void TextureIndexChangedHandler( object sender, Guid pairId, int oldIndex, int newIndex );
public delegate void AngleTexturePairHandler( object sender, Guid pairId, float angle, int textureIndex );
public class AutoSplatHeightAngleRange : IComparable<AutoSplatHeightAngleRange>
{
#region Public interface
#region Generated events
public event AngleTexturePairHandler AngleTexturePairAdded;
public event AngleTexturePairHandler AngleTexturePairRemoved;
public event AngleMovedHandler AngleMoved;
public event TextureIndexChangedHandler TextureIndexChanged;
#endregion Generated events
public long HeightMM
{
get { return m_heightMM; }
set { m_heightMM = value; }
}
long m_heightMM;
public Guid Id { get; private set; }
/// <summary>
/// Pairs (and therfore Ids) for Horizontal and Vertical are guaranteed to always exist.
/// </summary>
public Guid HorizontalId { get { return m_AngleSortedPairs[ 0 ].Id; } }
public Guid VerticalId { get { return m_AngleSortedPairs[ m_AngleSortedPairs.Count - 1 ].Id; } }
public IEnumerable<Guid> AllIdsInAscendingAngleOrder
{
get
{
for( int i = 0; i < m_AngleSortedPairs.Count; i++ )
{
yield return m_AngleSortedPairs[ i ].Id;
}
}
}
#region Constructors
public AutoSplatHeightAngleRange( long heightMM )
{
Id = Guid.NewGuid();
m_heightMM = heightMM;
}
public AutoSplatHeightAngleRange( long heightMM, int horizontalTextureIndex, int verticalTextureIndex ) :
this(heightMM)
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( AutoSplatAngleTexturePair.Horizontal, horizontalTextureIndex ) );
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( AutoSplatAngleTexturePair.Vertical, verticalTextureIndex ) );
}
public AutoSplatHeightAngleRange( long heightMM, AutoSplatHeightAngleRange other ) :
this(heightMM)
{
foreach( AutoSplatAngleTexturePair otherPair in other.m_AngleSortedPairs )
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( otherPair ) );
}
}
public AutoSplatHeightAngleRange( XmlReader reader )
{
Id = Guid.NewGuid();
FromXml( reader );
}
#endregion Constructors
#region Xml Serialization
public void FromXml( XmlReader reader )
{
Debug.Assert( reader.Name.Equals( "heightRange" ) );
XmlReader subReader = reader.ReadSubtree();
subReader.ReadToFollowing( "long" );
Debug.Assert( subReader.GetAttribute( "name" ).Equals( "height" ) );
m_heightMM = long.Parse( subReader.GetAttribute( "value" ) );
subReader.ReadToFollowing( "slopes" );
subReader.ReadToFollowing( "slope" );
do
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( subReader ) );
} while( subReader.ReadToNextSibling( "slope" ) );
subReader.Close();
}
public void ToXml( XmlWriter writer )
{
writer.WriteStartElement( "heightRange" );
writer.WriteStartElement( "long" );
writer.WriteAttributeString( "name", "height" );
writer.WriteAttributeString( "value", m_heightMM.ToString() );
writer.WriteEndElement();
writer.WriteStartElement( "slopes" );
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
pair.ToXml( writer );
}
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion Xml Serialization
/// <summary>
/// This is like an 'add' operation, but you need to restore the id of the
/// pair literally because further operations in the undo stack will refer
/// to the pair by id.
/// </summary>
/// <param name="angleDegrees">angle of the slope</param>
/// <param name="textureIndex">texture associated with the slope</param>
/// <param name="id">unique id by which the slope is accessed</param>
/// <returns></returns>
public AutoSplatAngleTexturePair UndoRemoveAngleTexturePair( float angleDegrees, int textureIndex, Guid id )
{
AutoSplatAngleTexturePair pair = new AutoSplatAngleTexturePair( angleDegrees, textureIndex, id );
InternalAddAngleTexturePair( pair );
return pair;
}
public AutoSplatAngleTexturePair AddAngleTexturePair( float angleDegrees, int textureIndex )
{
AutoSplatAngleTexturePair pair = new AutoSplatAngleTexturePair( angleDegrees, textureIndex );
InternalAddAngleTexturePair( pair );
return pair;
}
public void RemoveAngleTexturePair( Guid pairId )
{
InternalRemoveAngleTexturePair( GetPair( pairId ) );
}
public float GetAngleDegrees( Guid pairId )
{
Debug.Assert( m_IdToPairMap.ContainsKey( pairId ) );
return m_IdToPairMap[ pairId ].AngleDegrees;
}
public int GetTextureIndex( Guid pairId )
{
Debug.Assert( m_IdToPairMap.ContainsKey( pairId ) );
return m_IdToPairMap[ pairId ].TextureIndex;
}
public void MoveAngle( Guid pairId, float angleDegrees )
{
AutoSplatAngleTexturePair pair = GetPair( pairId );
if( ! pair.AngleDegrees.Equals( angleDegrees ) )
{
AutoSplatAngleTexturePair clone = null;
if( pair.IsCriticalAngle )
{
clone = new AutoSplatAngleTexturePair( pair );
// We won't need to 'infinitesimally bump' the new angle because
// we already tested to establish that the values are not equal.
}
else
{
// Guarenteed to be neither first nor last because it's not critical
int pairIndex = GetIndex( pairId );
float prevAngle = m_AngleSortedPairs[ pairIndex - 1 ].AngleDegrees;
float nextAngle = m_AngleSortedPairs[ pairIndex + 1 ].AngleDegrees;
if( angleDegrees < prevAngle || angleDegrees > nextAngle )
{
// Only Add and Remove should change the sorting order
throw new ConstraintException(
"MoveAngle would change ordering of pairs;" +
"only Add and Remove should change the sorting order." );
}
// If the move would make the angle coincide exactly with one of
// its neighbors, back it off a teensie-weensie bit.
const float infinitesimal = 0.0001f;
if( angleDegrees.Equals( prevAngle ) )
{
angleDegrees += infinitesimal;
}
else if( angleDegrees.Equals( nextAngle ) )
{
angleDegrees -= infinitesimal;
}
}
float oldAngle = pair.AngleDegrees;
pair.AngleDegrees = angleDegrees;
FireAngleMoved( pairId, oldAngle, angleDegrees );
if( null != clone )
{
// So we are splitting one of the critical pairs. By waiting until
// after we've moved the original pair to add the clone, we assure
// the sorting order stays the same for pre-existing pairs. The
// Outside World cares about this order.
InternalAddAngleTexturePair( clone );
}
}
}
public void SetPairTextureIndex( Guid pairId, int textureIndex )
{
int oldIndex = GetPair( pairId ).TextureIndex;
if( ! textureIndex.Equals( oldIndex ) )
{
GetPair( pairId ).TextureIndex = textureIndex;
FireTextureIndexChanged( pairId, oldIndex, textureIndex );
}
}
public float[] GetAutoSplatSampleNormalized( float angleDegrees )
{
AutoSplatAngleTexturePair lowerPair = null;
AutoSplatAngleTexturePair higherPair = null;
// We assume the pairs are sorted in increasing order by angle
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
if( pair.AngleDegrees == angleDegrees )
{
lowerPair = pair;
higherPair = pair;
break;
}
if( pair.AngleDegrees < angleDegrees )
{
lowerPair = pair;
continue;
}
if( pair.AngleDegrees > angleDegrees )
{
higherPair = pair;
// We should have both the lower & upper bounds now, so break;
break;
}
}
if (lowerPair == null)
{
Debug.Assert(lowerPair != null,
"Unable to find lower angle when getting autosplat sample. Angle=" + angleDegrees + " Range=" +
this);
}
if (higherPair == null)
{
Debug.Assert(higherPair != null,
"Unable to find higher angle when getting autosplat sample. Angle=" + angleDegrees +
" Range=" + this);
}
// Compute the gradiant weighting for the lower & higher angled textures
float lowerWeight;
float higherWeight;
float angleDiff = higherPair.AngleDegrees - lowerPair.AngleDegrees;
if( angleDiff == 0 || lowerPair.TextureIndex == higherPair.TextureIndex)
{
lowerWeight = 0f;
higherWeight = 1f;
}
else
{
// How close is the angle to the higher/lower angle? Normalize
// that distance from 0..1 and use that as the gradient weights
higherWeight = (angleDegrees - lowerPair.AngleDegrees) / angleDiff;
lowerWeight = 1f - higherWeight;
}
float[] normalizedSample = new float[AlphaSplatTerrainConfig.MAX_LAYER_TEXTURES];
// It's important that we set higher second because
// if lower & higher angle are equal the same, we
// set the higherWeight to 1f above and want to make
// sure it's set that way here.
normalizedSample[ lowerPair.TextureIndex ] = lowerWeight;
normalizedSample[ higherPair.TextureIndex ] = higherWeight;
return normalizedSample;
}
public IEnumerable<AutoSplatAngleTexturePair> GetAngleTexturePairs()
{
return m_AngleSortedPairs;
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append( m_heightMM );
builder.Append( "mm [" );
bool first = true;
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
if( first )
{
first = false;
}
else
{
builder.Append( ", " );
}
builder.Append( pair );
}
builder.Append( "]" );
return builder.ToString();
}
#region Implementation of IComparable<AutoSplatHeightAngleRange>
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This object is equal to <paramref name="other" />. Greater than zero This object is greater than <paramref name="other" />.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo( AutoSplatHeightAngleRange other )
{
long diff = m_heightMM - other.m_heightMM;
return (int) diff;
}
#endregion
#endregion Public interface
#region Private implementation
readonly List<AutoSplatAngleTexturePair> m_AngleSortedPairs = new List<AutoSplatAngleTexturePair>();
readonly Dictionary<Guid,AutoSplatAngleTexturePair> m_IdToPairMap = new Dictionary<Guid, AutoSplatAngleTexturePair>();
void InternalAddAngleTexturePair( AutoSplatAngleTexturePair pair )
{
if( pair == null )
{
throw new NullReferenceException();
}
if( m_IdToPairMap.ContainsKey( pair.Id ) )
{
throw new ArgumentException( "Key already in dictionary" );
}
// Make sure the pair *angle* to be added is not a duplicated.
foreach( AutoSplatAngleTexturePair atPair in m_AngleSortedPairs )
{
if( atPair.AngleDegrees.Equals( pair.AngleDegrees ) )
{
throw new ArgumentException( "Duplicate angles are not allowed." );
}
}
m_AngleSortedPairs.Add( pair );
m_AngleSortedPairs.Sort(); // Keep sorted by angle
m_IdToPairMap.Add( pair.Id, pair );
FireAngleTexturePairAdded( pair );
}
void InternalRemoveAngleTexturePair( AutoSplatAngleTexturePair pair )
{
// You are not allowed to remove critical pairs! We have a design
// constraint that there are always a horizontal and a vertical pair.
//
// This is not as constraining as it might sound. Assume the 'remove'
// request is the outcome of a GUI action--like dragging to the trash.
// Even if you attempt to remove a critical pair, the act of moving it
// to the trash hotspot will move it away from the critical position,
// which in turn causes a new pair to be inserted to replace it in the
// critical position. You could do it all day if that's how you like
// to spend your time.
if( ! pair.IsCriticalAngle )
{
m_IdToPairMap.Remove( pair.Id );
m_AngleSortedPairs.Remove( pair );
FireAngleTexturePairRemoved( pair );
}
}
AutoSplatAngleTexturePair GetPair( Guid pairId )
{
if( m_IdToPairMap.ContainsKey( pairId ) )
{
return m_IdToPairMap[ pairId ];
}
throw new ArgumentException( "Attempting to get an unregistered AngleTexturePair" );
}
int GetIndex( Guid pairId )
{
int index = m_AngleSortedPairs.IndexOf( GetPair( pairId ) );
if( index >= 0 )
{
return index;
}
throw new IndexOutOfRangeException();
}
#region Event firing
void FireAngleMoved( Guid pairId, float oldAngle, float newAngle )
{
if( null != AngleMoved )
{
AngleMoved( this, pairId, oldAngle, newAngle );
}
}
void FireTextureIndexChanged( Guid pairId, int oldIndex, int newIndex )
{
if( null != TextureIndexChanged )
{
TextureIndexChanged( this, pairId, oldIndex, newIndex );
}
}
void FireAngleTexturePairAdded( AutoSplatAngleTexturePair pair )
{
if( null != AngleTexturePairAdded )
{
AngleTexturePairAdded( this, pair.Id, pair.AngleDegrees, pair.TextureIndex );
}
}
void FireAngleTexturePairRemoved( AutoSplatAngleTexturePair pair )
{
if( null != AngleTexturePairRemoved )
{
AngleTexturePairRemoved( this, pair.Id, pair.AngleDegrees, pair.TextureIndex );
}
}
#endregion Event firing
#endregion Private implementation
}
}
| |
namespace SimpleECS
{
using Internal;
public partial struct World
{
public Entity CreateEntity<C1>(C1 c1)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1);
}
return default;
}
public Entity CreateEntity<C1, C2>(C1 c1, C2 c2)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2);
}
return default;
}
public Entity CreateEntity<C1, C2, C3>(C1 c1, C2 c2, C3 c3)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4>(C1 c1, C2 c2, C3 c3, C4 c4)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27, C28 c28)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>().Add<C28>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27).Set(c28);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27, C28 c28, C29 c29)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>().Add<C28>().Add<C29>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27).Set(c28).Set(c29);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27, C28 c28, C29 c29, C30 c30)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>().Add<C28>().Add<C29>().Add<C30>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27).Set(c28).Set(c29).Set(c30);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27, C28 c28, C29 c29, C30 c30, C31 c31)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>().Add<C28>().Add<C29>().Add<C30>().Add<C31>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27).Set(c28).Set(c29).Set(c30).Set(c31);
}
return default;
}
public Entity CreateEntity<C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31, C32>(C1 c1, C2 c2, C3 c3, C4 c4, C5 c5, C6 c6, C7 c7, C8 c8, C9 c9, C10 c10, C11 c11, C12 c12, C13 c13, C14 c14, C15 c15, C16 c16, C17 c17, C18 c18, C19 c19, C20 c20, C21 c21, C22 c22, C23 c23, C24 c24, C25 c25, C26 c26, C27 c27, C28 c28, C29 c29, C30 c30, C31 c31, C32 c32)
{
if (this.TryGetWorldInfo(out var data))
{
data.buffer_signature.Clear().Add<C1>().Add<C2>().Add<C3>().Add<C4>().Add<C5>().Add<C6>().Add<C7>().Add<C8>().Add<C9>().Add<C10>().Add<C11>().Add<C12>().Add<C13>().Add<C14>().Add<C15>().Add<C16>().Add<C17>().Add<C18>().Add<C19>().Add<C20>().Add<C21>().Add<C22>().Add<C23>().Add<C24>().Add<C25>().Add<C26>().Add<C27>().Add<C28>().Add<C29>().Add<C30>().Add<C31>().Add<C32>();
var archetype = data.GetArchetypeData(data.buffer_signature);
return data.StructureEvents.CreateEntity(archetype)
.Set(c1).Set(c2).Set(c3).Set(c4).Set(c5).Set(c6).Set(c7).Set(c8).Set(c9).Set(c10).Set(c11).Set(c12).Set(c13).Set(c14).Set(c15).Set(c16).Set(c17).Set(c18).Set(c19).Set(c20).Set(c21).Set(c22).Set(c23).Set(c24).Set(c25).Set(c26).Set(c27).Set(c28).Set(c29).Set(c30).Set(c31).Set(c32);
}
return default;
}
}
}
| |
/*
* Copyright (c) 2012 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using org.critterai.nav;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace org.critterai.nmbuild.u3d.editor
{
internal sealed class NavmeshBuildHelper
{
private readonly NavmeshBuild mBuild;
private readonly UnityBuildContext mContext = new UnityBuildContext();
public NavmeshBuildHelper(NavmeshBuild build)
{
if (!build)
throw new System.ArgumentNullException();
this.mBuild = build;
}
public void Build()
{
if (!mBuild)
return;
mBuild.ResetBuild();
// Note: The 'finally' takes care of all cleanup.
try
{
EditorUtility.DisplayCancelableProgressBar("Build & Bake"
, "Preparing..."
, 0);
// Prepare the build.
if (!CompileInput())
return;
if (!InitializeBuild())
return;
// Build the tiles.
NavmeshParams nconfig = null;
NavmeshTileData[] tiles = null;
bool success = true;
if (mBuild.TileSetDefinition == null)
{
if (!BuildSingleTile())
return;
tiles = new NavmeshTileData[1] { mBuild.BuildData.GetTileData(0, 0) };
nconfig = NavUtil.DeriveConfig(tiles[0]);
}
else if (BuildMultiTiled())
{
success = mBuild.BuildData.GetMeshBuildData(mBuild.TileSetDefinition.BoundsMin
, mBuild.TileSetDefinition.TileWorldSize
, out nconfig, out tiles);
}
else
return;
if (!success)
{
mContext.PostError("Navigation mesh creation failed.", mBuild);
return;
}
// Bake the mesh.
NavStatus nstatus =
mBuild.BuildTarget.Load(nconfig, tiles, NMBEditorUtil.GetConfig(mBuild));
if ((nstatus & NavStatus.Sucess) == 0)
mContext.PostError("Bake to target: Target reported failure.", mBuild);
else
EditorUtility.SetDirty((Object)mBuild.BuildTarget);
}
finally
{
mBuild.ResetBuild();
EditorUtility.ClearProgressBar();
}
}
private bool InitializeBuild()
{
mContext.ResetLog();
if (!mBuild.InitializeBuild(mContext, false))
{
mContext.PostError("Build initialization failed.", mBuild);
return false;
}
// Not helpful.
//else
// mContext.PostTrace("Initialized build.", mBuild);
mContext.ResetLog();
return true;
}
private bool BuildSingleTile()
{
TileBuildData tdata = mBuild.BuildData;
NMGenConfig config = mBuild.Config;
InputGeometry geom = mBuild.InputGeom;
mContext.ResetLog();
/*
* Design note:
*
* Not using the build task since it doesn't provide enough progress
* feedback for a single tile.
*
*/
// Create the NMGen builder.
IncrementalBuilder builder = IncrementalBuilder.Create(config.GetConfig()
, config.ResultOptions
, geom
, mBuild.NMGenProcessors);
if (builder == null)
{
mContext.PostError("Unexpected failure creating NMGen builder.", mBuild);
tdata.SetAsFailed(0, 0);
return false;
}
else if (builder.IsFinished)
{
if (builder.State == NMGenState.NoResult)
{
mContext.PostError("NMGen build did not produce a result. (Early exit.)"
, builder.GetMessages(), mBuild);
tdata.SetAsFailed(0, 0);
return false;
}
else
{
mContext.PostError("Unexpected NMGen builder completion."
, builder.GetMessages(), mBuild);
tdata.SetAsFailed(0, 0);
return false;
}
}
mBuild.BuildData.SetAsInProgress(0, 0);
// Run the NMGen builder.
while (!builder.IsFinished)
{
if (EditorUtility.DisplayCancelableProgressBar("Build Single Tile Mesh"
, IncrementalBuilder.ToLabel(builder.State)
, IncrementalBuilder.ToProgress(builder.State)))
{
return false;
}
builder.Build();
}
// Handle NMGen failures.
mContext.Log(builder.GetMessages()); // Single tile build. So go ahead an record.
switch (builder.State)
{
case NMGenState.Aborted:
mContext.PostError("NMGen build failed.", mBuild);
tdata.SetAsFailed(0, 0);
return false;
case NMGenState.NoResult:
mContext.PostError("NMGen build did not produce a result.", mBuild);
tdata.SetAsFailed(0, 0);
return false;
}
mContext.Log(string.Format("Completed NMGen build: {0} polygons."
, builder.Result.PolyMesh.PolyCount)
, mBuild);
// Build the tile.
NMGenAssets result = builder.Result;
NavmeshTileBuildData tbd = org.critterai.nmbuild.NMBuild.GetBuildData(
mContext, 0, 0
, result.PolyMesh.GetData(false), result.DetailMesh.GetData(false)
, mBuild.Connections
, (config.BuildFlags & NMGenBuildFlag.BVTreeEnabled) != 0);
if (tbd == null)
{
// No need to log the error. The above method takes care of that.
tdata.SetAsFailed(0, 0);
return false;
}
NavmeshTileData td = NavmeshTileData.Create(tbd);
if (td.Size == 0)
{
mContext.PostError(
"Could not create {0} object. Cause unknown." + typeof(NavmeshTileData)
, mBuild);
tdata.SetAsFailed(0, 0);
return false;
}
// Finalize the tile.
tdata.SetWorkingData(0, 0, result.PolyMesh, result.DetailMesh);
tdata.SetWorkingData(0, 0, td, tbd.PolyCount);
mContext.PostTrace("Completed single tile build.", mBuild);
return true;
}
private bool BuildMultiTiled()
{
TileSetDefinition tdef = mBuild.TileSetDefinition;
TileBuildData tdata = mBuild.BuildData;
mContext.ResetLog();
int total = tdef.Width * tdef.Depth;
string msg = string.Format("Multi-tile build: {0} tiles ({1}x{2})"
, total, tdef.Width, tdef.Depth);
mContext.Log(msg, mBuild);
int count = 0; // For the progress bar.
for (int tx = 0; tx < tdef.Width; tx++)
{
for (int tz = 0; tz < tdef.Depth; tz++)
{
count++;
string tileText = string.Format("({0},{1})", tx, tz);
if (EditorUtility.DisplayCancelableProgressBar("Multi-tiled Build & Bake"
, string.Format("Tile: {0} ({1} of {2})", tileText, count, total)
, (float)count / total))
{
return false;
}
// Create the NMGen builder.
IncrementalBuilder builder = IncrementalBuilder.Create(tx, tz
, mBuild.Config.ResultOptions
, mBuild.TileSetDefinition
, mBuild.NMGenProcessors);
if (builder == null)
{
mContext.PostError(
"Unexpected failure creating NMGen builder: Tile: " + tileText
, mBuild);
tdata.SetAsFailed(tx, tz);
return false;
}
mBuild.BuildData.SetAsInProgress(tx, tz);
// Create and run the build task.
NMGenTask ntask = NMGenTask.Create(builder, 0);
ntask.Run();
if (ntask.TaskState == BuildTaskState.Aborted)
{
mContext.PostError("NMGen build task failed: Tile: " + tileText
, ntask.Messages, mBuild);
tdata.SetAsFailed(tx, tz);
return false;
}
NMGenAssets nr = ntask.Result;
if (nr.NoResult)
{
mContext.PostTrace("NMGen complete. Empty tile: " + tileText
, builder.GetMessages()
, mBuild);
tdata.SetAsEmpty(tx, tz);
continue;
}
msg = string.Format("NMGen complete. Tile {0} has {1} polygons."
, tileText, nr.PolyMesh.PolyCount);
mContext.PostTrace(msg, builder.GetMessages(), mBuild);
TileBuildTask ttask = TileBuildTask.Create(tx, tz
, nr.PolyMesh.GetData(false), nr.DetailMesh.GetData(false)
, mBuild.Connections
, (mBuild.Config.BuildFlags & NMGenBuildFlag.BVTreeEnabled) != 0
, false, 0);
ttask.Run();
if (ttask.TaskState == BuildTaskState.Aborted)
{
mContext.PostError("Tile build task failed: Tile: " + tileText
, ttask.Messages
, mBuild);
tdata.SetAsFailed(tx, tz);
return false;
}
TileBuildAssets tr = ttask.Result;
tdata.SetWorkingData(tx, tz, nr.PolyMesh, nr.DetailMesh);
tdata.SetWorkingData(tx, tz, tr.Tile, tr.PolyCount);
}
}
int bakeable = tdata.BakeableCount();
if (bakeable == 0)
{
mContext.PostError("Build did not produce any usuable tiles. (All tiles empty?)"
, mBuild);
return false;
}
msg = string.Format("Tile build complete. {0} tiles produced. {1} empty tiles."
, bakeable, tdata.GetStateCount(TileBuildState.Empty));
mContext.PostTrace(msg, mBuild);
return true;
}
private bool CompileInput()
{
mContext.ResetLog();
InputAssets assets = BuildInput(false);
if (assets.geometry == null)
{
mContext.PostError("No input geometry generated.", mBuild);
return false;
}
org.critterai.geom.TriangleMesh mesh = assets.geometry;
InputGeometryBuilder gbuilder = InputGeometryBuilder.UnsafeCreate(mesh
, assets.areas
, mBuild.Config.GetConfig().WalkableSlope
, true);
if (gbuilder == null)
{
mContext.PostError("Could not create input geometry builder. (Internal error.)"
, mBuild);
return false;
}
gbuilder.BuildAll();
if (mBuild.SetInputData(mContext, gbuilder.Result
, assets.info, assets.processors, assets.conns
, false))
{
mContext.PostTrace("Input compile complete.", mBuild);
}
return true;
}
public InputAssets BuildInput()
{
if (!mBuild)
return new InputAssets();
return BuildInput(true);
}
private InputAssets BuildInput(bool ownProgress)
{
InputBuildOption options =
(mBuild.AutoCleanGeometry ? InputBuildOption.AutoCleanGeometry : 0);
InputBuilder builder =
InputBuilder.Create(mBuild.SceneQuery, mBuild.GetInputProcessors(), options);
if (builder == null)
{
mContext.LogError("Could not create input builder.", mBuild);
return new InputAssets();
}
try
{
while (!builder.IsFinished)
{
builder.Build();
if (EditorUtility.DisplayCancelableProgressBar("Compile Input"
, InputBuilder.ToLabel(builder.State)
, InputBuilder.ToProgress(builder.State)))
{
return new InputAssets();
}
}
}
finally
{
if (ownProgress)
EditorUtility.ClearProgressBar();
}
mContext.Log(builder.Messages);
if (builder.State != InputBuildState.Complete)
{
mContext.LogError("Input builder aborted.", mBuild);
return new InputAssets();
}
InputAssets assets = builder.Result;
org.critterai.geom.TriangleMesh mesh = assets.geometry;
if (!InputGeometryBuilder.IsValid(mesh, assets.areas))
{
mContext.LogError("Input geometry failed validation. (Malformed data.)", mBuild);
return new InputAssets();
}
return builder.Result;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NPOI.SS.UserModel;
using NUnit.Framework;
using TestCases.SS.Formula.Functions;
using NPOI.OpenXml4Net.OPC;
using System.IO;
using TestCases.HSSF;
using NPOI.Util;
using NPOI.SS.Util;
namespace NPOI.XSSF.UserModel{
/**
* Performs much the same role as {@link TestFormulasFromSpreadsheet},
* except for a XSSF spreadsheet, not a HSSF one.
* This allows us to check that all our Formula Evaluation code
* is able to work for XSSF, as well as for HSSF.
*
* Periodically, you should open FormulaEvalTestData.xls in
* Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx
*
*/
[TestFixture]
public class TestFormulaEvaluatorOnXSSF
{
private class Result
{
public const int SOME_EVALUATIONS_FAILED = -1;
public const int ALL_EVALUATIONS_SUCCEEDED = +1;
public const int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/**
* Name of the Test spreadsheet (found in the standard Test data folder)
*/
public static String FILENAME = "FormulaEvalTestData_Copy.xlsx";
/**
* Row (zero-based) in the Test spreadsheet where the operator examples start.
*/
public static int START_OPERATORS_ROW_INDEX = 22; // Row '23'
/**
* Row (zero-based) in the Test spreadsheet where the function examples start.
*/
public static int START_FUNCTIONS_ROW_INDEX = 95; // Row '96'
/**
* Index of the column that Contains the function names
*/
public static int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B'
/**
* Used to indicate when there are no more functions left
*/
public static String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>";
/**
* Index of the column where the Test values start (for each function)
*/
public static short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D'
/**
* Each function takes 4 rows in the Test spreadsheet
*/
public static int NUMBER_OF_ROWS_PER_FUNCTION = 4;
}
private XSSFWorkbook workbook;
private ISheet sheet;
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionFailedError is thrown at the end
private int _functionFailureCount;
private int _functionSuccessCount;
private int _EvaluationFailureCount;
private int _EvaluationSuccessCount;
private static ICell GetExpectedValueCell(IRow row, short columnIndex)
{
if (row == null)
{
return null;
}
return row.GetCell(columnIndex);
}
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
switch (expected.CellType)
{
case CellType.Blank:
Assert.AreEqual(CellType.Blank, actual.CellType, msg);
break;
case CellType.Boolean:
Assert.AreEqual(CellType.Boolean, actual.CellType, msg);
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Error:
Assert.AreEqual(CellType.Error, actual.CellType, msg);
//if (false)
//{ // TODO: fix ~45 functions which are currently returning incorrect error values
// Assert.AreEqual(expected.ErrorCellValue, actual.ErrorValue, msg);
//}
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(CellType.Numeric, actual.CellType, msg);
AbstractNumericTestCase.AssertEqual(msg, expected.NumericCellValue, actual.NumberValue, TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR);
// double delta = Math.abs(expected.NumericCellValue-actual.NumberValue);
// double pctExpected = Math.abs(0.00001*expected.NumericCellValue);
// Assert.IsTrue(msg, delta <= pctExpected);
break;
case CellType.String:
Assert.AreEqual(CellType.String, actual.CellType, msg);
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
[SetUp]
public void SetUp()
{
if (workbook == null)
{
Stream is1 = HSSFTestDataSamples.OpenSampleFileStream(SS.FILENAME);
OPCPackage pkg = OPCPackage.Open(is1);
workbook = new XSSFWorkbook(pkg);
sheet = workbook.GetSheetAt(0);
}
_functionFailureCount = 0;
_functionSuccessCount = 0;
_EvaluationFailureCount = 0;
_EvaluationSuccessCount = 0;
}
/**
* Checks that we can actually open the file
*/
[Test]
public void TestOpen()
{
Assert.IsNotNull(workbook);
}
/**
* Disabled for now, as many things seem to break
* for XSSF, which is a shame
*/
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
NumberToTextConverter.RawDoubleBitsToText(BitConverter.DoubleToInt64Bits(1.0));
ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null);
ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null);
// example for debugging individual functions/operators:
// ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval");
// ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE");
// confirm results
String successMsg = "There were "
+ _EvaluationSuccessCount + " successful Evaluation(s) and "
+ _functionSuccessCount + " function(s) without error";
if (_functionFailureCount > 0)
{
String msg = _functionFailureCount + " function(s) failed in "
+ _EvaluationFailureCount + " Evaluation(s). " + successMsg;
throw new AssertionException(msg);
}
//if (false)
//{ // normally no output for successful Tests
// Console.WriteLine(this.GetType().Name + ": " + successMsg);
//}
}
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
* @param TestFocusFunctionName name of a single function/operator to Test alone.
* Typically pass <code>null</code> to Test all functions
*/
private void ProcessFunctionGroup(int startRowIndex, String testFocusFunctionName)
{
IFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
int rowIndex = startRowIndex;
while (true)
{
IRow r = sheet.GetRow(rowIndex);
String targetFunctionName = GetTargetFunctionName(r);
if (targetFunctionName == null)
{
throw new AssertionException("Test spreadsheet cell empty on row ("
+ (rowIndex + 1) + "). Expected function name or '"
+ SS.FUNCTION_NAMES_END_SENTINEL + "'");
}
if (targetFunctionName.Equals(SS.FUNCTION_NAMES_END_SENTINEL))
{
// found end of functions list
break;
}
if (testFocusFunctionName == null || targetFunctionName.Equals(testFocusFunctionName, StringComparison.OrdinalIgnoreCase))
{
// expected results are on the row below
IRow expectedValuesRow = sheet.GetRow(rowIndex + 1);
if (expectedValuesRow == null)
{
int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row
throw new AssertionException("Missing expected values row for function '"
+ targetFunctionName + " (row " + missingRowNum + ")");
}
switch (ProcessFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow))
{
case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break;
case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break;
case Result.NO_EVALUATIONS_FOUND: // do nothing
break;
default:
throw new RuntimeException("unexpected result");
}
}
rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION;
}
}
/**
*
* @return a constant from the local Result class denoting whether there were any Evaluation
* cases, and whether they all succeeded.
*/
private int ProcessFunctionRow(IFormulaEvaluator Evaluator, String targetFunctionName,
IRow formulasRow, IRow expectedValuesRow)
{
int result = Result.NO_EVALUATIONS_FOUND; // so far
short endcolnum = formulasRow.LastCellNum;
// iterate across the row for all the Evaluation cases
for (short colnum = SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++)
{
ICell c = formulasRow.GetCell(colnum);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
if (IsIgnoredFormulaTestCase(c.CellFormula))
{
continue;
}
CellValue actualValue;
try
{
actualValue = Evaluator.Evaluate(c);
}
catch (RuntimeException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
continue;
}
ICell expectedValueCell = GetExpectedValueCell(expectedValuesRow, colnum);
try
{
ConfirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.CellFormula + " @ " + formulasRow.RowNum + ":" + colnum,
expectedValueCell, actualValue);
_EvaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (AssertionException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
return result;
}
/*
* TODO - these are all formulas which currently (Apr-2008) break on ooxml
*/
private static bool IsIgnoredFormulaTestCase(String cellFormula)
{
if ("COLUMN(1:2)".Equals(cellFormula) || "ROW(2:3)".Equals(cellFormula))
{
// full row ranges are not Parsed properly yet.
// These cases currently work in svn tRunk because of another bug which causes the
// formula to Get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3)
return true;
}
if ("ISREF(currentcell())".Equals(cellFormula))
{
// currently throws NPE because unknown function "currentcell" causes name lookup
// Name lookup requires some equivalent object of the Workbook within xSSFWorkbook.
return true;
}
return false;
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void PrintshortStackTrace(TextWriter ps, Exception e)
{
//StackTraceElement[] stes = e.GetStackTrace();
//int startIx = 0;
//// Skip any top frames inside junit.framework.Assert
//while(startIx<stes.Length) {
// if(!stes[startIx].GetClassName().Equals(Assert.class.GetName())) {
// break;
// }
// startIx++;
//}
//// Skip bottom frames (part of junit framework)
//int endIx = startIx+1;
//while(endIx < stes.Length) {
// if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) {
// break;
// }
// endIx++;
//}
//if(startIx >= endIx) {
// // something went wrong. just print the whole stack trace
// e.printStackTrace(ps);
//}
//endIx -= 4; // Skip 4 frames of reflection invocation
//ps.println(e.ToString());
//for(int i=startIx; i<endIx; i++) {
// ps.println("\tat " + stes[i].ToString());
//}
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
private static String GetTargetFunctionName(IRow r)
{
if (r == null)
{
System.Console.WriteLine("Warning - given null row, can't figure out function name");
return null;
}
ICell cell = r.GetCell(SS.COLUMN_INDEX_FUNCTION_NAME);
if (cell == null)
{
System.Console.WriteLine("Warning - Row " + r.RowNum + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
return null;
}
if (cell.CellType == CellType.Blank)
{
return null;
}
if (cell.CellType == CellType.String)
{
return cell.RichStringCellValue.String;
}
throw new AssertionException("Bad cell type for 'function name' column: ("
+ cell.CellType + ") row (" + (r.RowNum + 1) + ")");
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using ClassWrapper;
using ConcurrencyHelpers.Coroutines;
using Node.Cs.Lib.Attributes;
using Node.Cs.Lib.Contexts;
using Node.Cs.Lib.Controllers;
using Node.Cs.Lib.Exceptions;
using Node.Cs.Lib.Filters;
using Node.Cs.Lib.Routing;
using Node.Cs.Lib.Utils;
using TB.ComponentModel;
using System.IO;
using Node.Cs.Lib.Loggers;
namespace Node.Cs.Lib.OnReceive
{
public class ControllersManagerCoroutine : Coroutine, IControllersManagerCoroutine
{
public ControllersManagerCoroutine()
{
RouteInstanceParams = new Dictionary<string, object>();
}
public bool IsChildRequest { get; set; }
//public ContextManager ContextManager { get; set; }
public INodeCsContext Context { get; set; }
public RouteInstance RouteDefintion { get; set; }
public string LocalPath { get; set; }
public Dictionary<string, object> ViewData { get; set; }
public ISessionManager SessionManager { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public Dictionary<string,object> RouteInstanceParams { get; set; }
protected void RunGlobalPostFilters(IResponse result)
{
if (IsChildRequest) return;
foreach (var filter in GlobalVars.GlobalFilters)
{
filter.OnPostExecute((HttpContextBase)Context, result);
}
}
/// <summary>
/// Wait for completion and store the result into the container object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
/// <param name="result"></param>
/// <returns></returns>
protected virtual Step InvokeControllerAndWait<T>(Func<IEnumerable<T>> func, Container result = null)
{
if (typeof(T) != typeof(Step))
{
return InvokeLocalAndWait(() => MakeControllerEnumerable((IEnumerable)func()), result);
}
if (result == null) result = new Container();
var enumerator = ((IEnumerable<Step>)func()).GetEnumerator();
return Step.DataStep(new EnumeratorWrapper
{
Enum = enumerator,
Result = result,
Culture = System.Threading.Thread.CurrentThread.CurrentCulture
});
}
private static IEnumerable<Step> MakeControllerEnumerable(IEnumerable enumerable)
{
foreach (var item in enumerable)
{
var stepItem = item as Step;
var stepResponse = item as StepResponse;
if (stepResponse != null)
{
stepItem = stepResponse.CalleStep;
}
if (item == null) yield return Step.Current;
else if (stepItem == null) yield return Step.DataStep(item);
else yield return stepItem;
}
}
private IEnumerable<Step> EnumerateResponse(IEnumerable<IResponse> enumerableResult)
{
foreach (var item in enumerableResult)
{
var calleeStep = item as StepResponse;
var itemStep = item as Step;
if (calleeStep != null)
{
yield return calleeStep.CalleStep;
}
else if (itemStep != null)
{
yield return itemStep;
}
else
{
yield return Step.DataStep(item);
yield break;
}
}
}
private bool TryInvoke(MethodWrapperDescriptor method,
Dictionary<string, object> allParams,
global::ClassWrapper.ClassWrapper controllerWrapper, bool hasConverter,
HttpContextBase context, bool isChildRequest, out object methResult)
{
try
{
var request = context.Request;
var parsValues = new List<object>();
methResult = null;
var methPars = method.Parameters.ToList();
for (int index = 0; index < methPars.Count; index++)
{
bool parValueSet = false;
var par = methPars[index];
object valueToAdd = null;
if (allParams.ContainsKey(par.Name))
{
var parValue = allParams[par.Name];
if (parValue.GetType() != par.ParameterType)
{
object convertedValue;
if (UniversalTypeConverter.TryConvert(parValue, par.ParameterType, out convertedValue))
{
valueToAdd = convertedValue;
parValueSet = true;
}
else if (!par.HasDefault)
{
if (par.ParameterType.IsValueType)
{
return false;
}
parValueSet = true;
}
}
else
{
valueToAdd = parValue;
parValueSet = true;
}
}
if (par.ParameterType == typeof(FormCollection))
{
parValueSet = true;
valueToAdd = new FormCollection(context.Request.Form);
}
if (parValueSet == false && request.ContentType != null)
{
var parType = par.ParameterType;
if (!parType.IsValueType &&
!parType.IsArray &&
!(parType == typeof(string)) &&
!parType.IsEnum &&
!(parType == typeof(object)))
{
try
{
valueToAdd = GlobalVars.ConversionService.Convert(parType, request.ContentType, request);
parValueSet = true;
}
catch (Exception)
{
}
}
}
if (par.HasDefault && !parValueSet)
{
parValueSet = true;
valueToAdd = par.Default;
}
if (!parValueSet && string.Compare(par.Name, "returnUrl", StringComparison.OrdinalIgnoreCase) == 0)
{
if (request.UrlReferrer != null)
{
parValueSet = true;
valueToAdd = request.UrlReferrer.ToString();
}
}
if (!par.GetType().IsValueType && !parValueSet)
{
parValueSet = true;
valueToAdd = null;
}
if (!parValueSet) return false;
parsValues.Add(valueToAdd);
}
var attributes = new List<Attribute>(method.Attributes);
foreach (var attribute in attributes)
{
var filter = attribute as IFilter;
if (filter != null)
{
if (!filter.OnPreExecute(context))
{
methResult = NullResponse.Instance;
return true;
}
}
else if (attribute is ChildActionOnly && !isChildRequest)
{
throw new NodeCsException("Item not found '{0}'.", 404, Context.Request.Url.ToString());
}
}
var msd = new ModelStateDictionary();
foreach (var par in parsValues)
{
if (ValidationAttributesService.CanValidate(par))
{
ValidationAttributesService.ValidateModel(par, msd);
}
}
controllerWrapper.Set("ModelState", msd);
var result = controllerWrapper.TryInvoke(method, out methResult, parsValues.ToArray());
if (result)
{
foreach (var attribute in attributes)
{
var filter = attribute as IFilter;
if (filter != null)
{
filter.OnPostExecute(context, null);
}
}
}
return result;
}
catch (Exception)
{
Logger.Info("Not found suitable action for method '{0}'.", method.Name);
methResult = null;
return false;
}
}
public IEnumerable<Step> HandleRoutedRequests(RouteInstance routeInstance, string localPath,
INodeCsContext context, bool isChildRequest = false)
{
var verb = context.Request.HttpMethod;
object methResult = null;
if (!string.IsNullOrEmpty(ControllerName) &&
!string.IsNullOrEmpty(ActionName))
{
var allParams = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var param in RouteInstanceParams)
{
allParams.Add(param.Key, param.Value);
}
foreach (var param in context.Request.QueryString.AllKeys)
{
if (param != null && !allParams.ContainsKey(param))
{
allParams.Add(param, context.Request.QueryString[param]);
}
}
foreach (var param in context.Request.Form.AllKeys)
{
if (param != null && !allParams.ContainsKey(param))
{
allParams.Add(param, context.Request.Form[param]);
}
}
var requestContentType = context.Request.ContentType;
bool hasConverter = GlobalVars.ConversionService.HasConverter(requestContentType);
var controller = (ControllerWrapperInstance)GlobalVars.ControllersFactoryHandler.Create(ControllerName + "Controller");
if (controller == null)
{
throw new NodeCsException("Url '{0}' not found.",404,Context.Request.Url.ToString());
}
controller.Instance.Set("HttpContext", (HttpContextBase)context);
var methods = controller.GetMethodGroup(ActionName, verb).ToList();
bool methodInvoked = false;
foreach (var method in methods)
{
if (TryInvoke(method, allParams, controller.Instance, hasConverter, (HttpContextBase)context, isChildRequest,
out methResult))
{
methodInvoked = true;
break;
}
}
if (!methodInvoked)
{
throw new NodeCsException("Url '{0}' not found.", 404, Context.Request.Url.ToString());
}
var enumerableResult = methResult as IEnumerable<IResponse>;
var result = new Container();
yield return Coroutine.InvokeLocalAndWait(() => EnumerateResponse(enumerableResult), result);
var typeofResponse = result.RawData.GetType();
var responseHandler = GlobalVars.ResponseHandlers.Load(typeofResponse);
var response = result.RawData as IResponse;
if (responseHandler != null && response != null)
{
responseHandler.Handle(controller, context, response);
yield return Step.DataStep(response);
}
else
{
yield return Step.DataStep(result.RawData);
}
if (controller != null)
{
GlobalVars.ControllersFactoryHandler.Release((IController)controller.Instance.Instance);
}
yield break;
}
throw new NodeCsException("Url '{0}' not found.", 404, Context.Request.Url.ToString());
}
public override IEnumerable<Step> Run()
{
var resultDate = new Container();
yield return InvokeControllerAndWait(() =>
HandleRoutedRequests(RouteDefintion, LocalPath, Context, IsChildRequest),
resultDate);
CheckException();
var result = resultDate.RawData as IResponse;
if (result != null)
{
RunGlobalPostFilters(result);
var responseHandler = GlobalVars.ResponseHandlers.Load(result.GetType());
yield return Step.Current;
if (responseHandler != null)
{
//Its responsability to close connection
var viewResult = result as IViewResponse;
if (viewResult != null)
{
ViewData = viewResult.ViewData;
if (!IsChildRequest)
{
Thread.AddCoroutine(BuildViewManager(viewResult));
}
else
{
yield return InvokeCoroutineAndWait(BuildViewManager(viewResult));
}
}
}
else
{
var dataResponse = result as DataResponse;
if (dataResponse != null)
{
Context.Response.ContentType = dataResponse.ContentType;
Context.Response.ContentEncoding = dataResponse.ContentEncoding;
var output = Context.Response.OutputStream;;
((IForcedHeadersResponse)Context.Response).SetContentLength(dataResponse.Data.Length);
#if !TESTHTTP
yield return InvokeTaskAndWait(output.WriteAsync(dataResponse.Data, 0, dataResponse.Data.Length));
if (!IsChildRequest)
{
output.Close();
}
#else
if (IsChildRequest)
{
yield return InvokeTaskAndWait(output.WriteAsync(dataResponse.Data, 0, dataResponse.Data.Length));
}
else
{
HttpSender.Send(output, dataResponse.Data, true);
}
#endif
}
else
{
var codesManager = new HttpCodesManager();
codesManager.Response = result as HttpCodeResponse;
codesManager.Context = Context;
codesManager.SessionManager = SessionManager;
Thread.AddCoroutine(codesManager);
}
}
}
ShouldTerminate = true;
}
public IPagesManager PagesManager { get; set; }
protected virtual ViewsManagerCoroutine BuildViewManager(IViewResponse viewResult)
{
var viewsManager = new ViewsManagerCoroutine();
viewsManager.PagesManager = PagesManager;
viewsManager.LocalPath = viewResult.View;
viewsManager.ViewData = ViewData;
viewsManager.IsChildRequest = IsChildRequest;
viewsManager.Context = Context;
viewsManager.SessionManager = SessionManager;
viewsManager.ViewBag = viewResult.ViewBag;
viewsManager.Model = viewResult.Model;
viewsManager.ModelState = viewResult.ModelState;
if (IsChildRequest)
{
viewsManager.StringBuilder = StringBuilder;
}
return viewsManager;
}
public override void OnError(Exception ex)
{
ShouldTerminate = true;
GlobalVars.ExceptionManager.HandleException(ex, (HttpContextBase)Context);
Context.Response.Close();
}
public void InitializeRouteInstance()
{
RouteInstanceParams = RouteDefintion.Parameters;
if (RouteDefintion.Parameters.ContainsKey("controller"))
{
ControllerName = RouteDefintion.Parameters["controller"].ToString();
}
if (RouteDefintion.Parameters.ContainsKey("action"))
{
ActionName = RouteDefintion.Parameters["action"].ToString();
}
}
public StringBuilder StringBuilder { get; set; }
}
}
| |
//
// DatabaseTrackListModel.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Data.Sqlite;
using Hyena.Query;
using Banshee.Base;
using Banshee.Query;
using Banshee.Database;
using Banshee.PlaybackController;
namespace Banshee.Collection.Database
{
public class DatabaseTrackListModel : TrackListModel, IExportableModel,
ICacheableDatabaseModel, IFilterable, ISortable, ICareAboutView, ISearchable
{
private readonly BansheeDbConnection connection;
private IDatabaseTrackModelProvider provider;
protected IDatabaseTrackModelCache cache;
private Banshee.Sources.DatabaseSource source;
private long count;
private long filtered_count;
private TimeSpan filtered_duration, duration;
private long filtered_filesize, filesize;
private ISortableColumn sort_column;
private string sort_query;
private bool forced_sort_query;
private string reload_fragment;
private string join_table, join_fragment, join_primary_key, join_column, condition, condition_from;
private string query_fragment;
private string user_query;
private int rows_in_view;
public DatabaseTrackListModel (BansheeDbConnection connection, IDatabaseTrackModelProvider provider, Banshee.Sources.DatabaseSource source)
{
this.connection = connection;
this.provider = provider;
this.source = source;
SelectAggregates = String.Format ("SUM({0}), SUM({1})",
BansheeQuery.DurationField.Column, BansheeQuery.FileSizeField.Column);
Selection.Changed += delegate {
if (SelectionAggregatesHandler != null) {
cache.UpdateSelectionAggregates (SelectionAggregatesHandler);
}
};
}
protected Action<IDataReader> SelectionAggregatesHandler { get; set; }
protected HyenaSqliteConnection Connection {
get { return connection; }
}
private bool initialized = false;
public void Initialize (IDatabaseTrackModelCache cache)
{
if (initialized)
return;
initialized = true;
this.cache = cache;
cache.AggregatesUpdated += HandleCacheAggregatesUpdated;
GenerateSortQueryPart ();
}
private bool have_new_user_query = true;
private void GenerateUserQueryFragment ()
{
if (!have_new_user_query)
return;
if (String.IsNullOrEmpty (UserQuery)) {
query_fragment = null;
query_tree = null;
} else {
query_tree = UserQueryParser.Parse (UserQuery, BansheeQuery.FieldSet);
query_fragment = (query_tree == null) ? null : query_tree.ToSql (BansheeQuery.FieldSet);
if (query_fragment != null && query_fragment.Length == 0) {
query_fragment = null;
query_tree = null;
}
}
have_new_user_query = false;
}
private QueryNode query_tree;
public QueryNode Query {
get { return query_tree; }
}
protected string SortQuery {
get { return sort_query; }
set { sort_query = value; }
}
protected virtual void GenerateSortQueryPart ()
{
SortQuery = (SortColumn == null || SortColumn.SortType == SortType.None)
? (SortColumn != null && source is Banshee.Playlist.PlaylistSource)
? "CorePlaylistEntries.ViewOrder ASC, CorePlaylistEntries.EntryID ASC"
: BansheeQuery.GetSort (BansheeQuery.ArtistField, true)
: BansheeQuery.GetSort (SortColumn.Field, SortColumn.SortType == SortType.Ascending);
}
private SortType last_sort_type = SortType.None;
public bool Sort (ISortableColumn column)
{
lock (this) {
if (forced_sort_query) {
return false;
}
// Don't sort by the same column and the same sort-type more than once
if (sort_column != null && sort_column == column && column.SortType == last_sort_type) {
return false;
}
last_sort_type = column.SortType;
sort_column = column;
GenerateSortQueryPart ();
cache.Clear ();
}
return true;
}
public void Resort ()
{
var column = sort_column;
sort_column = null;
Sort (column);
}
private void HandleCacheAggregatesUpdated (IDataReader reader)
{
filtered_duration = TimeSpan.FromMilliseconds (reader[1] == null ? 0 : Convert.ToInt64 (reader[1]));
filtered_filesize = reader[2] == null ? 0 : Convert.ToInt64 (reader[2]);
}
public override void Clear ()
{
cache.Clear ();
count = 0;
filesize = 0;
duration = TimeSpan.Zero;
filtered_count = 0;
OnCleared ();
}
public void InvalidateCache (bool notify)
{
if (cache == null) {
Log.ErrorFormat ("Called invalidate cache for {0}'s track model, but cache is null", source);
} else {
cache.Clear ();
if (notify) {
OnReloaded ();
}
}
}
private string unfiltered_query;
public virtual string UnfilteredQuery {
get {
return unfiltered_query ?? (unfiltered_query = String.Format (
"FROM {0} WHERE {1} {2}",
FromFragment,
String.IsNullOrEmpty (provider.Where) ? "1=1" : provider.Where,
ConditionFragment
));
}
}
private string from;
protected string From {
get {
if (from == null) {
from = provider.From;
int i = from.IndexOf (',');
if (i > 0) {
// Force the join order to fix bgo#581103 and bgo#603661
// See section 5.2 in http://www.sqlite.org/optoverview.html
from = from.Substring (0, i) + " CROSS JOIN " + from.Substring (i + 1);
}
}
return from;
}
set { from = value; }
}
private string from_fragment;
public string FromFragment {
get { return from_fragment ?? (from_fragment = String.Format ("{0}{1}", From, JoinFragment)); }
}
public virtual void UpdateUnfilteredAggregates ()
{
HyenaSqliteCommand count_command = new HyenaSqliteCommand (String.Format (
"SELECT COUNT(*), SUM({0}), SUM({1}) {2}",
BansheeQuery.FileSizeField.Column, BansheeQuery.DurationField.Column, UnfilteredQuery
));
using (HyenaDataReader reader = new HyenaDataReader (connection.Query (count_command))) {
count = reader.Get<long> (0);
filesize = reader.Get<long> (1);
duration = reader.Get<TimeSpan> (2);
}
}
public override void Reload ()
{
Reload (null);
}
public void Reload (IListModel reloadTrigger)
{
if (cache == null) {
Log.WarningFormat ("Called Reload on {0} for source {1} but cache is null; Did you forget to call AfterInitialized () in your DatabaseSource ctor?",
this, source == null ? "null source!" : source.Name);
return;
}
lock (this) {
GenerateUserQueryFragment ();
UpdateUnfilteredAggregates ();
cache.SaveSelection ();
List<IFilterListModel> reload_models = new List<IFilterListModel> ();
if (null == reloadTrigger) {
reload_models.AddRange (source.CurrentFilters);
} else {
reload_models.AddRange (
source.CurrentFilters.SkipWhile (x => reloadTrigger != x).Skip (1)
);
}
if (reload_models.Count == 0) {
ReloadWithFilters (true);
} else {
ReloadWithoutFilters ();
foreach (IFilterListModel model in reload_models) {
model.Reload (false);
}
bool have_filters = false;
foreach (IFilterListModel filter in source.CurrentFilters) {
have_filters |= !filter.Selection.AllSelected;
}
// Unless both artist/album selections are "all" (eg unfiltered), reload
// the track model again with the artist/album filters now in place.
if (have_filters) {
ReloadWithFilters (true);
}
}
cache.UpdateAggregates ();
cache.RestoreSelection ();
if (SelectionAggregatesHandler != null) {
cache.UpdateSelectionAggregates (SelectionAggregatesHandler);
}
filtered_count = cache.Count;
OnReloaded ();
// Trigger these after the track list, b/c visually it's more important for it to update first
foreach (IFilterListModel model in reload_models) {
model.RaiseReloaded ();
}
}
}
private void ReloadWithoutFilters ()
{
ReloadWithFilters (false);
}
private void ReloadWithFilters (bool with_filters)
{
StringBuilder qb = new StringBuilder ();
qb.Append (UnfilteredQuery);
if (with_filters) {
foreach (IFilterListModel filter in source.CurrentFilters) {
string filter_sql = filter.GetSqlFilter ();
if (filter_sql != null) {
qb.Append (" AND ");
qb.Append (filter_sql);
}
}
}
if (query_fragment != null) {
qb.Append (" AND ");
qb.Append (query_fragment);
}
if (sort_query != null) {
qb.Append (" ORDER BY ");
qb.Append (sort_query);
}
reload_fragment = qb.ToString ();
cache.Reload ();
}
private QueryFieldSet query_fields = BansheeQuery.FieldSet;
public QueryFieldSet QueryFields {
get { return query_fields; }
protected set { query_fields = value; }
}
public bool Contains (DatabaseTrackInfo track)
{
return track != null && connection.Query<bool> (
String.Format ("SELECT COUNT(*) > 0 {0} AND CoreTracks.TrackID = ? LIMIT 1", UnfilteredQuery),
track.TrackId
);
}
public int IndexOf (QueryNode query, long offset)
{
lock (this) {
if (query == null) {
return -1;
}
return (int) cache.IndexOf (query.ToSql (QueryFields), offset);
}
}
public override int IndexOf (TrackInfo track)
{
lock (this) {
if (track is DatabaseTrackInfo) {
return (int) cache.IndexOf (track as DatabaseTrackInfo);
} else if (track is Banshee.Streaming.RadioTrackInfo) {
return (int) cache.IndexOf ((track as Banshee.Streaming.RadioTrackInfo).ParentTrack as DatabaseTrackInfo);
}
return -1;
}
}
public int IndexOfFirst (TrackInfo track)
{
lock (this) {
return IndexOf (cache.GetSingleWhere ("AND MetadataHash = ? ORDER BY OrderID", track.MetadataHash));
}
}
public override TrackInfo GetRandom (DateTime notPlayedSince)
{
return GetRandom (notPlayedSince, "song", true, false, Shuffler.Playback);
}
public TrackInfo GetRandom (DateTime notPlayedSince, string shuffle_mode, bool repeat, bool resetSinceTime, Shuffler shuffler)
{
lock (this) {
shuffler.SetModelAndCache (this, cache);
return shuffler.GetRandom (notPlayedSince, shuffle_mode, repeat, resetSinceTime);
}
}
public override TrackInfo this[int index] {
get {
lock (this) {
return cache.GetValue (index);
}
}
}
public override int Count {
get { return (int) filtered_count; }
}
public virtual TimeSpan Duration {
get { return filtered_duration; }
}
public virtual long FileSize {
get { return filtered_filesize; }
}
public long UnfilteredFileSize {
get { return filesize; }
}
public TimeSpan UnfilteredDuration {
get { return duration; }
}
public int UnfilteredCount {
get { return (int) count; }
set { count = value; }
}
public string UserQuery {
get { return user_query; }
set {
lock (this) {
user_query = value;
have_new_user_query = true;
}
}
}
public string ForcedSortQuery {
get { return forced_sort_query ? sort_query : null; }
set {
forced_sort_query = value != null;
sort_query = value;
if (cache != null) {
cache.Clear ();
}
}
}
public string JoinTable {
get { return join_table; }
set {
join_table = value;
join_fragment = String.Format (", {0}", join_table);
}
}
public string JoinFragment {
get { return join_fragment; }
}
public string JoinPrimaryKey {
get { return join_primary_key; }
set { join_primary_key = value; }
}
public string JoinColumn {
get { return join_column; }
set { join_column = value; }
}
public void AddCondition (string part)
{
AddCondition (null, part);
}
public void AddCondition (string tables, string part)
{
if (!String.IsNullOrEmpty (part)) {
condition = condition == null ? part : String.Format ("{0} AND {1}", condition, part);
if (!String.IsNullOrEmpty (tables)) {
condition_from = condition_from == null ? tables : String.Format ("{0}, {1}", condition_from, tables);
}
}
}
public string Condition {
get { return condition; }
}
private string condition_from_fragment;
public string ConditionFromFragment {
get {
if (condition_from_fragment == null) {
if (JoinFragment == null) {
condition_from_fragment = condition_from;
} else {
if (condition_from == null) {
condition_from = "CoreTracks";
}
condition_from_fragment = String.Format ("{0}{1}", condition_from, JoinFragment);
}
}
return condition_from_fragment;
}
}
public string ConditionFragment {
get { return PrefixCondition ("AND"); }
}
private string PrefixCondition (string prefix)
{
string condition = Condition;
return String.IsNullOrEmpty (condition)
? String.Empty
: String.Format (" {0} {1} ", prefix, condition);
}
public int CacheId {
get { return (int) cache.CacheId; }
}
public ISortableColumn SortColumn {
get { return sort_column; }
}
public virtual int RowsInView {
protected get { return rows_in_view; }
set { rows_in_view = value; }
}
int IExportableModel.GetLength ()
{
return Count;
}
IDictionary<string, object> IExportableModel.GetMetadata (int index)
{
return this[index].GenerateExportable ();
}
private string track_ids_sql;
public string TrackIdsSql {
get {
if (track_ids_sql == null) {
if (!CachesJoinTableEntries) {
track_ids_sql = "ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?";
} else {
track_ids_sql = String.Format (
"{0} FROM {1} WHERE {2} IN (SELECT ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?)",
JoinColumn, JoinTable, JoinPrimaryKey
);
}
}
return track_ids_sql;
}
}
private bool caches_join_table_entries = false;
public bool CachesJoinTableEntries {
get { return caches_join_table_entries; }
set { caches_join_table_entries = value; }
}
// Implement ICacheableModel
public int FetchCount {
get { return RowsInView > 0 ? RowsInView * 5 : 100; }
}
public string SelectAggregates { get; protected set; }
// Implement IDatabaseModel
public string ReloadFragment {
get { return reload_fragment; }
}
public bool CachesValues { get { return false; } }
}
}
| |
//
// Mono.Data.TdsClient.TdsParameterCollection.cs
//
// Author:
// Rodrigo Moya (rodrigo@ximian.com)
// Daniel Morgan (danmorg@sc.rr.com)
// Tim Coleman (tim@timcoleman.com)
//
// (C) Ximian, Inc 2002
// Copyright (C) Tim Coleman, 2002
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Data.Tds;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Collections;
namespace Mono.Data.TdsClient {
[ListBindable (false)]
public sealed class TdsParameterCollection : MarshalByRefObject, IDataParameterCollection, IList, ICollection, IEnumerable
{
#region Fields
ArrayList list = new ArrayList();
TdsMetaParameterCollection metaParameters;
TdsCommand command;
#endregion // Fields
#region Constructors
internal TdsParameterCollection (TdsCommand command)
{
this.command = command;
metaParameters = new TdsMetaParameterCollection ();
}
#endregion // Constructors
#region Properties
public int Count {
get { return list.Count; }
}
public TdsParameter this [int index] {
get { return (TdsParameter) list [index]; }
set { list [index] = (TdsParameter) value; }
}
object IDataParameterCollection.this [string parameterName] {
get { return this[parameterName]; }
set {
if (!(value is TdsParameter))
throw new InvalidCastException ("Only SQLParameter objects can be used.");
this [parameterName] = (TdsParameter) value;
}
}
public TdsParameter this [string parameterName] {
get {
foreach (TdsParameter p in list)
if (p.ParameterName.Equals (parameterName))
return p;
throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName);
}
set {
if (!Contains (parameterName))
throw new IndexOutOfRangeException("The specified name does not exist: " + parameterName);
this [IndexOf (parameterName)] = value;
}
}
object IList.this [int index] {
get { return (TdsParameter) this [index]; }
set { this [index] = (TdsParameter) value; }
}
bool IList.IsFixedSize {
get { return list.IsFixedSize; }
}
bool IList.IsReadOnly {
get { return list.IsReadOnly; }
}
bool ICollection.IsSynchronized {
get { return list.IsSynchronized; }
}
object ICollection.SyncRoot {
get { return list.SyncRoot; }
}
internal TdsMetaParameterCollection MetaParameters {
get { return metaParameters; }
}
#endregion // Properties
#region Methods
public int Add (object value)
{
if (!(value is TdsParameter))
throw new InvalidCastException ("The parameter was not an TdsParameter.");
Add ((TdsParameter) value);
return IndexOf (value);
}
public TdsParameter Add (TdsParameter value)
{
if (value.Container != null)
throw new ArgumentException ("The TdsParameter specified in the value parameter is already added to this or another TdsParameterCollection.");
value.Container = this;
list.Add (value);
metaParameters.Add (value.MetaParameter);
return value;
}
public TdsParameter Add (string parameterName, object value)
{
return Add (new TdsParameter (parameterName, value));
}
public TdsParameter Add (string parameterName, TdsType sybaseType)
{
return Add (new TdsParameter (parameterName, sybaseType));
}
public TdsParameter Add (string parameterName, TdsType sybaseType, int size)
{
return Add (new TdsParameter (parameterName, sybaseType, size));
}
public TdsParameter Add (string parameterName, TdsType sybaseType, int size, string sourceColumn)
{
return Add (new TdsParameter (parameterName, sybaseType, size, sourceColumn));
}
public void Clear()
{
metaParameters.Clear ();
list.Clear ();
}
public bool Contains (object value)
{
if (!(value is TdsParameter))
throw new InvalidCastException ("The parameter was not an TdsParameter.");
return Contains (((TdsParameter) value).ParameterName);
}
public bool Contains (string value)
{
foreach (TdsParameter p in list)
if (p.ParameterName.Equals (value))
return true;
return false;
}
public void CopyTo (Array array, int index)
{
list.CopyTo (array, index);
}
public IEnumerator GetEnumerator()
{
return list.GetEnumerator ();
}
public int IndexOf (object value)
{
if (!(value is TdsParameter))
throw new InvalidCastException ("The parameter was not an TdsParameter.");
return IndexOf (((TdsParameter) value).ParameterName);
}
public int IndexOf (string parameterName)
{
return list.IndexOf (parameterName);
}
public void Insert (int index, object value)
{
list.Insert (index, value);
}
public void Remove (object value)
{
metaParameters.Remove (((TdsParameter) value).MetaParameter);
list.Remove (value);
}
public void RemoveAt (int index)
{
metaParameters.RemoveAt (index);
list.RemoveAt (index);
}
public void RemoveAt (string parameterName)
{
RemoveAt (IndexOf (parameterName));
}
#endregion // Methods
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias Scripting;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver;
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
private static Control s_control;
private InteractiveAssemblyLoader _assemblyLoader;
private MetadataShadowCopyProvider _metadataFileProvider;
private ReplServiceProvider _replServiceProvider;
private InteractiveScriptGlobals _globals;
// Session is not thread-safe by itself, and the compilation
// and execution of scripts are asynchronous operations.
// However since the operations are executed serially, it
// is sufficient to lock when creating the async tasks.
private readonly object _lastTaskGuard = new object();
private Task<EvaluationState> _lastTask;
private struct EvaluationState
{
internal ImmutableArray<string> SourceSearchPaths;
internal ImmutableArray<string> ReferenceSearchPaths;
internal string WorkingDirectory;
internal readonly ScriptState<object> ScriptStateOpt;
internal readonly ScriptOptions ScriptOptions;
internal EvaluationState(
ScriptState<object> scriptState,
ScriptOptions scriptOptions,
ImmutableArray<string> sourceSearchPaths,
ImmutableArray<string> referenceSearchPaths,
string workingDirectory)
{
ScriptStateOpt = scriptState;
ScriptOptions = scriptOptions;
SourceSearchPaths = sourceSearchPaths;
ReferenceSearchPaths = referenceSearchPaths;
WorkingDirectory = workingDirectory;
}
internal EvaluationState WithScriptState(ScriptState<object> state)
{
return new EvaluationState(
state,
ScriptOptions,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
internal EvaluationState WithOptions(ScriptOptions options)
{
return new EvaluationState(
ScriptStateOpt,
options,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
}
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
var initialState = new EvaluationState(
scriptState: null,
scriptOptions: ScriptOptions.Default,
sourceSearchPaths: ImmutableArray<string>.Empty,
referenceSearchPaths: ImmutableArray<string>.Empty,
workingDirectory: Directory.GetCurrentDirectory());
_lastTask = Task.FromResult(initialState);
Console.OutputEncoding = Encoding.UTF8;
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replServiceProviderType, string cultureName)
{
Debug.Assert(replServiceProviderType != null);
Debug.Assert(cultureName != null);
Debug.Assert(_metadataFileProvider == null);
Debug.Assert(_assemblyLoader == null);
Debug.Assert(_replServiceProvider == null);
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories,
documentationCommentsCulture: new CultureInfo(cultureName));
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType);
_globals = new InteractiveScriptGlobals(Console.Out, _replServiceProvider.ObjectFormatter);
}
private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null,
GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null,
(path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties));
}
private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
using (var resetEvent = new ManualResetEventSlim(false))
{
var uiThread = new Thread(() =>
{
s_control = new Control();
s_control.CreateControl();
resetEvent.Set();
Application.Run();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
resetEvent.Wait();
}
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_lastTaskGuard)
{
_lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory);
}
}
private async Task<EvaluationState> SetPathsAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
Directory.SetCurrentDirectory(baseDirectory);
_globals.ReferencePaths.Clear();
_globals.ReferencePaths.AddRange(referenceSearchPaths);
_globals.SourcePaths.Clear();
_globals.SourcePaths.AddRange(sourceSearchPaths);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
lock (_lastTaskGuard)
{
_lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting);
}
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
lock (_lastTaskGuard)
{
_lastTask = AddReferenceAsync(_lastTask, operation, reference);
}
}
private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences));
success = true;
}
else
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
return state;
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteAsync(_lastTask, operation, text);
}
}
private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions);
if (script != null)
{
// successful if compiled
success = true;
// remove references and imports from the options, they have been applied and will be inherited from now on:
state = state.WithOptions(state.ScriptOptions.RemoveImportsAndReferences());
var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
if (newScriptState != null)
{
DisplaySubmissionResult(newScriptState);
state = state.WithScriptState(newScriptState);
}
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
private void DisplaySubmissionResult(ScriptState<object> state)
{
if (state.Script.HasReturnValue())
{
_globals.Print(state.ReturnValue);
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteFileAsync(operation, _lastTask, path);
}
}
private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success)
{
// send any updates to the host object and current directory back to the client:
var currentSourcePaths = _globals.SourcePaths.ToArray();
var currentReferencePaths = _globals.ReferencePaths.ToArray();
var currentWorkingDirectory = Directory.GetCurrentDirectory();
var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths;
var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths;
var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory;
operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory));
// no changes in resolvers:
if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null)
{
return state;
}
var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths);
var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths);
var newWorkingDirectory = currentWorkingDirectory;
ScriptOptions newOptions = state.ScriptOptions;
if (changedReferencePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory));
}
if (changedSourcePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory));
}
return new EvaluationState(
state.ScriptStateOpt,
newOptions,
newSourcePaths,
newReferencePaths,
workingDirectory: newWorkingDirectory);
}
private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask)
{
try
{
return await lastTask.ConfigureAwait(false);
}
catch (Exception e)
{
ReportUnhandledException(e);
return lastTask.Result;
}
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private async Task<EvaluationState> InitializeContextAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string initializationFileOpt,
bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_replServiceProvider.Logo);
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _replServiceProvider.CommandLineParser;
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);
var metadataReferences = new List<PortableExecutableReference>();
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
metadataReferences.AddRange(resolvedReferences);
}
}
var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;
var rspState = new EvaluationState(
state.ScriptStateOpt,
state.ScriptOptions.
WithFilePath(scriptPathOpt).
WithReferences(metadataReferences).
WithImports(CommandLineHelpers.GetImports(args)).
WithMetadataResolver(metadataResolver).
WithSourceResolver(sourceResolver),
args.SourcePaths,
args.ReferencePaths,
rspDirectory);
_globals.ReferencePaths.Clear();
_globals.ReferencePaths.AddRange(args.ReferencePaths);
_globals.SourcePaths.Clear();
_globals.SourcePaths.AddRange(args.SourcePaths);
_globals.Args.AddRange(args.ScriptArguments);
if (scriptPathOpt != null)
{
var newScriptState = await ExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false);
if (newScriptState != null)
{
// remove references and imports from the options, they have been applied and will be inherited from now on:
rspState = rspState.
WithScriptState(newScriptState).
WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
}
}
state = rspState;
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options)
{
Script script;
var scriptOptions = options.WithFilePath(path);
if (previousScript != null)
{
script = previousScript.ContinueWith(code, scriptOptions);
}
else
{
script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader);
}
var diagnostics = script.Compile();
if (diagnostics.HasAnyErrors())
{
DisplayInteractiveErrors(diagnostics, Console.Error);
return null;
}
return (Script<object>)script;
}
private async Task<EvaluationState> ExecuteFileAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
Task<EvaluationState> lastTask,
string path)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
var success = false;
try
{
var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false);
var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
success = true;
state = state.WithScriptState(newScriptState);
}
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath)
{
string content = null;
if (fullPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
content = File.ReadAllText(fullPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
ScriptState<object> newScriptState = null;
if (content != null)
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
if (script != null)
{
newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
}
}
return newScriptState;
}
private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray();
var uniqueDirectories = new HashSet<string>(directories);
writer.WriteLine(uniqueDirectories.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string directory in directories)
{
if (uniqueDirectories.Remove(directory))
{
writer.Write(" ");
writer.WriteLine(directory);
}
}
}
private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt)
{
return await ((Task<ScriptState<object>>)s_control.Invoke(
(Func<Task<ScriptState<object>>>)(async () =>
{
try
{
var task = (stateOpt == null) ?
script.RunAsync(_globals, CancellationToken.None) :
script.RunFromAsync(stateOpt, CancellationToken.None);
return await task.ConfigureAwait(false);
}
catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException)
{
Console.Error.WriteLine(e.InnerException.Message);
return null;
}
catch (Exception e)
{
Console.Error.Write(_replServiceProvider.ObjectFormatter.FormatException(e));
return null;
}
}))).ConfigureAwait(false);
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _replServiceProvider.DiagnosticFormatter;
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A command to get the content of an item at a specified path
/// </summary>
[Cmdlet(VerbsCommon.Get, "Content", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113310")]
public class GetContentCommand : ContentCommandBase
{
#region Parameters
/// <summary>
/// The number of content items to retrieve per block.
/// By default this value is 1 which means read one block
/// at a time. To read all blocks at once, set this value
/// to a negative number.
/// </summary>
///
[Parameter(ValueFromPipelineByPropertyName = true)]
public long ReadCount { get; set; } = 1;
/// <summary>
/// The number of content items to retrieve. By default this
/// value is -1 which means read all the content
/// </summary>
///
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("First", "Head")]
public long TotalCount
{
get
{
return _totalCount;
} // get
set
{
_totalCount = value;
_totalCountSpecified = true;
}
} // TotalCount
private bool _totalCountSpecified = false;
/// <summary>
/// The number of content items to retrieve from the back of the file.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Last")]
public int Tail
{
set
{
_backCount = value;
_tailSpecified = true;
}
get { return _backCount; }
}
private int _backCount = -1;
private bool _tailSpecified = false;
/// <summary>
/// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets
/// that require dynamic parameters should override this method and return the
/// dynamic parameter object.
/// </summary>
///
/// <param name="context">
/// The context under which the command is running.
/// </param>
///
/// <returns>
/// An object representing the dynamic parameters for the cmdlet or null if there
/// are none.
/// </returns>
///
internal override object GetDynamicParameters(CmdletProviderContext context)
{
if (Path != null && Path.Length > 0)
{
return InvokeProvider.Content.GetContentReaderDynamicParameters(Path[0], context);
}
return InvokeProvider.Content.GetContentReaderDynamicParameters(".", context);
} // GetDynamicParameters
#endregion Parameters
#region parameter data
/// <summary>
/// The number of content items to retrieve.
/// </summary>
private long _totalCount = -1;
#endregion parameter data
#region Command code
/// <summary>
/// Gets the content of an item at the specified path
/// </summary>
protected override void ProcessRecord()
{
// TotalCount and Tail should not be specified at the same time.
// Throw out terminating error if this is the case.
if (_totalCountSpecified && _tailSpecified)
{
string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail");
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null);
WriteError(error);
return;
}
if (TotalCount == 0)
{
// Don't read anything
return;
}
// Get the content readers
CmdletProviderContext currentContext = CmdletProviderContext;
contentStreams = this.GetContentReaders(Path, currentContext);
try
{
// Iterate through the content holders reading the content
foreach (ContentHolder holder in contentStreams)
{
long countRead = 0;
Dbg.Diagnostics.Assert(
holder.Reader != null,
"All holders should have a reader assigned");
if (_tailSpecified && !(holder.Reader is FileSystemContentReaderWriter))
{
string errMsg = SessionStateStrings.GetContent_TailNotSupported;
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail);
WriteError(error);
continue;
}
// If Tail is negative, we are supposed to read all content out. This is same
// as reading forwards. So we read forwards in this case.
// If Tail is positive, we seek the right position. Or, if the seek failed
// because of an unsupported encoding, we scan forward to get the tail content.
if (Tail >= 0)
{
bool seekSuccess = false;
try
{
seekSuccess = SeekPositionForTail(holder.Reader);
}
catch (Exception e)
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentReadError",
SessionStateStrings.ProviderContentReadError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
WriteError(new ErrorRecord(
providerException.ErrorRecord,
providerException));
continue;
}
// If the seek was successful, we start to read forwards from that
// point. Otherwise, we need to scan forwards to get the tail content.
if (!seekSuccess && !ScanForwardsForTail(holder, currentContext))
{
continue;
}
}
if (TotalCount != 0)
{
IList results = null;
do
{
long countToRead = ReadCount;
// Make sure we only ask for the amount the user wanted
// I am using TotalCount - countToRead so that I don't
// have to worry about overflow
if ((TotalCount > 0) && (TotalCount - countToRead < countRead))
{
countToRead = TotalCount - countRead;
}
try
{
results = holder.Reader.Read(countToRead);
}
catch (Exception e) // Catch-all OK. 3rd party callout
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentReadError",
SessionStateStrings.ProviderContentReadError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
WriteError(new ErrorRecord(
providerException.ErrorRecord,
providerException));
break;
}
if (results != null && results.Count > 0)
{
countRead += results.Count;
if (ReadCount == 1)
{
// Write out the content as a single object
WriteContentObject(results[0], countRead, holder.PathInfo, currentContext);
}
else
{
// Write out the content as an array of objects
WriteContentObject(results, countRead, holder.PathInfo, currentContext);
}
}
} while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount));
}
} // foreach holder in contentStreams
}
finally
{
// close all the content readers
CloseContent(contentStreams, false);
// Empty the content holder array
contentStreams = new List<ContentHolder>();
}
} // ProcessRecord
/// <summary>
/// Scan forwards to get the tail content
/// </summary>
/// <param name="holder"></param>
/// <param name="currentContext"></param>
/// <returns>
/// true if no error occured
/// false if there was an error
/// </returns>
private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext)
{
var fsReader = holder.Reader as FileSystemContentReaderWriter;
Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter");
var tailResultQueue = new Queue<object>();
IList results = null;
ErrorRecord error = null;
do
{
try
{
results = fsReader.ReadWithoutWaitingChanges(ReadCount);
}
catch (Exception e)
{
CommandsCommon.CheckForSevereException(this, e);
ProviderInvocationException providerException =
new ProviderInvocationException(
"ProviderContentReadError",
SessionStateStrings.ProviderContentReadError,
holder.PathInfo.Provider,
holder.PathInfo.Path,
e);
// Log a provider health event
MshLog.LogProviderHealthEvent(
this.Context,
holder.PathInfo.Provider.Name,
providerException,
Severity.Warning);
// Create and save the error record. The error record
// will be written outside the while loop.
// This is to make sure the accumulated results get written
// out before the error recrod when the 'scanForwardForTail' is true.
error = new ErrorRecord(
providerException.ErrorRecord,
providerException);
break;
}
if (results != null && results.Count > 0)
{
foreach (object entry in results)
{
if (tailResultQueue.Count == Tail)
tailResultQueue.Dequeue();
tailResultQueue.Enqueue(entry);
}
}
} while (results != null && results.Count > 0);
if (tailResultQueue.Count > 0)
{
// Respect the ReadCount parameter.
// Output single object when ReadCount == 1; Output array otherwise
int count = 0;
if (ReadCount <= 0 || (ReadCount >= tailResultQueue.Count && ReadCount != 1))
{
count = tailResultQueue.Count;
ArrayList outputList = new ArrayList();
while (tailResultQueue.Count > 0)
{
outputList.Add(tailResultQueue.Dequeue());
}
// Write out the content as an array of objects
WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext);
}
else if (ReadCount == 1)
{
// Write out the contnet as single object
while (tailResultQueue.Count > 0)
WriteContentObject(tailResultQueue.Dequeue(), count++, holder.PathInfo, currentContext);
}
else // ReadCount < Queue.Count
{
while (tailResultQueue.Count >= ReadCount)
{
ArrayList outputList = new ArrayList();
for (int idx = 0; idx < ReadCount; idx++, count++)
outputList.Add(tailResultQueue.Dequeue());
// Write out the content as an array of objects
WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext);
}
int remainder = tailResultQueue.Count;
if (remainder > 0)
{
ArrayList outputList = new ArrayList();
for (; remainder > 0; remainder--, count++)
outputList.Add(tailResultQueue.Dequeue());
// Write out the content as an array of objects
WriteContentObject(outputList.ToArray(), count, holder.PathInfo, currentContext);
}
}
}
if (error != null)
{
WriteError(error);
return false;
}
return true;
}
/// <summary>
/// Seek position to the right place
/// </summary>
/// <param name="reader">
/// reader should be able to be casted to FileSystemContentReader
/// </param>
/// <returns>
/// true if the stream pointer is moved to the right place
/// false if we cannot seek
/// </returns>
private bool SeekPositionForTail(IContentReader reader)
{
var fsReader = reader as FileSystemContentReaderWriter;
Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter");
try
{
fsReader.SeekItemsBackward(Tail);
return true;
}
catch (BackReaderEncodingNotSupportedException)
{
// Move to the head
fsReader.Seek(0, SeekOrigin.Begin);
return false;
}
}
/// <summary>
/// Be sure to clean up
/// </summary>
protected override void EndProcessing()
{
Dispose(true);
}
#endregion Command code
} // GetContentCommand
} // namespace Microsoft.PowerShell.Commands
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Net.Configuration;
using EventStore.Common.Log;
using EventStore.Core.Bus;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class CoreProjectionQueue
{
private readonly ILogger _logger = LogManager.GetLoggerFor<CoreProjectionQueue>();
private readonly StagedProcessingQueue _queuePendingEvents;
private readonly IPublisher _publisher;
private readonly Guid _projectionCorrelationId;
private readonly int _pendingEventsThreshold;
private readonly Action _updateStatistics;
private CheckpointTag _lastEnqueuedEventTag;
private bool _justInitialized;
private bool _subscriptionPaused;
public event Action EnsureTickPending
{
add { _queuePendingEvents.EnsureTickPending += value; }
remove { _queuePendingEvents.EnsureTickPending -= value; }
}
public CoreProjectionQueue(
Guid projectionCorrelationId, IPublisher publisher, int pendingEventsThreshold,
bool orderedPartitionProcessing, Action updateStatistics = null)
{
_queuePendingEvents =
new StagedProcessingQueue(
new[]
{
true /* record event order - async with ordered output*/,
true /* get state partition - ordered as it may change correlation id - sync */,
false /* load foreach state - async- unordered completion*/,
orderedPartitionProcessing /* process Js - unordered/ordered - inherently unordered/ordered completion*/,
true /* write emits - ordered - async ordered completion*/,
false /* complete item */
});
_publisher = publisher;
_projectionCorrelationId = projectionCorrelationId;
_pendingEventsThreshold = pendingEventsThreshold;
_updateStatistics = updateStatistics;
}
public bool IsRunning
{
get { return _isRunning; }
}
public bool ProcessEvent()
{
var processed = false;
if (_queuePendingEvents.Count > 0)
processed = ProcessOneEventBatch();
return processed;
}
public int GetBufferedEventCount()
{
return _queuePendingEvents.Count;
}
public void EnqueueTask(WorkItem workItem, CheckpointTag workItemCheckpointTag, bool allowCurrentPosition = false)
{
ValidateQueueingOrder(workItemCheckpointTag, allowCurrentPosition);
workItem.SetProjectionQueue(this);
workItem.SetCheckpointTag(workItemCheckpointTag);
_queuePendingEvents.Enqueue(workItem);
}
public void EnqueueOutOfOrderTask(WorkItem workItem)
{
if (_lastEnqueuedEventTag == null)
throw new InvalidOperationException(
"Cannot enqueue an out-of-order task. The projection position is currently unknown.");
workItem.SetProjectionQueue(this);
workItem.SetCheckpointTag(_lastEnqueuedEventTag);
_queuePendingEvents.Enqueue(workItem);
}
public void InitializeQueue(CheckpointTag zeroCheckpointTag)
{
_subscriptionPaused = false;
_unsubscribed = false;
_lastReportedStatisticsTimeStamp = default(DateTime);
_unsubscribed = false;
_subscriptionId = Guid.Empty;
_queuePendingEvents.Initialize();
_lastEnqueuedEventTag = zeroCheckpointTag;
_justInitialized = true;
}
public string GetStatus()
{
return (_subscriptionPaused ? "/Paused" : "");
}
private void ValidateQueueingOrder(CheckpointTag eventTag, bool allowCurrentPosition = false)
{
if (eventTag < _lastEnqueuedEventTag || (!(allowCurrentPosition || _justInitialized) && eventTag <= _lastEnqueuedEventTag))
throw new InvalidOperationException(
string.Format(
"Invalid order. Last known tag is: '{0}'. Current tag is: '{1}'", _lastEnqueuedEventTag,
eventTag));
_justInitialized = _justInitialized && (eventTag == _lastEnqueuedEventTag);
_lastEnqueuedEventTag = eventTag;
}
private void PauseSubscription()
{
if (_subscriptionId == Guid.Empty)
throw new InvalidOperationException("Not subscribed");
if (!_subscriptionPaused && !_unsubscribed)
{
_subscriptionPaused = true;
_publisher.Publish(
new ReaderSubscriptionManagement.Pause(_subscriptionId));
}
}
private void ResumeSubscription()
{
if (_subscriptionId == Guid.Empty)
throw new InvalidOperationException("Not subscribed");
if (_subscriptionPaused && !_unsubscribed)
{
_subscriptionPaused = false;
_publisher.Publish(
new ReaderSubscriptionManagement.Resume(_subscriptionId));
}
}
private DateTime _lastReportedStatisticsTimeStamp = default(DateTime);
private bool _unsubscribed;
private Guid _subscriptionId;
private bool _isRunning;
private bool ProcessOneEventBatch()
{
if (_queuePendingEvents.Count > _pendingEventsThreshold)
PauseSubscription();
var processed = _queuePendingEvents.Process(max: 30);
if (_subscriptionPaused && _queuePendingEvents.Count < _pendingEventsThreshold / 2)
ResumeSubscription();
if (_updateStatistics != null
&& ((_queuePendingEvents.Count == 0)
|| (DateTime.UtcNow - _lastReportedStatisticsTimeStamp).TotalMilliseconds > 500))
_updateStatistics();
_lastReportedStatisticsTimeStamp = DateTime.UtcNow;
return processed;
}
public void Unsubscribed()
{
_unsubscribed = true;
}
public void Subscribed(Guid currentSubscriptionId)
{
if (_unsubscribed)
throw new InvalidOperationException("Unsubscribed");
if (_subscriptionId != Guid.Empty)
throw new InvalidOperationException("Already subscribed");
_subscriptionId = currentSubscriptionId;
}
public void SetIsRunning(bool isRunning)
{
_isRunning = isRunning;
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
using Bearded.Utilities.Testing.Monads;
using FluentAssertions;
using Xunit;
using Xunit.Sdk;
namespace Bearded.Utilities.Tests;
[SuppressMessage("ReSharper", "ArgumentsStyleAnonymousFunction")]
public sealed class MaybeTests
{
public sealed class ValueOrDefault
{
public sealed class WithEagerDefault
{
[Fact]
public void ReturnsDefaultOnNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.ValueOrDefault(100).Should().Be(100);
}
[Fact]
public void ReturnsValueOnJust()
{
var maybe = Maybe.Just(200);
maybe.ValueOrDefault(100).Should().Be(200);
}
}
public sealed class WithLazyDefault
{
[Fact]
public void ReturnsDefaultOnNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.ValueOrDefault(() => 100).Should().Be(100);
}
[Fact]
public void ReturnsValueOnJust()
{
var maybe = Maybe.Just(200);
maybe.ValueOrDefault(() => 100).Should().Be(200);
}
}
}
public sealed class ValueOrError
{
public sealed class WithEagerError
{
[Fact]
public void ReturnsFailureOnNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.ValueOrFailure("something went wrong").Should().BeFailureWithError("something went wrong");
}
[Fact]
public void ReturnsSuccessOnJust()
{
var maybe = Maybe.Just(200);
maybe.ValueOrFailure("something went wrong").Should().BeSuccessWithResult(200);
}
}
public sealed class WithLazyError
{
[Fact]
public void ReturnsFailureOnNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.ValueOrFailure(() => "something went wrong").Should()
.BeFailureWithError("something went wrong");
}
[Fact]
public void ReturnsSuccessOnJust()
{
var maybe = Maybe.Just(200);
maybe.ValueOrFailure(() => "something went wrong").Should().BeSuccessWithResult(200);
}
}
}
public sealed class Select
{
[Fact]
public void MapsNothingToNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.Select(i => i * 2).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void MapsValueToJust()
{
var maybe = Maybe.Just(100);
maybe.Select(i => i * 2).Should().Be(Maybe.Just(200));
}
}
public sealed class SelectMany
{
[Fact]
public void MapsNothingToNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.SelectMany(i => Maybe.Just(i * 2)).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void MapsValueToJust()
{
var maybe = Maybe.Just(100);
maybe.SelectMany(i => Maybe.Just(i * 2)).Should().Be(Maybe.Just(200));
}
[Fact]
public void MapsValueToNothing()
{
var maybe = Maybe.Just(100);
maybe.SelectMany(i => Maybe<int>.Nothing).Should().Be(Maybe<int>.Nothing);
}
}
public sealed class Where
{
[Fact]
public void MapsNothingToNothingIfPredicateReturnsFalse()
{
var maybe = Maybe<int>.Nothing;
maybe.Where(_ => false).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void MapsNothingToNothingIfPredicateReturnsTrue()
{
var maybe = Maybe<int>.Nothing;
maybe.Where(_ => true).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void MapsJustToNothingIfPredicateReturnsFalse()
{
var maybe = Maybe.Just(100);
maybe.Where(_ => false).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void MapsJustToJustIfPredicateReturnsTrue()
{
var maybe = Maybe.Just(100);
maybe.Where(_ => true).Should().Be(Maybe.Just(100));
}
}
public sealed class MatchWithOneParameter
{
[Fact]
public void DoesNotCallOnValueWithNothing()
{
var maybe = Maybe<int>.Nothing;
maybe.Match(onValue: (val) => throw new XunitException("Wrong method called"));
}
[Fact]
public void CallsOnValueWithValueOnJust()
{
var maybe = Maybe.Just(100);
var isCalled = false;
maybe.Match(
onValue: (val) =>
{
val.Should().Be(100);
isCalled = true;
});
isCalled.Should().BeTrue("onValue should have been called");
}
}
public sealed class MatchWithTwoParameters
{
[Fact]
public void CallsOnNothingOnNothing()
{
var maybe = Maybe<int>.Nothing;
var isCalled = false;
maybe.Match(
onValue: (val) => throw new XunitException("Wrong method called"),
onNothing: () => isCalled = true);
isCalled.Should().BeTrue("onNothing should have been called");
}
[Fact]
public void CallsOnValueWithValueOnJust()
{
var maybe = Maybe.Just(100);
var isCalled = false;
maybe.Match(
onValue: (val) =>
{
val.Should().Be(100);
isCalled = true;
},
onNothing: () => throw new XunitException("Wrong method called"));
isCalled.Should().BeTrue("onValue should have been called");
}
}
public sealed class ReturningMatch
{
[Fact]
public void CallsOnNothingOnNothingAndReturnsItsValue()
{
var maybe = Maybe<int>.Nothing;
var expectedResult = "expected result";
var actualResult = maybe.Match(
onValue: (val) => throw new XunitException("Wrong method called"),
onNothing: () => expectedResult);
actualResult.Should().Be(expectedResult, "onNothing should have been called");
}
[Fact]
public void CallsOnValueWithValueOnJustAndReturnsItsValue()
{
var maybe = Maybe.Just(100);
var expectedResult = "expected result";
var actualResult = maybe.Match(
onValue: (val) =>
{
val.Should().Be(100);
return expectedResult;
},
onNothing: () => throw new XunitException("Wrong method called"));
actualResult.Should().Be(expectedResult, "onValue should have been called");
}
}
public sealed class FromNullable
{
[Fact]
public void ReturnsNothingOnReferenceTypeNull()
{
Maybe.FromNullable((string?) null).Should().Be(Maybe<string>.Nothing);
}
[Fact]
public void ReturnsJustOnReferenceTypeSet()
{
Maybe.FromNullable("the game").Should().Be(Maybe.Just("the game"));
}
[Fact]
public void ReturnsNothingOnNullableNoValue()
{
Maybe.FromNullable((int?) null).Should().Be(Maybe<int>.Nothing);
}
[Fact]
public void ReturnsJustOnNullableWithValue()
{
Maybe.FromNullable((int?) 10).Should().Be(Maybe.Just(10));
}
}
}
| |
using System;
using OpenTK;
using UIKit;
using OpenTK.Graphics.ES20;
namespace PerVertexDirectionalLighting
{
public class GLViewController : UIViewController
{
GLProgram program;
GLTexture texture;
float rot = 0f;
int positionAttribute,
textureCoordinateAttribute,
normalsAttribute,
matrixUniform,
textureUniform,
lightDirectionUniform,
lightDiffuseColorUniform;
float[] rotationMatrix = new float[16],
translationMatrix = new float[16],
modelViewMatrix = new float[16],
projectionMatrix = new float[16],
matrix = new float[16];
public GLViewController ()
{
}
public void Setup ()
{
program = new GLProgram ("Shader", "Shader");
program.AddAttribute ("position");
program.AddAttribute ("textureCoordinate");
program.AddAttribute ("normalsAttribute");
if (!program.Link ()) {
Console.WriteLine ("Link failed.");
Console.WriteLine (String.Format ("Program Log: {0}", program.ProgramLog ()));
Console.WriteLine (String.Format ("Fragment Log: {0}", program.FragmentShaderLog ()));
Console.WriteLine (String.Format ("Vertex Log: {0}", program.VertexShaderLog ()));
(View as GLView).StopAnimation ();
program = null;
return;
}
positionAttribute = program.GetAttributeIndex ("position");
textureCoordinateAttribute = program.GetAttributeIndex ("textureCoordinate");
normalsAttribute = program.GetAttributeIndex ("normalsAttribute");
matrixUniform = program.GetUniformIndex ("matrix");
textureUniform = program.GetUniformIndex ("texture");
lightDirectionUniform = program.GetUniformIndex ("lightDirection");
lightDiffuseColorUniform = program.GetUniformIndex ("lightDiffuseColor");
GL.Enable (EnableCap.DepthTest);
GL.Enable (EnableCap.CullFace);
GL.Enable (EnableCap.Texture2D);
GL.Enable (EnableCap.Blend);
GL.BlendFunc (BlendingFactorSrc.One, BlendingFactorDest.Zero);
texture = new GLTexture ("DieTexture.png");
}
public void Draw ()
{
Vector3[] vertices = {
new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f},
new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f},
new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f},
new Vector3 { X = 0.723600f, Y = 0.525720f, Z = -0.447215f},
new Vector3 { X = -0.894425f, Y = 0.000000f, Z = -0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f},
new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f},
new Vector3 { X = -0.276385f, Y = 0.850640f, Z = -0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f},
new Vector3 { X = -0.894425f, Y = 0.000000f, Z = -0.447215f},
new Vector3 { X = 0.723600f, Y = 0.525720f, Z = -0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f},
new Vector3 { X = -0.276385f, Y = 0.850640f, Z = -0.447215f},
new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f},
new Vector3 { X = 0.723600f, Y = 0.525720f, Z = -0.447215f},
new Vector3 { X = 0.894425f, Y = 0.000000f, Z = 0.447215f},
new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f},
new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f},
new Vector3 { X = 0.276385f, Y = -0.850640f, Z = 0.447215f},
new Vector3 { X = -0.894425f, Y = 0.000000f, Z = -0.447215f},
new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f},
new Vector3 { X = -0.723600f, Y = -0.525720f, Z = 0.447215f},
new Vector3 { X = -0.276385f, Y = 0.850640f, Z = -0.447215f},
new Vector3 { X = -0.894425f, Y = 0.000000f, Z = -0.447215f},
new Vector3 { X = -0.723600f, Y = 0.525720f, Z = 0.447215f},
new Vector3 { X = 0.723600f, Y = 0.525720f, Z = -0.447215f},
new Vector3 { X = -0.276385f, Y = 0.850640f, Z = -0.447215f},
new Vector3 { X = 0.276385f, Y = 0.850640f, Z = 0.447215f},
new Vector3 { X = 0.894425f, Y = 0.000000f, Z = 0.447215f},
new Vector3 { X = 0.276385f, Y = -0.850640f, Z = 0.447215f},
new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f},
new Vector3 { X = 0.276385f, Y = -0.850640f, Z = 0.447215f},
new Vector3 { X = -0.723600f, Y = -0.525720f, Z = 0.447215f},
new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f},
new Vector3 { X = -0.723600f, Y = -0.525720f, Z = 0.447215f},
new Vector3 { X = -0.723600f, Y = 0.525720f, Z = 0.447215f},
new Vector3 { X = -0.894425f, Y = 0.000000f, Z = -0.447215f},
new Vector3 { X = -0.723600f, Y = 0.525720f, Z = 0.447215f},
new Vector3 { X = 0.276385f, Y = 0.850640f, Z = 0.447215f},
new Vector3 { X = -0.276385f, Y = 0.850640f, Z = -0.447215f},
new Vector3 { X = 0.276385f, Y = 0.850640f, Z = 0.447215f},
new Vector3 { X = 0.894425f, Y = 0.000000f, Z = 0.447215f},
new Vector3 { X = 0.723600f, Y = 0.525720f, Z = -0.447215f},
new Vector3 { X = 0.276385f, Y = -0.850640f, Z = 0.447215f},
new Vector3 { X = 0.894425f, Y = 0.000000f, Z = 0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f},
new Vector3 { X = -0.723600f, Y = -0.525720f, Z = 0.447215f},
new Vector3 { X = 0.276385f, Y = -0.850640f, Z = 0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f},
new Vector3 { X = -0.723600f, Y = 0.525720f, Z = 0.447215f},
new Vector3 { X = -0.723600f, Y = -0.525720f, Z = 0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f},
new Vector3 { X = 0.276385f, Y = 0.850640f, Z = 0.447215f},
new Vector3 { X = -0.723600f, Y = 0.525720f, Z = 0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f},
new Vector3 { X = 0.894425f, Y = 0.000000f, Z = 0.447215f},
new Vector3 { X = 0.276385f, Y = 0.850640f, Z = 0.447215f},
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f},
};
TextureCoord[] textureCoordinates = {
new TextureCoord { S = .648752f, T = 0.445995f},
new TextureCoord { S = 0.914415f, T = 0.532311f},
new TextureCoord { S = 0.722181f, T = 0.671980f},
new TextureCoord { S = 0.722181f, T = 0.671980f},
new TextureCoord { S = 0.914415f, T = 0.532311f},
new TextureCoord { S = 0.914415f, T = 0.811645f},
new TextureCoord { S = 0.254949f, T = 0.204901f},
new TextureCoord { S = 0.254949f, T = 0.442518f},
new TextureCoord { S = 0.028963f, T = 0.278329f},
new TextureCoord { S = 0.480936f, T = 0.278329f},
new TextureCoord { S = 0.254949f, T = 0.442518f},
new TextureCoord { S = 0.254949f, T = 0.204901f},
new TextureCoord { S = 0.838115f, T = 0.247091f},
new TextureCoord { S = 0.713611f, T = 0.462739f},
new TextureCoord { S = 0.589108f, T = 0.247091f},
new TextureCoord { S = 0.722181f, T = 0.671980f},
new TextureCoord { S = 0.914415f, T = 0.811645f},
new TextureCoord { S = 0.648752f, T = 0.897968f},
new TextureCoord { S = 0.648752f, T = 0.445995f},
new TextureCoord { S = 0.722181f, T = 0.671980f},
new TextureCoord { S = 0.484562f, T = 0.671981f},
new TextureCoord { S = 0.254949f, T = 0.204901f},
new TextureCoord { S = 0.028963f, T = 0.278329f},
new TextureCoord { S = 0.115283f, T = 0.012663f},
new TextureCoord { S = 0.480936f, T = 0.278329f},
new TextureCoord { S = 0.254949f, T = 0.204901f},
new TextureCoord { S = 0.394615f, T = 0.012663f},
new TextureCoord { S = 0.838115f, T = 0.247091f},
new TextureCoord { S = 0.589108f, T = 0.247091f},
new TextureCoord { S = 0.713609f, T = 0.031441f},
new TextureCoord { S = 0.648752f, T = 0.897968f},
new TextureCoord { S = 0.484562f, T = 0.671981f},
new TextureCoord { S = 0.722181f, T = 0.671980f},
new TextureCoord { S = 0.644386f, T = 0.947134f},
new TextureCoord { S = 0.396380f, T = 0.969437f},
new TextureCoord { S = 0.501069f, T = 0.743502f},
new TextureCoord { S = 0.115283f, T = 0.012663f},
new TextureCoord { S = 0.394615f, T = 0.012663f},
new TextureCoord { S = 0.254949f, T = 0.204901f},
new TextureCoord { S = 0.464602f, T = 0.031442f},
new TextureCoord { S = 0.713609f, T = 0.031441f},
new TextureCoord { S = 0.589108f, T = 0.247091f},
new TextureCoord { S = 0.713609f, T = 0.031441f},
new TextureCoord { S = 0.962618f, T = 0.031441f},
new TextureCoord { S = 0.838115f, T = 0.247091f},
new TextureCoord { S = 0.028963f, T = 0.613069f},
new TextureCoord { S = 0.254949f, T = 0.448877f},
new TextureCoord { S = 0.254949f, T = 0.686495f},
new TextureCoord { S = 0.115283f, T = 0.878730f},
new TextureCoord { S = 0.028963f, T = 0.613069f},
new TextureCoord { S = 0.254949f, T = 0.686495f},
new TextureCoord { S = 0.394615f, T = 0.878730f},
new TextureCoord { S = 0.115283f, T = 0.878730f},
new TextureCoord { S = 0.254949f, T = 0.686495f},
new TextureCoord { S = 0.480935f, T = 0.613069f},
new TextureCoord { S = 0.394615f, T = 0.878730f},
new TextureCoord { S = 0.254949f, T = 0.686495f},
new TextureCoord { S = 0.254949f, T = 0.448877f},
new TextureCoord { S = 0.480935f, T = 0.613069f},
new TextureCoord { S = 0.254949f, T = 0.686495f},
};
Vector3[] normals = {
new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f },
new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f },
new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f },
new Vector3 { X = 0.723594f, Y = 0.525712f, Z = -0.447188f },
new Vector3 { X = -0.894406f, Y = 0.000000f, Z = -0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f },
new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f },
new Vector3 { X = -0.276376f, Y = 0.850642f, Z = -0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f },
new Vector3 { X = -0.894406f, Y = 0.000000f, Z = -0.447188f },
new Vector3 { X = 0.723594f, Y = 0.525712f, Z = -0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f },
new Vector3 { X = -0.276376f, Y = 0.850642f, Z = -0.447188f },
new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f },
new Vector3 { X = 0.723594f, Y = 0.525712f, Z = -0.447188f },
new Vector3 { X = 0.894406f, Y = 0.000000f, Z = 0.447188f },
new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f },
new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f },
new Vector3 { X = 0.276376f, Y = -0.850642f, Z = 0.447188f },
new Vector3 { X = -0.894406f, Y = 0.000000f, Z = -0.447188f },
new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f },
new Vector3 { X = -0.723594f, Y = -0.525712f, Z = 0.447188f },
new Vector3 { X = -0.276376f, Y = 0.850642f, Z = -0.447188f },
new Vector3 { X = -0.894406f, Y = 0.000000f, Z = -0.447188f },
new Vector3 { X = -0.723594f, Y = 0.525712f, Z = 0.447188f },
new Vector3 { X = 0.723594f, Y = 0.525712f, Z = -0.447188f },
new Vector3 { X = -0.276376f, Y = 0.850642f, Z = -0.447188f },
new Vector3 { X = 0.276376f, Y = 0.850642f, Z = 0.447188f },
new Vector3 { X = 0.894406f, Y = 0.000000f, Z = 0.447188f },
new Vector3 { X = 0.276376f, Y = -0.850642f, Z = 0.447188f },
new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f },
new Vector3 { X = 0.276376f, Y = -0.850642f, Z = 0.447188f },
new Vector3 { X = -0.723594f, Y = -0.525712f, Z = 0.447188f },
new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f },
new Vector3 { X = -0.723594f, Y = -0.525712f, Z = 0.447188f },
new Vector3 { X = -0.723594f, Y = 0.525712f, Z = 0.447188f },
new Vector3 { X = -0.894406f, Y = 0.000000f, Z = -0.447188f },
new Vector3 { X = -0.723594f, Y = 0.525712f, Z = 0.447188f },
new Vector3 { X = 0.276376f, Y = 0.850642f, Z = 0.447188f },
new Vector3 { X = -0.276376f, Y = 0.850642f, Z = -0.447188f },
new Vector3 { X = 0.276376f, Y = 0.850642f, Z = 0.447188f },
new Vector3 { X = 0.894406f, Y = 0.000000f, Z = 0.447188f },
new Vector3 { X = 0.723594f, Y = 0.525712f, Z = -0.447188f },
new Vector3 { X = 0.276376f, Y = -0.850642f, Z = 0.447188f },
new Vector3 { X = 0.894406f, Y = 0.000000f, Z = 0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f },
new Vector3 { X = -0.723594f, Y = -0.525712f, Z = 0.447188f },
new Vector3 { X = 0.276376f, Y = -0.850642f, Z = 0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f },
new Vector3 { X = -0.723594f, Y = 0.525712f, Z = 0.447188f },
new Vector3 { X = -0.723594f, Y = -0.525712f, Z = 0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f },
new Vector3 { X = 0.276376f, Y = 0.850642f, Z = 0.447188f },
new Vector3 { X = -0.723594f, Y = 0.525712f, Z = 0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f },
new Vector3 { X = 0.894406f, Y = 0.000000f, Z = 0.447188f },
new Vector3 { X = 0.276376f, Y = 0.850642f, Z = 0.447188f },
new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f },
};
GL.ClearColor (0f, 0f, 0f, 1f);
GL.Clear (ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
if (program != null)
program.Use ();
GL.VertexAttribPointer (positionAttribute, 3, VertexAttribPointerType.Float, false, 0, vertices);
GL.EnableVertexAttribArray (positionAttribute);
GL.VertexAttribPointer (textureCoordinateAttribute, 2, VertexAttribPointerType.Float, false, 0, textureCoordinates);
GL.EnableVertexAttribArray (textureCoordinateAttribute);
GL.VertexAttribPointer (normalsAttribute, 2, VertexAttribPointerType.Float, false, 0, normals);
GL.EnableVertexAttribArray (normalsAttribute);
Vector3 rotationVector = new Vector3 (1.0f, 1.0f, 1.0f);
GLCommon.Matrix3DSetRotationByDegrees (ref rotationMatrix, rot, rotationVector);
GLCommon.Matrix3DSetTranslation (ref translationMatrix, 0.0f, 0.0f, -3.0f);
modelViewMatrix = GLCommon.Matrix3DMultiply (translationMatrix, rotationMatrix);
GLCommon.Matrix3DSetPerspectiveProjectionWithFieldOfView (ref projectionMatrix, 45.0f, 0.1f, 100.0f,
(float)(View.Frame.Size.Width / View.Frame.Size.Height));
matrix = GLCommon.Matrix3DMultiply (projectionMatrix, modelViewMatrix);
GL.UniformMatrix4 (matrixUniform, 1, false, matrix);
GL.ActiveTexture (TextureUnit.Texture0);
if (texture != null)
texture.Use ();
GL.Uniform1 (textureUniform, 0);
GL.Uniform4 (lightDirectionUniform, 1.0f, 0.75f, 0.25f, 1.0f);
GL.Uniform4 (lightDiffuseColorUniform, 0.8f, 0.8f, 1.0f, 1.0f);
GL.DrawArrays (BeginMode.Triangles, 0, vertices.Length);
rot += 2.0f;
if (rot > 360.0f)
rot -= 360.0f;
}
public override void LoadView ()
{
GLView view = new GLView ();
view.Controller = this;
View = view;
}
}
}
| |
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
// @todo UWP: this file is a work in progress and is not yet complete for the F5 scenario for UWP
namespace UnrealBuildTool
{
/**
* Base class for platform-specific project generators
*/
public class UWPProjectGenerator : UEPlatformProjectGenerator
{
/**
* Register the platform with the UEPlatformProjectGenerator class
*/
public override void RegisterPlatformProjectGenerator()
{
if( UWPPlatform.bEnableUWPSupport )
{
// Register this project generator for UWP
Log.TraceVerbose(" Registering for {0}", UnrealTargetPlatform.UWP.ToString());
UEPlatformProjectGenerator.RegisterPlatformProjectGenerator(UnrealTargetPlatform.UWP, this);
}
}
public static void GetTargetUWPPaths(string InTargetName, TargetRules InTargetRules,
out string OutEngineSourceRelativeBinaryPath, out string OutRelativeTargetPath)
{
OutEngineSourceRelativeBinaryPath = "";
OutRelativeTargetPath = "";
string TargetFilename = RulesCompiler.GetTargetFilename(InTargetName);
string ProjectSourceFolder = new FileInfo(TargetFilename).DirectoryName;
string EnginePath = Path.Combine(ProjectFileGenerator.EngineRelativePath);
string EngineSourcePath = Path.Combine(EnginePath, "Source");
string RelativeTargetFilename = Utils.MakePathRelativeTo(TargetFilename, EngineSourcePath);
if ((RelativeTargetFilename.StartsWith("..") == false) && (RelativeTargetFilename.Contains(":") == false))
{
// This target must be UNDER Engine/Source...
RelativeTargetFilename = Path.Combine(EngineSourcePath, RelativeTargetFilename);
}
RelativeTargetFilename = RelativeTargetFilename.Replace("\\", "/");
EnginePath = EnginePath.Replace("\\", "/");
Int32 LastSourceIdx = RelativeTargetFilename.LastIndexOf("Source");
if (LastSourceIdx != -1)
{
RelativeTargetFilename = RelativeTargetFilename.Substring(0, LastSourceIdx);
}
else
{
RelativeTargetFilename = "";
}
OutRelativeTargetPath = RelativeTargetFilename;
if (InTargetRules.bOutputToEngineBinaries)
{
RelativeTargetFilename = EnginePath;
}
OutEngineSourceRelativeBinaryPath = Path.Combine(RelativeTargetFilename, "Binaries/UWP/");
OutEngineSourceRelativeBinaryPath = OutEngineSourceRelativeBinaryPath.Replace("\\", "/");
}
///
/// VisualStudio project generation functions
///
/**
* Whether this build platform has native support for VisualStudio
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return bool true if native VisualStudio support (or custom VSI) is available
*/
public override bool HasVisualStudioSupport(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
return false;
}
/**
* Get whether this platform deploys
*
* @return bool true if the 'Deploy' option should be enabled
*/
public override bool GetVisualStudioDeploymentEnabled(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
return true;
}
private Dictionary<string, string> GameToBuildFolder = new Dictionary<string, string>();
protected void GeneratePackageAppXManifest(string InGameName, bool bIsUE4Game, string InManifestType, string InGameBinaries, string InGameIntermediates, string InOutputPath)
{
string BuildFolder = Path.Combine(InOutputPath, "../../Build/UWP");
string CheckPath;
if (GameToBuildFolder.TryGetValue(InGameName, out CheckPath) == false)
{
GameToBuildFolder.Add(InGameName, BuildFolder);
}
string OutputPackageAppXManifestPath = Path.Combine(BuildFolder, InManifestType + ".AppxManifest");
// first look for a per-game template
string PackageAppXManifestPath = OutputPackageAppXManifestPath + ".template";
if (!File.Exists(PackageAppXManifestPath))
{
// then fallback to shared template
PackageAppXManifestPath = "../../Engine/Build/UWP/Templates/" + InManifestType + ".appxmanifest.template";
}
GenerateFileFromTemplate(PackageAppXManifestPath, OutputPackageAppXManifestPath, bIsUE4Game, InGameName, "", InGameBinaries, InGameIntermediates);
// Generate the package name...
// todo - richiem - this is next to fix
string PackageName = "foobar"; //= XboxOneDeploy.XboxOnePackageNameHelper_Run(OutputPackageAppXManifestPath);
if (string.IsNullOrEmpty(PackageName) == false)
{
if (GameToBuildFolder.TryGetValue(InGameName, out CheckPath) == false)
{
GameToBuildFolder.Add(InGameName, PackageName);
}
}
else
{
throw new BuildException("Error: Failed to find package name for {0}", OutputPackageAppXManifestPath);
}
}
protected void GeneratePackagePriConfig(string InGameName, bool bIsUE4Game, string InGameBinaries, string InGameIntermediates, string InOutputPath)
{
string BuildFolder = Path.Combine(InOutputPath, "../../Build/UWP");
string OutputPackagePriConfigPath = Path.Combine(BuildFolder, "Package.PriConfig");
// first look for a per-game template
string PackagePriConfigPath = OutputPackagePriConfigPath + ".template";
if (!File.Exists(PackagePriConfigPath))
{
// then fallback to shared template
PackagePriConfigPath = "../../Engine/Build/UWP/Templates/Package.priconfig.template";
}
GenerateFileFromTemplate(PackagePriConfigPath, OutputPackagePriConfigPath, bIsUE4Game, InGameName, "", InGameBinaries, InGameIntermediates);
}
protected void GeneratePackageResources(string InGameName, bool bIsUE4Game, string InGameBinaries, string InGameIntermediates, string InOutputPath)
{
string BuildFolder = Path.Combine(InOutputPath, "../../Build/UWP");
string OutputPackageResourcesPath = Path.Combine(BuildFolder, "Resources", "Resources.resw");
// first look for a per-game template
string PackageResourcesPath = Path.Combine(BuildFolder, "Resources", "Package.resources.template");
if (!File.Exists(PackageResourcesPath))
{
// then fallback to shared template
PackageResourcesPath = "../../Engine/Build/UWP/Templates/Package.resources.template";
}
// Only generate the example language if the resources haven't been setup at all previously
if (!File.Exists(OutputPackageResourcesPath))
{
GenerateFileFromTemplate(PackageResourcesPath, Path.Combine(BuildFolder, "Resources", "en-US", "Resources.resw"), bIsUE4Game, InGameName, "", InGameBinaries, InGameIntermediates);
}
GenerateFileFromTemplate(PackageResourcesPath, OutputPackageResourcesPath, bIsUE4Game, InGameName, "", InGameBinaries, InGameIntermediates);
}
protected void GenerateFileFromTemplate(string InTemplateFile, string InOutputFile, bool bIsUE4Game, string InGameName, string InGameConfiguration, string InGameBinaries, string InGameIntermediates, string InGuidString = "", Dictionary<string, string> InExtraReplacements = null)
{
String ExecutableName = bIsUE4Game ? "UE4Game" : InGameName;
StringBuilder outputContents = new StringBuilder();
using (StreamReader reader = new StreamReader(InTemplateFile))
{
string LineStr = null;
while (reader.Peek() != -1)
{
LineStr = reader.ReadLine();
if (LineStr.Contains("%GAME%"))
{
if (LineStr.Contains("Executable") || LineStr.Contains("EntryPoint"))
{
LineStr = LineStr.Replace("%GAME%", ExecutableName);
}
else
{
LineStr = LineStr.Replace("%GAME%", InGameName);
}
}
if (LineStr.Contains("%PROJECT%"))
{
if (bIsUE4Game)
{
LineStr = LineStr.Replace("%PROJECT%", "Engine");
}
else
{
LineStr = LineStr.Replace("%PROJECT%", InGameName);
}
}
if (LineStr.Contains("%CONFIG%"))
{
LineStr = LineStr.Replace("%CONFIG%", InGameConfiguration);
}
if (LineStr.Contains("%DISPLAYCONFIG%"))
{
if (string.IsNullOrEmpty(InGameConfiguration))
{
LineStr = LineStr.Replace("%DISPLAYCONFIG%", "");
}
else
{
LineStr = LineStr.Replace("%DISPLAYCONFIG%", " (" + InGameConfiguration + ")");
}
}
if (LineStr.Contains("%GAMEBINARIES%"))
{
LineStr = LineStr.Replace("%GAMEBINARIES%", InGameBinaries);
}
if (LineStr.Contains("%GAMEBINARIESFOLDER%"))
{
LineStr = LineStr.Replace("%GAMEBINARIESFOLDER%", InGameBinaries);
}
if (LineStr.Contains("%GAMEINTERMEDIATESFOLDER%"))
{
LineStr = LineStr.Replace("%GAMEINTERMEDIATESFOLDER%", InGameIntermediates);
}
if (LineStr.Contains("%GUID%"))
{
LineStr = LineStr.Replace("%GUID%", InGuidString);
}
if (InExtraReplacements != null)
{
foreach (KeyValuePair<string, string> Replacement in InExtraReplacements)
{
if (LineStr.Contains(Replacement.Key))
{
LineStr = LineStr.Replace(Replacement.Key, Replacement.Value);
}
}
}
outputContents.AppendLine(LineStr);
}
}
if (outputContents.Length > 0)
{
bool bFileNeedsSave = true;
if (File.Exists(InOutputFile))
{
// Read in the original file completely
string LoadedFileContent = null;
var FileAlreadyExists = File.Exists(InOutputFile);
if (FileAlreadyExists)
{
try
{
LoadedFileContent = File.ReadAllText(InOutputFile);
}
catch (Exception)
{
Log.TraceInformation("Error while trying to load existing file {0}. Ignored.", InOutputFile);
}
}
// Don't bother saving anything out if the new file content is the same as the old file's content
if (LoadedFileContent != null)
{
var bIgnoreProjectFileWhitespaces = true;
if (ProjectFileComparer.CompareOrdinalIgnoreCase(LoadedFileContent, outputContents.ToString(), bIgnoreProjectFileWhitespaces) == 0)
{
// Exact match!
bFileNeedsSave = false;
}
if (!bFileNeedsSave)
{
Log.TraceVerbose("Skipped saving {0} because contents haven't changed.", Path.GetFileName(InOutputFile));
}
}
}
if (bFileNeedsSave)
{
// Save the file
try
{
Directory.CreateDirectory(Path.GetDirectoryName(InOutputFile));
File.WriteAllText(InOutputFile, outputContents.ToString(), Encoding.UTF8);
Log.TraceVerbose("Saved {0}", Path.GetFileName(InOutputFile));
}
catch (Exception)
{
// Unable to write to the project file.
Log.TraceInformation("Error while trying to write file {0}. The file is probably read-only.", InOutputFile);
}
}
}
}
protected void CopyDefaultImageFiles(string InOutputPath)
{
string OutputImageFolder = Path.Combine(InOutputPath, "../../Build/UWP/Resources");
if (Directory.Exists(OutputImageFolder) == false)
{
Directory.CreateDirectory(OutputImageFolder);
}
string[] ImageList = new string[] { "Logo.png", "SmallLogo.png", "SplashScreen.png", "StoreLogo.png", "WideLogo.png" };
foreach (string ImageName in ImageList)
{
string OutputImageFilePath = Path.Combine(OutputImageFolder, ImageName);
if (File.Exists(OutputImageFilePath) == false)
{
string SourceImagePath = "../../Engine/Build/UWP/DefaultImages/" + ImageName;
File.Copy(SourceImagePath, OutputImageFilePath);
string OutputEnglishImageFilePath = Path.Combine(OutputImageFolder, "en-US", ImageName);
if (Directory.Exists(OutputImageFolder + "/en-US") == false)
{
Directory.CreateDirectory(OutputImageFolder + "/en-US");
}
if (File.Exists(OutputEnglishImageFilePath) == false)
{
File.Copy(SourceImagePath, OutputEnglishImageFilePath);
}
}
}
}
public void GenerateDeployFiles(string InTargetName, string InTargetFilepath, bool bIsUE4Game, string EngineSourceRelativeBinaryPath)
{
const string SourceFolderString = "/Source/";
string OutTargetPath = InTargetFilepath;
OutTargetPath = OutTargetPath.Replace("\\", "/");
if (bIsUE4Game == false)
{
int LastSourceIndex = OutTargetPath.LastIndexOf(SourceFolderString);
if (LastSourceIndex != -1)
{
OutTargetPath = OutTargetPath.Substring(0, LastSourceIndex + SourceFolderString.Length);
OutTargetPath = Path.Combine(OutTargetPath, "UWP");
}
else
{
// @todo UWP: This is bad... throw a build exception?
}
}
else
{
OutTargetPath = Path.Combine((new FileInfo(InTargetFilepath)).DirectoryName, "UWP");
}
string GameBinariesFolder = Utils.MakePathRelativeTo(EngineSourceRelativeBinaryPath, OutTargetPath);
GameBinariesFolder = GameBinariesFolder.Replace("\\", "/");
if (GameBinariesFolder.EndsWith("/") == false)
{
GameBinariesFolder += "/";
}
string GameIntermediatesFolder = GameBinariesFolder.Replace("Binaries/WinAUP", "Intermediate/Build/Unused");
// Make sure the output directory exists...
if (Directory.Exists(OutTargetPath) == false)
{
Log.TraceVerbose("Generating output directory " + OutTargetPath);
Directory.CreateDirectory(OutTargetPath);
}
GeneratePackageAppXManifest(InTargetName, bIsUE4Game, "Package", GameBinariesFolder, GameIntermediatesFolder, OutTargetPath);
GeneratePackageAppXManifest(InTargetName, bIsUE4Game, "Deploy", GameBinariesFolder, GameIntermediatesFolder, OutTargetPath);
GeneratePackagePriConfig(InTargetName, bIsUE4Game, GameBinariesFolder, GameIntermediatesFolder, OutTargetPath);
GeneratePackageResources(InTargetName, bIsUE4Game, GameBinariesFolder, GameIntermediatesFolder, OutTargetPath);
CopyDefaultImageFiles(OutTargetPath);
}
public override void GenerateGameProperties(UnrealTargetConfiguration Configuration, StringBuilder VCProjectFileContent, TargetRules.TargetType TargetType, string RootDirectory, string TargetFilePath)
{
// @todo UWP: This used to be "WINUAP=1". Need to verify that 'UWP' is the correct define that we want here.
VCProjectFileContent.Append(" <NMakePreprocessorDefinitions>$(NMakePreprocessorDefinitions);PLATFORM_UWP=1;UWP=1;</NMakePreprocessorDefinitions>" + ProjectFileGenerator.NewLine);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using CALI.Database.Contracts;
using CALI.Database.Contracts.Data;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace CALI.Database.Logic.Data
{
[Serializable]
public abstract partial class QueryLogicBase : LogicBase<QueryLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<QueryContract> Results;
public QueryLogicBase()
{
Results = new List<QueryContract>();
}
/// <summary>
/// Run Query_Insert.
/// </summary>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <param name="fldIsSuccess">Value for IsSuccess</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
, bool fldIsSuccess
)
{
int? result = null;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
,
new SqlParameter("@IsSuccess", fldIsSuccess)
});
result = (int?)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Run Query_Insert.
/// </summary>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <param name="fldIsSuccess">Value for IsSuccess</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
, bool fldIsSuccess
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Query_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
,
new SqlParameter("@IsSuccess", fldIsSuccess)
});
return (int?)cmd.ExecuteScalar();
}
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(QueryContract row)
{
int? result = null;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", row.Text)
,
new SqlParameter("@PoviderSource", row.PoviderSource)
,
new SqlParameter("@ProcessorUsed", row.ProcessorUsed)
,
new SqlParameter("@Exceptions", row.Exceptions)
,
new SqlParameter("@IsSuccess", row.IsSuccess)
});
result = (int?)cmd.ExecuteScalar();
row.QueryId = result;
}
});
return result != null ? 1 : 0;
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(QueryContract row, SqlConnection connection, SqlTransaction transaction)
{
int? result = null;
using (
var cmd = new SqlCommand("[Data].[Query_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", row.Text)
,
new SqlParameter("@PoviderSource", row.PoviderSource)
,
new SqlParameter("@ProcessorUsed", row.ProcessorUsed)
,
new SqlParameter("@Exceptions", row.Exceptions)
,
new SqlParameter("@IsSuccess", row.IsSuccess)
});
result = (int?)cmd.ExecuteScalar();
row.QueryId = result;
}
return result != null ? 1 : 0;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<QueryContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = InsertAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Insert(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Query_Update.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldQueryId">Value for QueryId</param>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <param name="fldIsSuccess">Value for IsSuccess</param>
public virtual int Update(int fldQueryId
, string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
, bool fldIsSuccess
)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
,
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
,
new SqlParameter("@IsSuccess", fldIsSuccess)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Query_Update.
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <param name="fldIsSuccess">Value for IsSuccess</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(int fldQueryId
, string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
, bool fldIsSuccess
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Query_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
,
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
,
new SqlParameter("@IsSuccess", fldIsSuccess)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(QueryContract row)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", row.QueryId)
,
new SqlParameter("@Text", row.Text)
,
new SqlParameter("@PoviderSource", row.PoviderSource)
,
new SqlParameter("@ProcessorUsed", row.ProcessorUsed)
,
new SqlParameter("@Exceptions", row.Exceptions)
,
new SqlParameter("@IsSuccess", row.IsSuccess)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(QueryContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Query_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", row.QueryId)
,
new SqlParameter("@Text", row.Text)
,
new SqlParameter("@PoviderSource", row.PoviderSource)
,
new SqlParameter("@ProcessorUsed", row.ProcessorUsed)
,
new SqlParameter("@Exceptions", row.Exceptions)
,
new SqlParameter("@IsSuccess", row.IsSuccess)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<QueryContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = UpdateAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Update(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Query_Delete.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldQueryId">Value for QueryId</param>
public virtual int Delete(int fldQueryId
)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Query_Delete.
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(int fldQueryId
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Query_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(QueryContract row)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", row.QueryId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(QueryContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Query_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", row.QueryId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<QueryContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = DeleteAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Delete(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldQueryId
)
{
bool result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldQueryId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Query_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run Query_Search, and return results as a list of QueryRow.
/// </summary>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <returns>A collection of QueryRow.</returns>
public virtual bool Search(string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
)
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_Search]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Query_Search, and return results as a list of QueryRow.
/// </summary>
/// <param name="fldText">Value for Text</param>
/// <param name="fldPoviderSource">Value for PoviderSource</param>
/// <param name="fldProcessorUsed">Value for ProcessorUsed</param>
/// <param name="fldExceptions">Value for Exceptions</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of QueryRow.</returns>
public virtual bool Search(string fldText
, string fldPoviderSource
, string fldProcessorUsed
, string fldExceptions
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Query_Search]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@Text", fldText)
,
new SqlParameter("@PoviderSource", fldPoviderSource)
,
new SqlParameter("@ProcessorUsed", fldProcessorUsed)
,
new SqlParameter("@Exceptions", fldExceptions)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Query_SelectAll, and return results as a list of QueryRow.
/// </summary>
/// <returns>A collection of QueryRow.</returns>
public virtual bool SelectAll()
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Query_SelectAll, and return results as a list of QueryRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of QueryRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Query_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Query_SelectBy_QueryId, and return results as a list of QueryRow.
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <returns>A collection of QueryRow.</returns>
public virtual bool SelectBy_QueryId(int fldQueryId
)
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Query_SelectBy_QueryId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Query_SelectBy_QueryId, and return results as a list of QueryRow.
/// </summary>
/// <param name="fldQueryId">Value for QueryId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of QueryRow.</returns>
public virtual bool SelectBy_QueryId(int fldQueryId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Query_SelectBy_QueryId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@QueryId", fldQueryId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new QueryContract
{
QueryId = reader.GetInt32(0),
Text = reader.GetString(1),
PoviderSource = reader.IsDBNull(2) ? null : reader.GetString(2),
ProcessorUsed = reader.IsDBNull(3) ? null : reader.GetString(3),
Exceptions = reader.IsDBNull(4) ? null : reader.GetString(4),
IsSuccess = reader.GetBoolean(5),
});
return true;
}
return false;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(QueryContract row)
{
if(row == null) return 0;
if(row.QueryId != null) return Update(row);
return Insert(row);
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(QueryContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row == null) return 0;
if(row.QueryId != null) return Update(row, connection, transaction);
return Insert(row, connection, transaction);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<QueryContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
foreach(var row in rows) rowCount += Save(row, x, null);
});
return rowCount;
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<QueryContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Save(row, connection, transaction);
return rowCount;
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class ReceivingWorksheetLineItem : IEquatable<ReceivingWorksheetLineItem>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingWorksheetLineItem" /> class.
/// Initializes a new instance of the <see cref="ReceivingWorksheetLineItem" />class.
/// </summary>
/// <param name="ReceivingQty">ReceivingQty (required).</param>
/// <param name="UnitCode">UnitCode (required).</param>
/// <param name="WrapCode">WrapCode (required).</param>
/// <param name="UnitsPerWrap">UnitsPerWrap.</param>
/// <param name="UnitsPerCase">UnitsPerCase.</param>
/// <param name="CasesPerPallet">CasesPerPallet.</param>
/// <param name="WeightPerWrap">WeightPerWrap (required).</param>
/// <param name="WeightPerCase">WeightPerCase.</param>
/// <param name="ProductionLot">ProductionLot.</param>
/// <param name="ProductIdTag">ProductIdTag.</param>
/// <param name="RevisionDate">RevisionDate.</param>
/// <param name="Origin">Origin.</param>
/// <param name="CartonLength">CartonLength.</param>
/// <param name="CartonWidth">CartonWidth.</param>
/// <param name="CartonHeight">CartonHeight.</param>
/// <param name="PutAwayPlans">PutAwayPlans.</param>
/// <param name="Quantity">Quantity.</param>
/// <param name="CustomFields">CustomFields.</param>
public ReceivingWorksheetLineItem(int? ReceivingQty = null, string UnitCode = null, string WrapCode = null, int? UnitsPerWrap = null, int? UnitsPerCase = null, int? CasesPerPallet = null, double? WeightPerWrap = null, double? WeightPerCase = null, string ProductionLot = null, string ProductIdTag = null, string RevisionDate = null, string Origin = null, double? CartonLength = null, double? CartonWidth = null, double? CartonHeight = null, List<ReceivingWorksheetPutAwayPlan> PutAwayPlans = null, int? Quantity = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "ReceivingQty" is required (not null)
if (ReceivingQty == null)
{
throw new InvalidDataException("ReceivingQty is a required property for ReceivingWorksheetLineItem and cannot be null");
}
else
{
this.ReceivingQty = ReceivingQty;
}
// to ensure "UnitCode" is required (not null)
if (UnitCode == null)
{
throw new InvalidDataException("UnitCode is a required property for ReceivingWorksheetLineItem and cannot be null");
}
else
{
this.UnitCode = UnitCode;
}
// to ensure "WrapCode" is required (not null)
if (WrapCode == null)
{
throw new InvalidDataException("WrapCode is a required property for ReceivingWorksheetLineItem and cannot be null");
}
else
{
this.WrapCode = WrapCode;
}
// to ensure "WeightPerWrap" is required (not null)
if (WeightPerWrap == null)
{
throw new InvalidDataException("WeightPerWrap is a required property for ReceivingWorksheetLineItem and cannot be null");
}
else
{
this.WeightPerWrap = WeightPerWrap;
}
this.UnitsPerWrap = UnitsPerWrap;
this.UnitsPerCase = UnitsPerCase;
this.CasesPerPallet = CasesPerPallet;
this.WeightPerCase = WeightPerCase;
this.ProductionLot = ProductionLot;
this.ProductIdTag = ProductIdTag;
this.RevisionDate = RevisionDate;
this.Origin = Origin;
this.CartonLength = CartonLength;
this.CartonWidth = CartonWidth;
this.CartonHeight = CartonHeight;
this.PutAwayPlans = PutAwayPlans;
this.Quantity = Quantity;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { get; private set; }
/// <summary>
/// Gets or Sets Sku2
/// </summary>
[DataMember(Name="sku2", EmitDefaultValue=false)]
public string Sku2 { get; private set; }
/// <summary>
/// Gets or Sets FullDescription
/// </summary>
[DataMember(Name="fullDescription", EmitDefaultValue=false)]
public string FullDescription { get; private set; }
/// <summary>
/// Gets or Sets OrderedQty
/// </summary>
[DataMember(Name="orderedQty", EmitDefaultValue=false)]
public int? OrderedQty { get; private set; }
/// <summary>
/// Gets or Sets PrevReceivedQty
/// </summary>
[DataMember(Name="prevReceivedQty", EmitDefaultValue=false)]
public int? PrevReceivedQty { get; private set; }
/// <summary>
/// Gets or Sets UnreceivedQty
/// </summary>
[DataMember(Name="unreceivedQty", EmitDefaultValue=false)]
public int? UnreceivedQty { get; private set; }
/// <summary>
/// Gets or Sets ReceivingQty
/// </summary>
[DataMember(Name="receivingQty", EmitDefaultValue=false)]
public int? ReceivingQty { get; set; }
/// <summary>
/// Gets or Sets UnitCode
/// </summary>
[DataMember(Name="unitCode", EmitDefaultValue=false)]
public string UnitCode { get; set; }
/// <summary>
/// Gets or Sets WrapCode
/// </summary>
[DataMember(Name="wrapCode", EmitDefaultValue=false)]
public string WrapCode { get; set; }
/// <summary>
/// Gets or Sets UnitsPerWrap
/// </summary>
[DataMember(Name="unitsPerWrap", EmitDefaultValue=false)]
public int? UnitsPerWrap { get; set; }
/// <summary>
/// Gets or Sets UnitsPerCase
/// </summary>
[DataMember(Name="unitsPerCase", EmitDefaultValue=false)]
public int? UnitsPerCase { get; set; }
/// <summary>
/// Gets or Sets CasesPerPallet
/// </summary>
[DataMember(Name="casesPerPallet", EmitDefaultValue=false)]
public int? CasesPerPallet { get; set; }
/// <summary>
/// Gets or Sets WeightPerWrap
/// </summary>
[DataMember(Name="weightPerWrap", EmitDefaultValue=false)]
public double? WeightPerWrap { get; set; }
/// <summary>
/// Gets or Sets WeightPerCase
/// </summary>
[DataMember(Name="weightPerCase", EmitDefaultValue=false)]
public double? WeightPerCase { get; set; }
/// <summary>
/// Gets or Sets ProductionLot
/// </summary>
[DataMember(Name="productionLot", EmitDefaultValue=false)]
public string ProductionLot { get; set; }
/// <summary>
/// Gets or Sets ProductIdTag
/// </summary>
[DataMember(Name="productIdTag", EmitDefaultValue=false)]
public string ProductIdTag { get; set; }
/// <summary>
/// Gets or Sets RevisionDate
/// </summary>
[DataMember(Name="revisionDate", EmitDefaultValue=false)]
public string RevisionDate { get; set; }
/// <summary>
/// Gets or Sets Origin
/// </summary>
[DataMember(Name="origin", EmitDefaultValue=false)]
public string Origin { get; set; }
/// <summary>
/// Gets or Sets CartonLength
/// </summary>
[DataMember(Name="cartonLength", EmitDefaultValue=false)]
public double? CartonLength { get; set; }
/// <summary>
/// Gets or Sets CartonWidth
/// </summary>
[DataMember(Name="cartonWidth", EmitDefaultValue=false)]
public double? CartonWidth { get; set; }
/// <summary>
/// Gets or Sets CartonHeight
/// </summary>
[DataMember(Name="cartonHeight", EmitDefaultValue=false)]
public double? CartonHeight { get; set; }
/// <summary>
/// Gets or Sets PutAwayPlans
/// </summary>
[DataMember(Name="putAwayPlans", EmitDefaultValue=false)]
public List<ReceivingWorksheetPutAwayPlan> PutAwayPlans { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ReceivingWorksheetLineItem {\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append(" Sku2: ").Append(Sku2).Append("\n");
sb.Append(" FullDescription: ").Append(FullDescription).Append("\n");
sb.Append(" OrderedQty: ").Append(OrderedQty).Append("\n");
sb.Append(" PrevReceivedQty: ").Append(PrevReceivedQty).Append("\n");
sb.Append(" UnreceivedQty: ").Append(UnreceivedQty).Append("\n");
sb.Append(" ReceivingQty: ").Append(ReceivingQty).Append("\n");
sb.Append(" UnitCode: ").Append(UnitCode).Append("\n");
sb.Append(" WrapCode: ").Append(WrapCode).Append("\n");
sb.Append(" UnitsPerWrap: ").Append(UnitsPerWrap).Append("\n");
sb.Append(" UnitsPerCase: ").Append(UnitsPerCase).Append("\n");
sb.Append(" CasesPerPallet: ").Append(CasesPerPallet).Append("\n");
sb.Append(" WeightPerWrap: ").Append(WeightPerWrap).Append("\n");
sb.Append(" WeightPerCase: ").Append(WeightPerCase).Append("\n");
sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n");
sb.Append(" ProductIdTag: ").Append(ProductIdTag).Append("\n");
sb.Append(" RevisionDate: ").Append(RevisionDate).Append("\n");
sb.Append(" Origin: ").Append(Origin).Append("\n");
sb.Append(" CartonLength: ").Append(CartonLength).Append("\n");
sb.Append(" CartonWidth: ").Append(CartonWidth).Append("\n");
sb.Append(" CartonHeight: ").Append(CartonHeight).Append("\n");
sb.Append(" PutAwayPlans: ").Append(PutAwayPlans).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ReceivingWorksheetLineItem);
}
/// <summary>
/// Returns true if ReceivingWorksheetLineItem instances are equal
/// </summary>
/// <param name="other">Instance of ReceivingWorksheetLineItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReceivingWorksheetLineItem other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
) &&
(
this.Sku2 == other.Sku2 ||
this.Sku2 != null &&
this.Sku2.Equals(other.Sku2)
) &&
(
this.FullDescription == other.FullDescription ||
this.FullDescription != null &&
this.FullDescription.Equals(other.FullDescription)
) &&
(
this.OrderedQty == other.OrderedQty ||
this.OrderedQty != null &&
this.OrderedQty.Equals(other.OrderedQty)
) &&
(
this.PrevReceivedQty == other.PrevReceivedQty ||
this.PrevReceivedQty != null &&
this.PrevReceivedQty.Equals(other.PrevReceivedQty)
) &&
(
this.UnreceivedQty == other.UnreceivedQty ||
this.UnreceivedQty != null &&
this.UnreceivedQty.Equals(other.UnreceivedQty)
) &&
(
this.ReceivingQty == other.ReceivingQty ||
this.ReceivingQty != null &&
this.ReceivingQty.Equals(other.ReceivingQty)
) &&
(
this.UnitCode == other.UnitCode ||
this.UnitCode != null &&
this.UnitCode.Equals(other.UnitCode)
) &&
(
this.WrapCode == other.WrapCode ||
this.WrapCode != null &&
this.WrapCode.Equals(other.WrapCode)
) &&
(
this.UnitsPerWrap == other.UnitsPerWrap ||
this.UnitsPerWrap != null &&
this.UnitsPerWrap.Equals(other.UnitsPerWrap)
) &&
(
this.UnitsPerCase == other.UnitsPerCase ||
this.UnitsPerCase != null &&
this.UnitsPerCase.Equals(other.UnitsPerCase)
) &&
(
this.CasesPerPallet == other.CasesPerPallet ||
this.CasesPerPallet != null &&
this.CasesPerPallet.Equals(other.CasesPerPallet)
) &&
(
this.WeightPerWrap == other.WeightPerWrap ||
this.WeightPerWrap != null &&
this.WeightPerWrap.Equals(other.WeightPerWrap)
) &&
(
this.WeightPerCase == other.WeightPerCase ||
this.WeightPerCase != null &&
this.WeightPerCase.Equals(other.WeightPerCase)
) &&
(
this.ProductionLot == other.ProductionLot ||
this.ProductionLot != null &&
this.ProductionLot.Equals(other.ProductionLot)
) &&
(
this.ProductIdTag == other.ProductIdTag ||
this.ProductIdTag != null &&
this.ProductIdTag.Equals(other.ProductIdTag)
) &&
(
this.RevisionDate == other.RevisionDate ||
this.RevisionDate != null &&
this.RevisionDate.Equals(other.RevisionDate)
) &&
(
this.Origin == other.Origin ||
this.Origin != null &&
this.Origin.Equals(other.Origin)
) &&
(
this.CartonLength == other.CartonLength ||
this.CartonLength != null &&
this.CartonLength.Equals(other.CartonLength)
) &&
(
this.CartonWidth == other.CartonWidth ||
this.CartonWidth != null &&
this.CartonWidth.Equals(other.CartonWidth)
) &&
(
this.CartonHeight == other.CartonHeight ||
this.CartonHeight != null &&
this.CartonHeight.Equals(other.CartonHeight)
) &&
(
this.PutAwayPlans == other.PutAwayPlans ||
this.PutAwayPlans != null &&
this.PutAwayPlans.SequenceEqual(other.PutAwayPlans)
) &&
(
this.Quantity == other.Quantity ||
this.Quantity != null &&
this.Quantity.Equals(other.Quantity)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
if (this.Sku2 != null)
hash = hash * 59 + this.Sku2.GetHashCode();
if (this.FullDescription != null)
hash = hash * 59 + this.FullDescription.GetHashCode();
if (this.OrderedQty != null)
hash = hash * 59 + this.OrderedQty.GetHashCode();
if (this.PrevReceivedQty != null)
hash = hash * 59 + this.PrevReceivedQty.GetHashCode();
if (this.UnreceivedQty != null)
hash = hash * 59 + this.UnreceivedQty.GetHashCode();
if (this.ReceivingQty != null)
hash = hash * 59 + this.ReceivingQty.GetHashCode();
if (this.UnitCode != null)
hash = hash * 59 + this.UnitCode.GetHashCode();
if (this.WrapCode != null)
hash = hash * 59 + this.WrapCode.GetHashCode();
if (this.UnitsPerWrap != null)
hash = hash * 59 + this.UnitsPerWrap.GetHashCode();
if (this.UnitsPerCase != null)
hash = hash * 59 + this.UnitsPerCase.GetHashCode();
if (this.CasesPerPallet != null)
hash = hash * 59 + this.CasesPerPallet.GetHashCode();
if (this.WeightPerWrap != null)
hash = hash * 59 + this.WeightPerWrap.GetHashCode();
if (this.WeightPerCase != null)
hash = hash * 59 + this.WeightPerCase.GetHashCode();
if (this.ProductionLot != null)
hash = hash * 59 + this.ProductionLot.GetHashCode();
if (this.ProductIdTag != null)
hash = hash * 59 + this.ProductIdTag.GetHashCode();
if (this.RevisionDate != null)
hash = hash * 59 + this.RevisionDate.GetHashCode();
if (this.Origin != null)
hash = hash * 59 + this.Origin.GetHashCode();
if (this.CartonLength != null)
hash = hash * 59 + this.CartonLength.GetHashCode();
if (this.CartonWidth != null)
hash = hash * 59 + this.CartonWidth.GetHashCode();
if (this.CartonHeight != null)
hash = hash * 59 + this.CartonHeight.GetHashCode();
if (this.PutAwayPlans != null)
hash = hash * 59 + this.PutAwayPlans.GetHashCode();
if (this.Quantity != null)
hash = hash * 59 + this.Quantity.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudsearchdomain-2013-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.CloudSearchDomain.Model;
using Amazon.CloudSearchDomain.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudSearchDomain
{
/// <summary>
/// Implementation for accessing CloudSearchDomain
///
/// You use the AmazonCloudSearch2013 API to upload documents to a search domain and search
/// those documents.
///
///
/// <para>
/// The endpoints for submitting <code>UploadDocuments</code>, <code>Search</code>, and
/// <code>Suggest</code> requests are domain-specific. To get the endpoints for your domain,
/// use the Amazon CloudSearch configuration service <code>DescribeDomains</code> action.
/// The domain endpoints are also displayed on the domain dashboard in the Amazon CloudSearch
/// console. You submit suggest requests to the search endpoint.
/// </para>
///
/// <para>
/// For more information, see the <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide">Amazon
/// CloudSearch Developer Guide</a>.
/// </para>
/// </summary>
public partial class AmazonCloudSearchDomainClient : AmazonServiceClient, IAmazonCloudSearchDomain
{
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Customize the pipeline
/// </summary>
/// <param name="pipeline"></param>
protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline)
{
pipeline.AddHandlerBefore<Amazon.Runtime.Internal.Marshaller>(new Amazon.CloudSearchDomain.Internal.ProcessRequestHandler());
pipeline.AddHandlerBefore<Amazon.Runtime.Internal.Unmarshaller>(new Amazon.CloudSearchDomain.Internal.ValidationResponseHandler());
pipeline.AddHandlerBefore<Amazon.Runtime.Internal.Unmarshaller>(new Amazon.CloudSearchDomain.Internal.ProcessExceptionHandler());
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region Search
/// <summary>
/// Retrieves a list of documents that match the specified search criteria. How you specify
/// the search criteria depends on which query parser you use. Amazon CloudSearch supports
/// four query parsers:
///
/// <ul> <li> <code>simple</code>: search all <code>text</code> and <code>text-array</code>
/// fields for the specified string. Search for phrases, individual terms, and prefixes.
/// </li> <li> <code>structured</code>: search specific fields, construct compound queries
/// using Boolean operators, and use advanced features such as term boosting and proximity
/// searching.</li> <li> <code>lucene</code>: specify search criteria using the Apache
/// Lucene query parser syntax.</li> <li> <code>dismax</code>: specify search criteria
/// using the simplified subset of the Apache Lucene query parser syntax defined by the
/// DisMax query parser.</li> </ul>
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching.html">Searching
/// Your Data</a> in the <i>Amazon CloudSearch Developer Guide</i>.
/// </para>
///
/// <para>
/// The endpoint for submitting <code>Search</code> requests is domain-specific. You submit
/// search requests to a domain's search endpoint. To get the search endpoint for your
/// domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
/// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
/// CloudSearch console.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the Search service method.</param>
///
/// <returns>The response from the Search service method, as returned by CloudSearchDomain.</returns>
/// <exception cref="Amazon.CloudSearchDomain.Model.SearchException">
/// Information about any problems encountered while processing a search request.
/// </exception>
public SearchResponse Search(SearchRequest request)
{
var marshaller = new SearchRequestMarshaller();
var unmarshaller = SearchResponseUnmarshaller.Instance;
return Invoke<SearchRequest,SearchResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the Search operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the Search operation on AmazonCloudSearchDomainClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSearch
/// operation.</returns>
public IAsyncResult BeginSearch(SearchRequest request, AsyncCallback callback, object state)
{
var marshaller = new SearchRequestMarshaller();
var unmarshaller = SearchResponseUnmarshaller.Instance;
return BeginInvoke<SearchRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the Search operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSearch.</param>
///
/// <returns>Returns a SearchResult from CloudSearchDomain.</returns>
public SearchResponse EndSearch(IAsyncResult asyncResult)
{
return EndInvoke<SearchResponse>(asyncResult);
}
#endregion
#region Suggest
/// <summary>
/// Retrieves autocomplete suggestions for a partial query string. You can use suggestions
/// enable you to display likely matches before users finish typing. In Amazon CloudSearch,
/// suggestions are based on the contents of a particular text field. When you request
/// suggestions, Amazon CloudSearch finds all of the documents whose values in the suggester
/// field start with the specified query string. The beginning of the field must match
/// the query string to be considered a match.
///
///
/// <para>
/// For more information about configuring suggesters and retrieving suggestions, see
/// <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html">Getting
/// Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.
/// </para>
///
/// <para>
/// The endpoint for submitting <code>Suggest</code> requests is domain-specific. You
/// submit suggest requests to a domain's search endpoint. To get the search endpoint
/// for your domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
/// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
/// CloudSearch console.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the Suggest service method.</param>
///
/// <returns>The response from the Suggest service method, as returned by CloudSearchDomain.</returns>
/// <exception cref="Amazon.CloudSearchDomain.Model.SearchException">
/// Information about any problems encountered while processing a search request.
/// </exception>
public SuggestResponse Suggest(SuggestRequest request)
{
var marshaller = new SuggestRequestMarshaller();
var unmarshaller = SuggestResponseUnmarshaller.Instance;
return Invoke<SuggestRequest,SuggestResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the Suggest operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the Suggest operation on AmazonCloudSearchDomainClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSuggest
/// operation.</returns>
public IAsyncResult BeginSuggest(SuggestRequest request, AsyncCallback callback, object state)
{
var marshaller = new SuggestRequestMarshaller();
var unmarshaller = SuggestResponseUnmarshaller.Instance;
return BeginInvoke<SuggestRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the Suggest operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSuggest.</param>
///
/// <returns>Returns a SuggestResult from CloudSearchDomain.</returns>
public SuggestResponse EndSuggest(IAsyncResult asyncResult)
{
return EndInvoke<SuggestResponse>(asyncResult);
}
#endregion
#region UploadDocuments
/// <summary>
/// Posts a batch of documents to a search domain for indexing. A document batch is a
/// collection of add and delete operations that represent the documents you want to add,
/// update, or delete from your domain. Batches can be described in either JSON or XML.
/// Each item that you want Amazon CloudSearch to return as a search result (such as a
/// product) is represented as a document. Every document has a unique ID and one or more
/// fields that contain the data that you want to search and return in results. Individual
/// documents cannot contain more than 1 MB of data. The entire batch cannot exceed 5
/// MB. To get the best possible upload performance, group add and delete operations in
/// batches that are close the 5 MB limit. Submitting a large volume of single-document
/// batches can overload a domain's document service.
///
///
/// <para>
/// The endpoint for submitting <code>UploadDocuments</code> requests is domain-specific.
/// To get the document endpoint for your domain, use the Amazon CloudSearch configuration
/// service <code>DescribeDomains</code> action. A domain's endpoints are also displayed
/// on the domain dashboard in the Amazon CloudSearch console.
/// </para>
///
/// <para>
/// For more information about formatting your data for Amazon CloudSearch, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html">Preparing
/// Your Data</a> in the <i>Amazon CloudSearch Developer Guide</i>. For more information
/// about uploading data for indexing, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/uploading-data.html">Uploading
/// Data</a> in the <i>Amazon CloudSearch Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UploadDocuments service method.</param>
///
/// <returns>The response from the UploadDocuments service method, as returned by CloudSearchDomain.</returns>
/// <exception cref="Amazon.CloudSearchDomain.Model.DocumentServiceException">
/// Information about any problems encountered while processing an upload request.
/// </exception>
public UploadDocumentsResponse UploadDocuments(UploadDocumentsRequest request)
{
var marshaller = new UploadDocumentsRequestMarshaller();
var unmarshaller = UploadDocumentsResponseUnmarshaller.Instance;
return Invoke<UploadDocumentsRequest,UploadDocumentsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UploadDocuments operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UploadDocuments operation on AmazonCloudSearchDomainClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUploadDocuments
/// operation.</returns>
public IAsyncResult BeginUploadDocuments(UploadDocumentsRequest request, AsyncCallback callback, object state)
{
var marshaller = new UploadDocumentsRequestMarshaller();
var unmarshaller = UploadDocumentsResponseUnmarshaller.Instance;
return BeginInvoke<UploadDocumentsRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UploadDocuments operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUploadDocuments.</param>
///
/// <returns>Returns a UploadDocumentsResult from CloudSearchDomain.</returns>
public UploadDocumentsResponse EndUploadDocuments(IAsyncResult asyncResult)
{
return EndInvoke<UploadDocumentsResponse>(asyncResult);
}
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using Gallio.Common.Diagnostics;
using Gallio.Host.Properties;
using Gallio.Common.Platform;
using Gallio.Common.Reflection;
using Gallio.Runtime.ConsoleSupport;
using Gallio.Runtime.Debugging;
using Gallio.Runtime.Hosting;
using Gallio.Runtime.Logging;
namespace Gallio.Host
{
/// <summary>
/// The Gallio host process.
/// </summary>
public sealed class HostProgram : ConsoleProgram<HostArguments>
{
/// <summary>
/// Creates an instance of the program.
/// </summary>
public HostProgram()
{
ApplicationName = Resources.ApplicationName;
}
/// <inheritdoc />
protected override int RunImpl(string[] args)
{
if (!ParseArguments(args))
{
ShowHelp();
return 1;
}
if (Arguments.Help)
{
ShowHelp();
return 0;
}
if (! ValidateArguments())
{
ShowHelp();
return 1;
}
ILogger logger = Arguments.Quiet ? NullLogger.Instance : (ILogger) new RichConsoleLogger(Console);
if (Arguments.SeverityPrefix)
logger = new SeverityPrefixLogger(logger);
/* Already reported via other means. The duplication is distracting.
UnhandledExceptionPolicy.ReportUnhandledException += (sender, e) =>
{
if (! e.IsRecursive)
logger.Log(LogSeverity.Error, String.Format("Unhandled exception: {0}", e.GetDescription()));
};
*/
logger.Log(LogSeverity.Info, String.Format("Host started at {0}.", DateTime.Now));
logger.Log(LogSeverity.Info, String.Format("Running under {0} {1} runtime.",
DotNetRuntimeSupport.RuntimeType, DotNetRuntimeSupport.RuntimeVersion));
bool fatal = false;
try
{
if (Arguments.Debug)
RunEndpointWithDebugger(logger);
else
RunEndpoint(logger);
}
catch (Exception ex)
{
logger.Log(LogSeverity.Error, String.Format("Fatal exception: {0}", ExceptionUtils.SafeToString(ex)));
fatal = true;
}
logger.Log(LogSeverity.Info, String.Format("Host stopped at {0}.", DateTime.Now));
ForceExit(fatal);
return 0;
}
private static void ForceExit(bool fatal)
{
// Force the host to terminate in case there are some recalcitrant foreground
// threads still kicking around.
if (DotNetRuntimeSupport.IsUsingMono && fatal)
{
// On Mono, we can encounter (unexplained) CannotUnloadAppDomainExceptions
// which prevent the process from terminating even when we call Exit.
// So in the interest of robustness, we give it a little shove...
Process.GetCurrentProcess().Kill();
}
Environment.Exit(0);
}
private bool ValidateArguments()
{
if (Arguments.IpcPortName != null && Arguments.TcpPortNumber >= 0
|| Arguments.IpcPortName == null && Arguments.TcpPortNumber < 0)
{
ShowErrorMessage("Either /ipc-port or /tcp-port must be specified, not both.");
return false;
}
if (Arguments.ApplicationBaseDirectory != null && !Directory.Exists(Arguments.ApplicationBaseDirectory))
{
ShowErrorMessage(string.Format("The specified application base directory '{0}' does not exist.", Arguments.ApplicationBaseDirectory));
return false;
}
foreach (string hintDirectory in Arguments.HintDirectories)
{
if (!Directory.Exists(hintDirectory))
{
ShowErrorMessage(string.Format("The specified hint directory '{0}' does not exist.", hintDirectory));
return false;
}
}
if (Arguments.ConfigurationFile != null && !File.Exists(Arguments.ConfigurationFile))
{
ShowErrorMessage(string.Format("The specified configuration file '{0}' does not exist.", Arguments.ConfigurationFile));
return false;
}
return true;
}
private void RunEndpointWithDebugger(ILogger logger)
{
Process currentProcess = Process.GetCurrentProcess();
IDebuggerManager debuggerManager = new DefaultDebuggerManager(); // FIXME: Get from IoC
var debuggerSetup = new DebuggerSetup();
IDebugger debugger = debuggerManager.GetDebugger(debuggerSetup, logger);
AttachDebuggerResult attachResult = AttachDebuggerResult.CouldNotAttach;
try
{
if (! Debugger.IsAttached)
{
logger.Log(LogSeverity.Important, "Attaching the debugger to the host.");
attachResult = debugger.AttachToProcess(currentProcess);
if (attachResult == AttachDebuggerResult.CouldNotAttach)
logger.Log(LogSeverity.Warning, "Could not attach debugger to the host.");
}
RunEndpoint(logger);
}
finally
{
if (attachResult == AttachDebuggerResult.Attached)
{
logger.Log(LogSeverity.Important, "Detaching the debugger from the host.");
DetachDebuggerResult detachResult = debugger.DetachFromProcess(currentProcess);
if (detachResult == DetachDebuggerResult.CouldNotDetach)
logger.Log(LogSeverity.Warning, "Could not detach debugger from the host.");
}
}
}
private void RunEndpoint(ILogger logger)
{
AppDomain appDomain = null;
try
{
appDomain = AppDomainUtils.CreateAppDomain(@"Host",
Arguments.ApplicationBaseDirectory, Arguments.ConfigurationFile, Arguments.ShadowCopy);
Type endpointType = typeof(HostEndpoint);
using (HostEndpoint endpoint = (HostEndpoint)appDomain.CreateInstanceFromAndUnwrap(
AssemblyUtils.GetAssemblyLocalPath(endpointType.Assembly), endpointType.FullName))
{
foreach (string hintDirectory in Arguments.HintDirectories)
endpoint.AddHintDirectory(hintDirectory);
if (Arguments.OwnerProcessId >= 0)
{
if (!endpoint.SetOwnerProcess(Arguments.OwnerProcessId))
{
logger.Log(LogSeverity.Warning,
String.Format("The owner process with PID {0} does not appear to be running!",
Arguments.OwnerProcessId));
return;
}
}
if (Arguments.IpcPortName != null)
{
logger.Log(LogSeverity.Debug, String.Format("Listening for connections on IPC port: '{0}'",
Arguments.IpcPortName));
endpoint.InitializeIpcChannel(Arguments.IpcPortName);
}
else
{
logger.Log(LogSeverity.Debug, String.Format("Listening for connections on TCP port: '{0}'",
Arguments.TcpPortNumber));
endpoint.InitializeTcpChannel(Arguments.TcpPortNumber);
}
TimeSpan? watchdogTimeout = Arguments.TimeoutSeconds <= 0
? (TimeSpan?) null
: TimeSpan.FromSeconds(Arguments.TimeoutSeconds);
HostTerminationReason reason = endpoint.Run(watchdogTimeout);
switch (reason)
{
case HostTerminationReason.WatchdogTimeout:
logger.Log(LogSeverity.Warning, "Watchdog timer expired!");
break;
case HostTerminationReason.Disowned:
logger.Log(LogSeverity.Warning, "Owner process terminated abruptly!");
break;
case HostTerminationReason.Disposed:
break;
}
}
}
finally
{
// For some reason this is throwing CannotUnloadAppDomainException on Mono 1.9.1.
// After that happens, the process refuses to shut down normally.
// -- Jeff.
if (appDomain != null)
AppDomain.Unload(appDomain);
}
}
[STAThread]
//[LoaderOptimization(LoaderOptimization.MultiDomain)] // Disabled due to bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95157
internal static int Main(string[] args)
{
return new HostProgram().Run(NativeConsole.Instance, args);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Runtime.CompilerServices;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
namespace umbraco.cms.businesslogic.task
{
/// <summary>
/// An umbraco task is currently only used with the translation workflow in umbraco. But is extendable to cover other taskbased system as well.
/// A task represent a simple job, it will always be assigned to a user, related to a node, and contain a comment about the task.
/// The user attached to the task can complete the task, and the author of the task can reopen tasks that are not complete correct.
///
/// Tasks can in umbraco be used for setting up simple workflows, and contains basic controls structures to determine if the task is completed or not.
/// </summary>
public class Task
{
#region Properties
private int _id;
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public int Id
{
get { return _id; }
set { _id = value; }
}
private bool _closed;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Task"/> is closed.
/// </summary>
/// <value><c>true</c> if closed; otherwise, <c>false</c>.</value>
public bool Closed
{
get { return _closed; }
set { _closed = value; }
}
private CMSNode _node;
/// <summary>
/// Gets or sets the node.
/// </summary>
/// <value>The node.</value>
public CMSNode Node
{
get { return _node; }
set { _node = value; }
}
private TaskType _type;
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public TaskType Type
{
get { return _type; }
set { _type = value; }
}
private User _parentUser;
/// <summary>
/// Gets or sets the parent user.
/// </summary>
/// <value>The parent user.</value>
public User ParentUser
{
get { return _parentUser; }
set { _parentUser = value; }
}
private string _comment;
/// <summary>
/// Gets or sets the comment.
/// </summary>
/// <value>The comment.</value>
public string Comment
{
get { return _comment; }
set { _comment = value; }
}
private DateTime _date;
/// <summary>
/// Gets or sets the date.
/// </summary>
/// <value>The date.</value>
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
private User _user;
/// <summary>
/// Gets or sets the user.
/// </summary>
/// <value>The user.</value>
public User User
{
get { return _user; }
set { _user = value; }
}
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Task"/> class.
/// </summary>
public Task()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Task"/> class.
/// </summary>
/// <param name="TaskId">The task id.</param>
public Task(int TaskId)
{
using (IRecordsReader dr =
SqlHelper.ExecuteReader(
"select id, taskTypeId, nodeId, parentUserId, userId, DateTime, comment, closed from cmsTask where id = @id",
SqlHelper.CreateParameter("@id", TaskId)))
{
if (dr.Read())
{
PopulateTaskFromReader(dr);
}
else
{
throw new ArgumentException("Task with id: '" + TaskId + "' not found");
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Deletes the current task.
/// Generally tasks should not be deleted and closed instead.
/// </summary>
public void Delete()
{
SqlHelper.ExecuteNonQuery("DELETE FROM cmsTask WHERE id = @id", SqlHelper.CreateParameter("@id", this._id));
}
/// <summary>
/// Saves this instance.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Save()
{
//error checking
if (Node == null) throw new ArgumentNullException("Node");
if (ParentUser == null) throw new ArgumentNullException("ParentUser");
if (User == null) throw new ArgumentNullException("User");
if (Id == 0)
{
// The method is synchronized
SqlHelper.ExecuteNonQuery(
"insert into cmsTask (closed, taskTypeId, nodeId, parentUserId, userId, comment) values (@closed, @taskTypeId, @nodeId, @parentUserId, @userId, @comment)",
SqlHelper.CreateParameter("@closed", Closed),
SqlHelper.CreateParameter("@taskTypeId", Type.Id),
SqlHelper.CreateParameter("@nodeId", Node.Id),
SqlHelper.CreateParameter("@parentUserId", ParentUser.Id),
SqlHelper.CreateParameter("@userId", User.Id),
SqlHelper.CreateParameter("@comment", Comment));
Id = SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM cmsTask");
}
else
{
SqlHelper.ExecuteNonQuery(
"update cmsTask set closed = @closed, taskTypeId = @taskTypeId, nodeId = @nodeId, parentUserId = @parentUserId, userId = @userId, comment = @comment where id = @id",
SqlHelper.CreateParameter("@closed", Closed),
SqlHelper.CreateParameter("@taskTypeId", Type.Id),
SqlHelper.CreateParameter("@nodeId", Node.Id),
SqlHelper.CreateParameter("@parentUserId", ParentUser.Id),
SqlHelper.CreateParameter("@userId", User.Id),
SqlHelper.CreateParameter("@comment", Comment),
SqlHelper.CreateParameter("@id", Id));
}
}
#endregion
#region Private methods
private void PopulateTaskFromReader(IRecordsReader dr)
{
_id = dr.GetInt("id");
Type = new TaskType((int)dr.GetByte("taskTypeId"));
Node = new CMSNode(dr.GetInt("nodeId"));
ParentUser = User.GetUser(dr.GetInt("parentUserId"));
User = User.GetUser(dr.GetInt("userId"));
Date = dr.GetDateTime("DateTime");
Comment = dr.GetString("comment");
Closed = dr.GetBoolean("closed");
}
#endregion
#region static methods
/// <summary>
/// Returns all tasks by type
/// </summary>
/// <param name="taskType"></param>
/// <returns></returns>
public static Tasks GetTasksByType(int taskType)
{
var sql = "select id, taskTypeId, nodeId, parentUserId, userId, DateTime, comment, closed from cmsTask where taskTypeId = @taskTypeId";
Tasks tasks = new Tasks();
using (IRecordsReader dr = SqlHelper.ExecuteReader(sql, SqlHelper.CreateParameter("@taskTypeId", taskType)))
{
while (dr.Read())
{
var t = new Task();
t.PopulateTaskFromReader(dr);
tasks.Add(t);
}
}
return tasks;
}
/// <summary>
/// Get all tasks assigned to a node
/// </summary>
/// <param name="nodeId"></param>
/// <returns></returns>
public static Tasks GetTasks(int nodeId)
{
var sql = "select id, taskTypeId, nodeId, parentUserId, userId, DateTime, comment, closed from cmsTask where nodeId = @nodeId";
Tasks tasks = new Tasks();
using (IRecordsReader dr = SqlHelper.ExecuteReader(sql, SqlHelper.CreateParameter("@nodeId", nodeId)))
{
while (dr.Read())
{
var t = new Task();
t.PopulateTaskFromReader(dr);
tasks.Add(t);
}
}
return tasks;
}
/// <summary>
/// Retrieves a collection of open tasks assigned to the user
/// </summary>
/// <param name="User">The User who have the tasks assigned</param>
/// <param name="IncludeClosed">If true both open and closed tasks will be returned</param>
/// <returns>A collections of tasks</returns>
public static Tasks GetTasks(User User, bool IncludeClosed) {
string sql = "select id, taskTypeId, nodeId, parentUserId, userId, DateTime, comment, closed from cmsTask where userId = @userId";
if (!IncludeClosed)
sql += " and closed = 0";
sql += " order by DateTime desc";
Tasks tasks = new Tasks();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
sql,
SqlHelper.CreateParameter("@userId", User.Id)))
{
while (dr.Read())
{
var t = new Task();
t.PopulateTaskFromReader(dr);
tasks.Add(t);
}
}
return tasks;
}
/// <summary>
/// Retrieves a collection of open tasks assigned to the user
/// </summary>
/// <param name="User">The User who have the tasks assigned</param>
/// <param name="IncludeClosed">If true both open and closed tasks will be returned</param>
/// <returns>A collections of tasks</returns>
public static Tasks GetOwnedTasks(User User, bool IncludeClosed) {
string sql = "select id, taskTypeId, nodeId, parentUserId, userId, DateTime, comment, closed from cmsTask where parentUserId = @userId";
if (!IncludeClosed)
sql += " and closed = 0";
sql += " order by DateTime desc";
Tasks tasks = new Tasks();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
sql,
SqlHelper.CreateParameter("@userId", User.Id))) {
while (dr.Read())
{
var t = new Task();
t.PopulateTaskFromReader(dr);
tasks.Add(t);
}
}
return tasks;
}
#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 Xunit;
using System;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class AddNVCTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
[ActiveIssue(2769, PlatformID.AnyUnix)]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
NameValueCollection nvc1;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
nvc1 = new NameValueCollection();
// [] Add(empty_coll) to empty collection
//
nvc.Clear();
nvc1.Clear();
nvc.Add(nvc1);
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of 0", nvc.Count));
}
// [] Add(simple_strings_coll) to empty collection
//
nvc.Clear();
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
nvc1.Clear();
nvc1.Add(nvc);
if (nvc1.Count != nvc.Count)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, nvc.Count));
}
//
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
// [] Add(simple_strings_coll) to simple_string_collection
//
len = values.Length;
if (nvc.Count < len)
{
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
nvc1.Clear();
for (int i = 0; i < len; i++)
{
nvc1.Add("k" + i, "v" + i);
}
cnt = nvc1.Count;
nvc1.Add(nvc);
if (nvc1.Count != cnt + nvc.Count)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, cnt + nvc.Count));
}
//
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
}
if (String.Compare(nvc1["k" + i], "v" + i) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc["k" + i], "v" + i));
}
}
//
// Intl strings
// [] Add(intl_strings_coll) to empty collection
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
// fill init collection with intl strings
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
// add filled collection to tested empty collection
nvc1.Clear();
nvc1.Add(nvc);
for (int i = 0; i < len; i++)
{
//
if (String.Compare(nvc1[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValues[i + len]], intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
// add uppercase to tested collection
nvc1.Clear();
nvc1.Add(nvc);
//
for (int i = 0; i < len; i++)
{
// uppercase key
if (String.Compare(nvc1[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValues[i + len]], intlValues[i]));
}
// lowercase key
if (String.Compare(nvc1[intlValuesLower[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc1[intlValuesLower[i + len]], intlValues[i]));
}
if (!caseInsensitive && (String.Compare(nvc1[intlValues[i + len]], intlValuesLower[i]) == 0))
{
Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
}
}
//
// when adding values with existing keys, values should be added to existing values
// [] Add(NVC) with already existing keys
//
nvc.Clear();
cnt = nvc.Count;
len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
nvc1.Clear();
for (int i = 0; i < len; i++)
{
nvc1.Add(keys[i], values[i]);
}
if (nvc1.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, values.Length));
}
cnt = nvc1.Count;
nvc1.Add(nvc);
// count should not change
if (nvc1.Count != cnt)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, cnt));
}
// values should be added to previously existed values
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1[keys[i]], values[i] + "," + values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i] + "," + values[i]));
}
}
// [] multiple items with same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string k1 = "hm1";
string exp = "";
string exp1 = "";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
nvc.Add(k1, "iTem" + i);
if (i < len - 1)
{
exp += "Value" + i + ",";
exp1 += "iTem" + i + ",";
}
else
{
exp += "Value" + i;
exp1 += "iTem" + i;
}
}
if (nvc.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
}
// add NVC
nvc1.Clear();
nvc1.Add(nvc);
if (String.Compare(nvc1[k], exp) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[k], exp));
}
// Values array should contain len items
if (nvc1.GetValues(k).Length != len)
{
Assert.False(true, string.Format("Error, number of values is {0} instead of {1}", nvc1.GetValues(k).Length, len));
}
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1.GetValues(k)[i], "Value" + i) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, nvc1.GetValues(k)[i], "Value" + i));
}
}
if (String.Compare(nvc1[k1], exp1) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[k1], exp1));
}
// Values array should contain len items
if (nvc1.GetValues(k1).Length != len)
{
Assert.False(true, string.Format("Error, number of values is {0} instead of {1}", nvc1.GetValues(k1).Length, len));
}
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1.GetValues(k1)[i], "iTem" + i) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, nvc1.GetValues(k1)[i], "iTem" + i));
}
}
//
// [] Add(with_null_key) when there is item with null key
//
cnt = nvc.Count;
nvc.Add(null, "nullValue");
nvc1[null] = "nullValue1";
nvc1.Add(nvc);
if (String.Compare(nvc1[null], "nullValue1," + nvc[null]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc1[null], "nullValue1," + nvc[null]));
}
//
// [] Add(with_null_key) when there is no item with null key
//
nvc.Clear();
nvc1.Clear();
for (int i = 0; i < len; i++)
{
nvc1.Add(keys[i], values[i]);
}
nvc[null] = "newNullValue";
nvc1.Add(nvc);
if (String.Compare(nvc1[null], "newNullValue") != 0)
{
Assert.False(true, "Error, returned unexpected value ");
}
//
// [] Add(null_collection)
//
try
{
nvc1.Add(null);
Assert.False(true, "Error, no exception");
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
//
// [] Add(empty_coll) to filled collection
//
nvc.Clear();
if (nvc1.Count < len)
{
nvc1.Clear();
for (int i = 0; i < len; i++)
{
nvc1.Add(keys[i], values[i]);
}
if (nvc1.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, values.Length));
}
}
cnt = nvc1.Count;
nvc1.Add(nvc);
if (nvc1.Count != cnt)
{
Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc1.Count, cnt));
}
// verify that collection has not changed
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
//
// [] Add collection with null values
//
nvc.Clear();
nvc1.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], null);
}
nvc1.Add(nvc);
if (nvc1.Count != nvc.Count)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc1.Count, nvc.Count));
}
//
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc1[keys[i]], null) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PropertyOperations operations.
/// </summary>
internal partial class PropertyOperations : IServiceOperations<ApiManagementClient>, IPropertyOperations
{
/// <summary>
/// Initializes a new instance of the PropertyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PropertyOperations(ApiManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ApiManagementClient
/// </summary>
public ApiManagementClient Client { get; private set; }
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PropertyContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<PropertyContract> odataQuery = default(ODataQuery<PropertyContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByService", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PropertyContract>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PropertyContract>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the details of the property specified by its identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PropertyContract,PropertyGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (propId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "propId");
}
if (propId != null)
{
if (propId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "propId", 256);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(propId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "propId", "^[^*#&+:<>?]+$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{propId}", System.Uri.EscapeDataString(propId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 AzureOperationResponse<PropertyContract,PropertyGetHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PropertyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PropertyGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a property.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PropertyContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, PropertyContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (propId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "propId");
}
if (propId != null)
{
if (propId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "propId", 256);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(propId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "propId", "^[^*#&+:<>?]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{propId}", System.Uri.EscapeDataString(propId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 AzureOperationResponse<PropertyContract>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PropertyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PropertyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates the specific property.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, PropertyUpdateParameters parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (propId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "propId");
}
if (propId != null)
{
if (propId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "propId", 256);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(propId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "propId", "^[^*#&+:<>?]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (ifMatch == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{propId}", System.Uri.EscapeDataString(propId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes specific property from the the API Management service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to delete. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (propId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "propId");
}
if (propId != null)
{
if (propId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "propId", 256);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(propId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "propId", "^[^*#&+:<>?]+$");
}
}
if (ifMatch == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("propId", propId);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/properties/{propId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{propId}", System.Uri.EscapeDataString(propId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PropertyContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByServiceNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PropertyContract>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PropertyContract>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Branding.InjectResponsiveCSS
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// 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.Concurrent;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
internal class StackTraceSymbols : IDisposable
{
private readonly ConcurrentDictionary<IntPtr, MetadataReaderProvider> _metadataCache;
/// <summary>
/// Create an instance of this class.
/// </summary>
public StackTraceSymbols()
{
_metadataCache = new ConcurrentDictionary<IntPtr, MetadataReaderProvider>();
}
/// <summary>
/// Clean up any cached providers.
/// </summary>
void IDisposable.Dispose()
{
foreach (MetadataReaderProvider provider in _metadataCache.Values)
{
provider?.Dispose();
}
_metadataCache.Clear();
}
/// <summary>
/// Returns the source file and line number information for the method.
/// </summary>
/// <param name="assemblyPath">file path of the assembly or null</param>
/// <param name="loadedPeAddress">loaded PE image address or zero</param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="methodToken">method token</param>
/// <param name="ilOffset">il offset of the stack frame</param>
/// <param name="sourceFile">source file return</param>
/// <param name="sourceLine">line number return</param>
/// <param name="sourceColumn">column return</param>
internal void GetSourceLineInfo(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn)
{
sourceFile = null;
sourceLine = 0;
sourceColumn = 0;
MetadataReader reader = TryGetReader(assemblyPath, loadedPeAddress, loadedPeSize, inMemoryPdbAddress, inMemoryPdbSize);
if (reader != null)
{
Handle handle = MetadataTokens.Handle(methodToken);
if (handle.Kind == HandleKind.MethodDefinition)
{
MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
MethodDebugInformation methodInfo = reader.GetMethodDebugInformation(methodDebugHandle);
if (!methodInfo.SequencePointsBlob.IsNil)
{
SequencePointCollection sequencePoints = methodInfo.GetSequencePoints();
SequencePoint? bestPointSoFar = null;
foreach (SequencePoint point in sequencePoints)
{
if (point.Offset > ilOffset)
break;
if (point.StartLine != SequencePoint.HiddenLine)
bestPointSoFar = point;
}
if (bestPointSoFar.HasValue)
{
sourceLine = bestPointSoFar.Value.StartLine;
sourceColumn = bestPointSoFar.Value.StartColumn;
sourceFile = reader.GetString(reader.GetDocument(bestPointSoFar.Value.Document).Name);
}
}
}
}
}
/// <summary>
/// Returns the portable PDB reader for the assembly path
/// </summary>
/// <param name="assemblyPath">
/// File path of the assembly or null if the module is dynamic (generated by Reflection.Emit).
/// </param>
/// <param name="loadedPeAddress">
/// Loaded PE image address or zero if the module is dynamic (generated by Reflection.Emit).
/// Dynamic modules have their PDBs (if any) generated to an in-memory stream
/// (pointed to by <paramref name="inMemoryPdbAddress"/> and <paramref name="inMemoryPdbSize"/>).
/// </param>
/// <param name="loadedPeSize">loaded PE image size</param>
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <param name="reader">returns the reader</param>
/// <returns>reader</returns>
/// <remarks>
/// Assumes that neither PE image nor PDB loaded into memory can be unloaded or moved around.
/// </remarks>
private unsafe MetadataReader TryGetReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
if ((loadedPeAddress == IntPtr.Zero || assemblyPath == null) && inMemoryPdbAddress == IntPtr.Zero)
{
// Dynamic or in-memory module without symbols (they would be in-memory if they were available).
return null;
}
IntPtr cacheKey = (inMemoryPdbAddress != IntPtr.Zero) ? inMemoryPdbAddress : loadedPeAddress;
MetadataReaderProvider provider;
while (!_metadataCache.TryGetValue(cacheKey, out provider))
{
provider = (inMemoryPdbAddress != IntPtr.Zero) ?
TryOpenReaderForInMemoryPdb(inMemoryPdbAddress, inMemoryPdbSize) :
TryOpenReaderFromAssemblyFile(assemblyPath, loadedPeAddress, loadedPeSize);
// If the add loses the race with another thread, then the dispose the provider just
// created and return the provider already in the cache.
if (_metadataCache.TryAdd(cacheKey, provider))
break;
provider?.Dispose();
}
// The reader has already been open, so this doesn't throw.
return provider?.GetMetadataReader();
}
private static unsafe MetadataReaderProvider TryOpenReaderForInMemoryPdb(IntPtr inMemoryPdbAddress, int inMemoryPdbSize)
{
Debug.Assert(inMemoryPdbAddress != IntPtr.Zero);
// quick check to avoid throwing exceptions below in common cases:
const uint ManagedMetadataSignature = 0x424A5342;
if (inMemoryPdbSize < sizeof(uint) || *(uint*)inMemoryPdbAddress != ManagedMetadataSignature)
{
// not a Portable PDB
return null;
}
var provider = MetadataReaderProvider.FromMetadataImage((byte*)inMemoryPdbAddress, inMemoryPdbSize);
try
{
// may throw if the metadata is invalid
provider.GetMetadataReader();
return provider;
}
catch (BadImageFormatException)
{
provider.Dispose();
return null;
}
}
private static unsafe PEReader TryGetPEReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize)
{
// TODO: https://github.com/dotnet/corefx/issues/11406
//if (loadedPeAddress != IntPtr.Zero && loadedPeSize > 0)
//{
// return new PEReader((byte*)loadedPeAddress, loadedPeSize, isLoadedImage: true);
//}
Stream peStream = TryOpenFile(assemblyPath);
if (peStream != null)
{
return new PEReader(peStream);
}
return null;
}
private static MetadataReaderProvider TryOpenReaderFromAssemblyFile(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize)
{
using (var peReader = TryGetPEReader(assemblyPath, loadedPeAddress, loadedPeSize))
{
if (peReader == null)
{
return null;
}
string pdbPath;
MetadataReaderProvider provider;
if (peReader.TryOpenAssociatedPortablePdb(assemblyPath, TryOpenFile, out provider, out pdbPath))
{
// TODO:
// Consider caching the provider in a global cache (across stack traces) if the PDB is embedded (pdbPath == null),
// as decompressing embedded PDB takes some time.
return provider;
}
}
return null;
}
private static Stream TryOpenFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
return File.OpenRead(path);
}
catch
{
return null;
}
}
}
}
| |
/*
* Created by Alexandre Rocha Lima e Marcondes
* User: Administrator
* Date: 27/09/2005
* Time: 15:49
*
* Description: An SQL Builder, Object Interface to Database Tables
* Its based on DataObjects from php PEAR
* 1. Builds SQL statements based on the objects vars and the builder methods.
* 2. acts as a datastore for a table row.
* The core class is designed to be extended for each of your tables so that you put the
* data logic inside the data classes.
* included is a Generator to make your configuration files and your base classes.
*
* CSharp DataObject
* Copyright (c) 2005, Alessandro de Oliveira Binhara
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Data;
using NUnit.Framework;
using CsDO.Lib;
using CsDO.Lib.MockDriver;
namespace CsDO.Tests {
public class TesteObj4 : DataObject {
private int _id;
[Column("Cod")]
public int ID {
get {
return _id;
}
set {
_id = value;
}
}
private string _nome;
public string Nome {
get {
return _nome;
}
set {
_nome = value;
}
}
private int _idade;
public int Idade {
get {
return _idade;
}
set {
_idade = value;
}
}
private double _peso;
[Column("PesoKg")]
public double Peso {
get {
return _peso;
}
set {
_peso = value;
}
}
private TesteObj _teste;
[Column("Teste1")]
public TesteObj TesteObj3 {
get {
return _teste;
}
set {
_teste = value;
}
}
public void SetField(string col, object val)
{
setField(col, val);
}
public bool Retrieve(string col, object val)
{
return retrieve(col, val);
}
public string GetFields()
{
return Fields;
}
public string GetActiveFields()
{
return ActiveFields;
}
}
[TestFixture]
public class ForeignKeyTests {
[TestFixtureSetUp]
public void FixtureSetup() {
Conf.Driver = new MockDriver();
((MockDriver) Conf.Driver).addTable("TesteObj");
((MockDriver) Conf.Driver).addColumn("TesteObj", "Cod", typeof(Int32), true, false);
((MockDriver) Conf.Driver).addColumn("TesteObj", "Idade", typeof(Int32));
((MockDriver) Conf.Driver).addColumn("TesteObj", "Nome", typeof(string));
((MockDriver) Conf.Driver).addColumn("TesteObj", "PesoKg", typeof(Double));
((MockDriver) Conf.Driver).addColumn("TesteObj", "Teste1", typeof(Int32));
((MockDriver)Conf.Driver).addColumn("TesteObj", "Ativo", typeof(bool));
((MockDriver)Conf.Driver).addColumn("TesteObj", "Aniversario", typeof(DateTime));
DataRow data = ((MockDriver) Conf.Driver).newRow("TesteObj");
data["Cod"] = 5;
data["Idade"] = 18;
data["Nome"] = "teste1";
data["PesoKg"] = 60.5;
data["Teste1"] = 5;
((MockDriver) Conf.Driver).addRow("TesteObj", data);
data = ((MockDriver) Conf.Driver).newRow("TesteObj");
data["Cod"] = 2;
data["Idade"] = 20;
data["Nome"] = "teste2";
data["PesoKg"] = 80.5;
data["Teste1"] = 10;
((MockDriver) Conf.Driver).addRow("TesteObj", data);
data = ((MockDriver) Conf.Driver).newRow("TesteObj");
data["Cod"] = 3;
data["Idade"] = 22;
data["Nome"] = "teste3";
data["PesoKg"] = 50.5;
data["Teste1"] = 15;
((MockDriver) Conf.Driver).addRow("TesteObj", data);
data = ((MockDriver) Conf.Driver).newRow("TesteObj");
data["Cod"] = 4;
data["Idade"] = 28;
data["Nome"] = "teste4";
data["PesoKg"] = 70.5;
data["Teste1"] = 20;
((MockDriver) Conf.Driver).addRow("TesteObj", data);
((MockDriver) Conf.Driver).addTable("TesteObj3");
((MockDriver) Conf.Driver).addColumn("TesteObj3", "Cod", typeof(Int32), true, false);
((MockDriver) Conf.Driver).addColumn("TesteObj3", "Idade", typeof(Int32));
((MockDriver) Conf.Driver).addColumn("TesteObj3", "Nome", typeof(string));
((MockDriver) Conf.Driver).addColumn("TesteObj3", "PesoKg", typeof(Double));
data = ((MockDriver) Conf.Driver).newRow("TesteObj3");
data["Cod"] = 5;
data["Idade"] = 50;
data["Nome"] = "teste5";
data["PesoKg"] = 100.5;
((MockDriver) Conf.Driver).addRow("TesteObj3", data);
data = ((MockDriver) Conf.Driver).newRow("TesteObj3");
data["Cod"] = 9;
data["Idade"] = 50;
data["Nome"] = "teste5";
data["PesoKg"] = 100.5;
((MockDriver) Conf.Driver).addRow("TesteObj3", data);
}
[TestFixtureTearDown]
public void FixtureTearDown() {
Conf.Driver = null;
}
[Test]
public void Inheritance() {
TesteObj2 obj = new TesteObj2();
obj.ID = 1;
obj.Nome = "teste";
obj.Idade = 18;
obj.Peso = 60.5;
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 5;
obj.insert();
Assert.AreEqual("INSERT INTO TesteObject (Cod,Nome,Idade,PesoKg,Teste1,Ativo) Values (1,'teste',18,60.5,5,'F')", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot insert into table");
Assert.IsTrue(obj.find(), "DataObject find");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObject WHERE (Cod = 1) ", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot select from table");
Assert.IsTrue(obj.retrieve("Nome", "teste"), "DataObject retrieve");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObject WHERE Nome LIKE 'teste'", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject retrieve");
}
[Test]
public void Insert() {
TesteObj obj = new TesteObj();
obj.ID = 1;
obj.Nome = "teste";
obj.Idade = 18;
obj.Peso = 60.5;
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 5;
Assert.AreEqual(true, obj.insert(), "DataObject cannot insert into table");
Assert.AreEqual("INSERT INTO TesteObj (Cod,Nome,Idade,PesoKg,Teste1,Ativo) Values (1,'teste',18,60.5,5,'F')", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot insert into table");
}
[Test]
public void FindFetch() {
TesteObj obj = new TesteObj();
obj.ID = 1;
obj.Nome = "teste";
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 5;
Assert.IsTrue(obj.find(), "DataObject find");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObj WHERE (Cod = 1) ", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot select from table");
Assert.IsTrue(obj.fetch(), "DataObject fetch from DataReader");
obj = new TesteObj();
obj.Nome = "teste";
obj.Idade = 18;
obj.Peso = 60.5;
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 5;
Assert.IsTrue(obj.find(), "DataObject find");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObj WHERE (Nome LIKE 'teste') AND (Idade = 18) AND (PesoKg = 60.5) AND (Teste1 = 5) ", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot select from table");
}
[Test]
public void SetField() {
TesteObj obj = new TesteObj();
obj.ID = 2;
obj.Nome = "teste 2";
TesteObj3 obj3 = new TesteObj3();
obj3.ID = 5;
obj.SetField("Teste1", obj3);
Assert.AreEqual(obj3, obj.TesteObj3, "DataObject cannot set Field 'Nome'");
obj.SetField("Teste1", 1);
Assert.IsNull(obj.TesteObj3, "DataObject cannot set Field 'Teste1'");
obj.SetField("Teste1", 5);
Assert.AreEqual(5, obj.TesteObj3.ID, "DataObject cannot set Field 'Teste1'");
obj3 = new TesteObj3();
obj3.ID = 10;
obj.SetField("TesteObj3", obj3);
Assert.AreEqual(obj3, obj.TesteObj3, "DataObject cannot set Field 'TesteObj3'");
}
[Test, ExpectedException(typeof(CsDOException))]
public void SetFieldError() {
TesteObj4 obj = new TesteObj4();
obj.ID = 1;
obj.Nome = "teste";
obj.SetField("TesteObj", 2);
}
[Test]
public void Retrieve() {
Conf.DataPool.Clear();
TesteObj obj = new TesteObj();
TesteObj3 obj3 = new TesteObj3();
obj3.ID = 5;
Assert.IsTrue(obj.retrieve("Teste1", obj3), "DataObject retrieve");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObj WHERE Teste1 = 5", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject retrieve");
Assert.IsTrue(obj.fetch(), "DataObject fetch");
Assert.AreEqual(5, obj.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.Peso, "DataObject retrieve");
Assert.AreEqual(5, obj.TesteObj3.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.TesteObj3.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.TesteObj3.Peso, "DataObject retrieve");
Assert.AreEqual("teste1", obj.TesteObj3.Nome, "DataObject retrieve");
Assert.AreEqual("teste1", obj.Nome, "DataObject retrieve");
obj = new TesteObj();
Assert.IsTrue(obj.retrieve("Teste1", 5), "DataObject retrieve");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObj WHERE Teste1 = 5", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject retrieve");
Assert.IsTrue(obj.fetch(), "DataObject fetch");
Assert.AreEqual(5, obj.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.Peso, "DataObject retrieve");
Assert.AreEqual(5, obj.TesteObj3.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.TesteObj3.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.TesteObj3.Peso, "DataObject retrieve");
Assert.AreEqual("teste1", obj.TesteObj3.Nome, "DataObject retrieve");
Assert.AreEqual("teste1", obj.Nome, "DataObject retrieve");
obj = new TesteObj();
Assert.IsTrue(obj.retrieve("TesteObj3", 5), "DataObject retrieve");
Assert.AreEqual("SELECT Cod,Nome,Idade,PesoKg,Aniversario,Teste1,Ativo FROM TesteObj WHERE Teste1 = 5", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject retrieve");
Assert.IsTrue(obj.fetch(), "DataObject fetch");
Assert.AreEqual(5, obj.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.Peso, "DataObject retrieve");
Assert.AreEqual(5, obj.TesteObj3.ID, "DataObject retrieve");
Assert.AreEqual(18, obj.TesteObj3.Idade, "DataObject retrieve");
Assert.AreEqual(60.5, obj.TesteObj3.Peso, "DataObject retrieve");
Assert.AreEqual("teste1", obj.TesteObj3.Nome, "DataObject retrieve");
Assert.AreEqual("teste1", obj.Nome, "DataObject retrieve");
}
[Test]
public void Update() {
TesteObj obj = new TesteObj();
obj.ID = 1;
obj.Nome = "teste2";
obj.Idade = 22;
obj.Peso = 70.5;
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 5;
Assert.AreEqual(true, obj.update(), "DataObject cannot update table");
Assert.AreEqual("UPDATE TesteObj SET Nome='teste2',Idade=22,PesoKg=70.5,Teste1=5,Ativo='F' WHERE (Cod = 1) ", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot update table");
obj = new TesteObj();
obj.ID = 2;
obj.Nome = "teste3";
obj.TesteObj3 = new TesteObj3();
obj.TesteObj3.ID = 6;
Assert.AreEqual(true, obj.update(), "DataObject cannot update table");
Assert.AreEqual("UPDATE TesteObj SET Nome='teste3',Teste1=6,Ativo='F' WHERE (Cod = 2) ", ((MockDriver)Conf.Driver).getPreviousCommand().CommandText, "DataObject cannot update table");
}
}
}
| |
namespace dotless.Core.Parser.Tree
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Exceptions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
public class Color : Node, IOperable
{
private static readonly Dictionary<int, string> Html4ColorsReverse;
private static readonly Dictionary<string, int> Html4Colors =
new Dictionary<string, int>
{
{"black", 0x000000},
{"silver", 0xc0c0c0},
{"gray", 0x808080},
{"white", 0xffffff},
{"maroon", 0x800000},
{"red", 0xff0000},
{"purple", 0x800080},
{"fuchsia", 0xff00ff},
{"green", 0x008000},
{"lime", 0x00ff00},
{"olive", 0x808000},
{"yellow", 0xffff00},
{"navy", 0x000080},
{"blue", 0x0000ff},
{"teal", 0x008080},
{"aqua", 0x00ffff}
};
static Color()
{
Html4ColorsReverse = Html4Colors.ToDictionary(x => x.Value, x => x.Key);
}
public readonly double[] RGB;
public readonly double Alpha;
public Color(double[] rgb) : this(rgb, 1)
{
}
public Color(double[] rgb, double alpha)
{
RGB = rgb;
Alpha = alpha;
}
public Color(IEnumerable<Number> rgb, Number alpha)
{
RGB = rgb
.Select(d => d.Normalize(255d))
.ToArray<double>();
Alpha = alpha.Normalize();
}
public Color(string rgb)
{
if (rgb.Length == 6)
{
RGB = Enumerable.Range(0, 3)
.Select(i => rgb.Substring(i*2, 2))
.Select(s => (double) int.Parse(s, NumberStyles.HexNumber))
.ToArray();
}
else
{
RGB = rgb.ToCharArray()
.Select(c => (double) int.Parse("" + c + c, NumberStyles.HexNumber))
.ToArray();
}
Alpha = 1;
}
public Color(double red, double green, double blue, double alpha)
{
RGB = new[]
{
NumberExtensions.Normalize(red, 255d),
NumberExtensions.Normalize(green, 255d),
NumberExtensions.Normalize(blue, 255d)
};
Alpha = NumberExtensions.Normalize(alpha);
}
public Color(double red, double green, double blue)
: this(red, green, blue, 1d)
{
}
public Color(int color)
{
RGB = new double[3];
B = color & 0xff;
color >>= 8;
G = color & 0xff;
color >>= 8;
R = color & 0xff;
Alpha = 1;
}
public double R
{
get { return RGB[0]; }
set { RGB[0] = value; }
}
public double G
{
get { return RGB[1]; }
set { RGB[1] = value; }
}
public double B
{
get { return RGB[2]; }
set { RGB[2] = value; }
}
public override string ToCSS(Env env)
{
var rgb = RGB
.Select(d => (int) Math.Round(d, MidpointRounding.AwayFromZero))
.Select(i => i > 255 ? 255 : (i < 0 ? 0 : i))
.ToArray();
if (Alpha < 1.0)
return string.Format(CultureInfo.InvariantCulture, "rgba({0}, {1}, {2}, {3})", rgb[0], rgb[1], rgb[2], Alpha);
var keyword = GetKeyword(rgb);
var hexString = '#' + rgb
.Select(i => i.ToString("X2"))
.JoinStrings("")
.ToLowerInvariant();
if (env.Compress)
{
hexString = Regex.Replace(hexString, @"#(.)\1(.)\2(.)\3", "#$1$2$3");
return string.IsNullOrEmpty(keyword) || hexString.Length < keyword.Length ? hexString : keyword;
}
if (!string.IsNullOrEmpty(keyword))
return keyword;
return hexString;
}
public Node Operate(Operation op, Node other)
{
var otherColor = other as Color;
if (otherColor == null)
{
var operable = other as IOperable;
if(operable == null)
throw new ParsingException(string.Format("Unable to convert right hand side of {0} to a color", op.Operator), op.Index);
otherColor = operable.ToColor();
}
var result = new double[3];
for (var c = 0; c < 3; c++)
{
result[c] = Operation.Operate(op.Operator, RGB[c], otherColor.RGB[c]);
}
return new Color(result);
}
public Color ToColor()
{
return this;
}
public string GetKeyword(int[] rgb)
{
var color = (rgb[0] << 16) + (rgb[1] << 8) + rgb[2];
string keyword;
if (Html4ColorsReverse.TryGetValue(color, out keyword))
return keyword;
return null;
}
public static Color GetColorFromKeyword(string keyword)
{
int color;
if (Html4Colors.TryGetValue(keyword, out color))
return new Color(color);
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public partial class HttpWebRequestTest : RemoteExecutorTestBase
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private readonly ITestOutputHelper _output;
public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers;
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.True(request.AllowAutoRedirect);
Assert.False(request.AllowReadStreamBuffering);
Assert.True(request.AllowWriteStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.NotNull(request.ClientCertificates);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.True(request.KeepAlive);
Assert.Equal(0, request.Headers.Count);
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
Assert.Equal("GET", request.Method);
Assert.Equal(HttpWebRequest.DefaultMaximumResponseHeadersLength, 64);
Assert.NotNull(HttpWebRequest.DefaultCachePolicy);
Assert.Equal(HttpWebRequest.DefaultCachePolicy.Level, RequestCacheLevel.BypassCache);
Assert.Equal(PlatformDetection.IsFullFramework ? 64 : 0, HttpWebRequest.DefaultMaximumErrorResponseLength);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.Equal(100000, request.Timeout);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")]
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetNegativeOne_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContentLength = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetThenGetOne_Success(Uri remoteServer)
{
const int ContentLength = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentLength = ContentLength;
Assert.Equal(ContentLength, request.ContentLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Fact]
public async Task Headers_SetAfterRequestSubmitted_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
Task<WebResponse> getResponse = request.GetResponseAsync();
await LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (WebResponse response = await getResponse)
{
Assert.Throws<InvalidOperationException>(() => request.AutomaticDecompression = DecompressionMethods.Deflate);
Assert.Throws<InvalidOperationException>(() => request.ContentLength = 255);
Assert.Throws<InvalidOperationException>(() => request.ContinueTimeout = 255);
Assert.Throws<InvalidOperationException>(() => request.Host = "localhost");
Assert.Throws<InvalidOperationException>(() => request.MaximumResponseHeadersLength = 255);
Assert.Throws<InvalidOperationException>(() => request.SendChunked = true);
Assert.Throws<InvalidOperationException>(() => request.Proxy = WebRequest.DefaultWebProxy);
Assert.Throws<InvalidOperationException>(() => request.Headers = null);
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.MaximumResponseHeadersLength = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetThenGetNegativeOne_Success(Uri remoteServer)
{
const int MaximumResponseHeaderLength = -1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumResponseHeadersLength = MaximumResponseHeaderLength;
Assert.Equal(MaximumResponseHeaderLength, request.MaximumResponseHeadersLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetZeroOrNegative_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = 0);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetThenGetOne_Success(Uri remoteServer)
{
const int MaximumAutomaticRedirections = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumAutomaticRedirections = MaximumAutomaticRedirections;
Assert.Equal(MaximumAutomaticRedirections, request.MaximumAutomaticRedirections);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
const int Timeout = 0;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = Timeout;
Assert.Equal(Timeout, request.Timeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void TimeOut_SetThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = 100;
Assert.Equal(100, request.Timeout);
request.Timeout = Threading.Timeout.Infinite;
Assert.Equal(Threading.Timeout.Infinite, request.Timeout);
request.Timeout = int.MaxValue;
Assert.Equal(int.MaxValue, request.Timeout);
}
[Fact]
public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Timeout = 10; // ms.
var sw = Stopwatch.StartNew();
WebException exception = Assert.Throws<WebException>(() => request.GetResponse());
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds, 1, 15 * 1000);
Assert.Equal(WebExceptionStatus.Timeout, exception.Status);
Assert.Equal(null, exception.InnerException);
Assert.Equal(null, exception.Response);
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Address_CtorAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.Address);
}
[Theory, MemberData(nameof(EchoServers))]
public void UserAgent_SetThenGetWindows_ValuesMatch(Uri remoteServer)
{
const string UserAgent = "Windows";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UserAgent = UserAgent;
Assert.Equal(UserAgent, request.UserAgent);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetNullValue_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", null, () => request.Host = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetSlash_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "/localhost");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetInvalidUri_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "NoUri+-*");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUri_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUriWithPort_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost:8080";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_GetDefaultHostSameAsAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer.Host, request.Host);
}
[Theory]
[InlineData("https://microsoft.com:8080")]
public void Host_GetDefaultHostWithCustomPortSameAsAddress_ValuesMatch(string endpoint)
{
Uri endpointUri = new Uri(endpoint);
HttpWebRequest request = WebRequest.CreateHttp(endpointUri);
Assert.Equal(endpointUri.Host + ":" + endpointUri.Port, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Pipelined_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Pipelined = true;
Assert.True(request.Pipelined);
request.Pipelined = false;
Assert.False(request.Pipelined);
}
[Theory, MemberData(nameof(EchoServers))]
public void Referer_SetThenGetReferer_ValuesMatch(Uri remoteServer)
{
const string Referer = "Referer";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Referer = Referer;
Assert.Equal(Referer, request.Referer);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string TransferEncoding = "xml";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
request.TransferEncoding = TransferEncoding;
Assert.Equal(TransferEncoding, request.TransferEncoding);
request.TransferEncoding = null;
Assert.Equal(null, request.TransferEncoding);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetChunked_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.TransferEncoding = "chunked");
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetWithSendChunkedFalse_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<InvalidOperationException>(() => request.TransferEncoding = "xml");
}
[Theory, MemberData(nameof(EchoServers))]
public void KeepAlive_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.KeepAlive = true;
Assert.True(request.KeepAlive);
request.KeepAlive = false;
Assert.False(request.KeepAlive);
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
public void KeepAlive_CorrectConnectionHeaderSent(bool? keepAlive)
{
HttpWebRequest request = WebRequest.CreateHttp(Test.Common.Configuration.Http.RemoteEchoServer);
if (keepAlive.HasValue)
{
request.KeepAlive = keepAlive.Value;
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var body = new StreamReader(response.GetResponseStream()))
{
string content = body.ReadToEnd();
if (!keepAlive.HasValue || keepAlive.Value)
{
// Validate that the request doesn't contain Connection: "close", but we can't validate
// that it does contain Connection: "keep-alive", as that's optional as of HTTP 1.1.
Assert.DoesNotContain("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
}
else
{
Assert.Contains("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("\"Keep-Alive\"", content, StringComparison.OrdinalIgnoreCase);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public void AutomaticDecompression_SetAndGetDeflate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AutomaticDecompression = DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.Deflate, request.AutomaticDecompression);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowWriteStreamBuffering_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowWriteStreamBuffering = true;
Assert.True(request.AllowWriteStreamBuffering);
request.AllowWriteStreamBuffering = false;
Assert.False(request.AllowWriteStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowAutoRedirect_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowAutoRedirect = true;
Assert.True(request.AllowAutoRedirect);
request.AllowAutoRedirect = false;
Assert.False(request.AllowAutoRedirect);
}
[Fact]
public void ConnectionGroupName_SetAndGetGroup_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Null(request.ConnectionGroupName);
request.ConnectionGroupName = "Group";
Assert.Equal("Group", request.ConnectionGroupName);
}
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
Assert.True(request.PreAuthenticate);
request.PreAuthenticate = false;
Assert.False(request.PreAuthenticate);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBooleanResponse_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
using (var response = (HttpWebResponse)request.GetResponse())
{
Assert.True(request.PreAuthenticate);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Connection = "connect";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Connection = Connection;
Assert.Equal(Connection, request.Connection);
request.Connection = null;
Assert.Equal(null, request.Connection);
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_SetKeepAliveAndClose_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "keep-alive");
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "close");
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_SetNullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Expect = "101-go";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Expect = Expect;
Assert.Equal(Expect, request.Expect);
request.Expect = null;
Assert.Equal(null, request.Expect);
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_Set100Continue_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Expect = "100-continue");
}
[ActiveIssue(20136, TargetFrameworkMonikers.Uap)]
[Fact]
public void DefaultMaximumResponseHeadersLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
const int NewDefaultMaximumResponseHeadersLength = 255;
try
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = NewDefaultMaximumResponseHeadersLength;
Assert.Equal(NewDefaultMaximumResponseHeadersLength, HttpWebRequest.DefaultMaximumResponseHeadersLength);
}
finally
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength;
}
return SuccessExitCode;
}).Dispose();
}
[ActiveIssue(20136, TargetFrameworkMonikers.Uap)]
[Fact]
public void DefaultMaximumErrorResponseLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumErrorsResponseLength = HttpWebRequest.DefaultMaximumErrorResponseLength;
const int NewDefaultMaximumErrorsResponseLength = 255;
try
{
HttpWebRequest.DefaultMaximumErrorResponseLength = NewDefaultMaximumErrorsResponseLength;
Assert.Equal(NewDefaultMaximumErrorsResponseLength, HttpWebRequest.DefaultMaximumErrorResponseLength);
}
finally
{
HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength;
}
return SuccessExitCode;
}).Dispose();
}
[ActiveIssue(20136, TargetFrameworkMonikers.Uap)]
[Fact]
public void DefaultCachePolicy_SetAndGetPolicyReload_ValuesMatch()
{
RemoteInvoke(() =>
{
RequestCachePolicy requestCachePolicy = HttpWebRequest.DefaultCachePolicy;
try
{
RequestCachePolicy newRequestCachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
HttpWebRequest.DefaultCachePolicy = newRequestCachePolicy;
Assert.Equal(newRequestCachePolicy.Level, HttpWebRequest.DefaultCachePolicy.Level);
}
finally
{
HttpWebRequest.DefaultCachePolicy = requestCachePolicy;
}
return SuccessExitCode;
}).Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void IfModifiedSince_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newIfModifiedSince = new DateTime(2000, 1, 1);
request.IfModifiedSince = newIfModifiedSince;
Assert.Equal(newIfModifiedSince, request.IfModifiedSince);
DateTime ifModifiedSince = DateTime.MinValue;
request.IfModifiedSince = ifModifiedSince;
Assert.Equal(ifModifiedSince, request.IfModifiedSince);
}
[Theory, MemberData(nameof(EchoServers))]
public void Date_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newDate = new DateTime(2000, 1, 1);
request.Date = newDate;
Assert.Equal(newDate, request.Date);
DateTime date = DateTime.MinValue;
request.Date = date;
Assert.Equal(date, request.Date);
}
[Theory, MemberData(nameof(EchoServers))]
public void SendChunked_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
Assert.True(request.SendChunked);
request.SendChunked = false;
Assert.False(request.SendChunked);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetNullDelegate_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueDelegate = null;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetDelegateThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpContinueDelegate continueDelegate = new HttpContinueDelegate((a, b) => { });
request.ContinueDelegate = continueDelegate;
Assert.Same(continueDelegate, request.ContinueDelegate);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServicePoint_GetValue_ExpectedResult(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(request.ServicePoint);
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => request.ServicePoint);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ServerCertificateValidationCallback_SetCallbackThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var serverCertificateVallidationCallback = new Security.RemoteCertificateValidationCallback((a, b, c, d) => true);
request.ServerCertificateValidationCallback = serverCertificateVallidationCallback;
Assert.Same(serverCertificateVallidationCallback, request.ServerCertificateValidationCallback);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetNullX509_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", () => request.ClientCertificates = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetThenGetX509_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var certificateCollection = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
request.ClientCertificates = certificateCollection;
Assert.Same(certificateCollection, request.ClientCertificates);
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetInvalidHttpVersion_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.ProtocolVersion = new Version());
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetThenGetHttpVersions_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ProtocolVersion = HttpVersion.Version10;
Assert.Equal(HttpVersion.Version10, request.ProtocolVersion);
request.ProtocolVersion = HttpVersion.Version11;
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
}
[Fact]
public void ReadWriteTimeout_SetThenGet_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = 5;
Assert.Equal(5, request.ReadWriteTimeout);
}
[Fact]
public void ReadWriteTimeout_InfiniteValue_Ok()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = Timeout.Infinite;
}
[Fact]
public void ReadWriteTimeout_NegativeOrZeroValue_Fail()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = -10; });
}
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_SetThenGetContainer_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.CookieContainer = null;
var cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
Assert.Same(cookieContainer, request.CookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[OuterLoop]
[Theory]
[MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetGetResponse_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
response.Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = "POST";
IAsyncResult asyncResult = request.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
public async Task BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() => request.BeginGetResponse(null, null));
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
Assert.Throws<ArgumentException>(() => new StreamReader(requestStream));
}
});
}
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
Assert.NotNull(requestStream);
}
});
}
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.NotNull(response.GetResponseStream());
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
{
Assert.NotNull(myStream);
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\""));
}
}
}
[OuterLoop]
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_Count_Add(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime now = DateTime.UtcNow;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(remoteServer, new Cookie("1", "cookie1"));
request.CookieContainer.Add(remoteServer, new Cookie("2", "cookie2"));
Assert.True(request.SupportsCookieContainer);
Assert.Equal(request.CookieContainer.GetCookies(remoteServer).Count, 2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Range_Add_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AddRange(1, 5);
Assert.Equal(request.Headers["Range"], "bytes=1-5");
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains(RequestBody));
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
var response = await request.GetResponseAsync();
response.Dispose();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public async Task GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
public static object[][] StatusCodeServers = {
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) },
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) },
};
[Theory, MemberData(nameof(StatusCodeServers))]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.True(request.HaveResponse);
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
string headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = string.Empty);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = "Method(2");
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.Equal(remoteServer, response.ResponseUri);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
const string ContentType = "text/plain; charset=utf-8";
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains($"\"Content-Type\": \"{ContentType}\""));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void MediaType_SetThenGet_ValuesMatch(Uri remoteServer)
{
const string MediaType = "text/plain";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MediaType = MediaType;
Assert.Equal(MediaType, request.MediaType);
}
public async Task HttpWebRequest_EndGetRequestStreamContext_ExpectedValue()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
System.Net.TransportContext context;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
using (request.EndGetRequestStream(request.BeginGetRequestStream(null, null), out context))
{
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(context);
}
else
{
Assert.Null(context);
}
}
return Task.FromResult<object>(null);
});
}
[ActiveIssue(19083)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19083")]
[Fact]
public async Task Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state);
request.Abort();
Assert.Equal(1, state.RequestStreamCallbackCallCount);
WebException wex = state.SavedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
Assert.Equal(1, state.ResponseCallbackCallCount);
return Task.FromResult<object>(null);
});
}
[ActiveIssue(18800)]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
WebException wex = state.SavedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[Fact]
public async Task Abort_BeginGetResponseUsingNoCallbackThenAbort_Success()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.BeginGetResponse(null, null);
request.Abort();
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.RequestStreamCallbackCallCount++;
try
{
HttpWebRequest request = state.Request;
state.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream stream = request.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
state.SavedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.ResponseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(asynchronousResult))
{
state.SavedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
state.SavedResponseException = ex;
}
}
[Fact]
public void HttpWebRequest_Serialize_Fails()
{
using (MemoryStream fs = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
var hwr = HttpWebRequest.CreateHttp("http://localhost");
// .NET Framework throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
// While .NET Core throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.HttpWebRequest' in Assembly 'System.Net.Requests, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr));
}
}
}
public class RequestState
{
public HttpWebRequest Request;
public HttpWebResponse Response;
public WebHeaderCollection SavedResponseHeaders;
public int RequestStreamCallbackCallCount;
public int ResponseCallbackCallCount;
public Exception SavedRequestStreamException;
public Exception SavedResponseException;
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.MatLab.MatLab
File: EventArgs.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.MatLab
{
using System;
using System.Collections.Generic;
using System.Linq;
using StockSharp.BusinessEntities;
/// <summary>
/// Argument which contains an error information.
/// </summary>
public class ErrorEventArgs : EventArgs
{
internal ErrorEventArgs(Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
Error = error;
}
/// <summary>
/// Error info.
/// </summary>
public Exception Error { get; private set; }
}
/// <summary>
/// Argument which contains instruments.
/// </summary>
public class SecuritiesEventArgs : EventArgs
{
internal SecuritiesEventArgs(IEnumerable<Security> securities)
{
if (securities == null)
throw new ArgumentNullException(nameof(securities));
Securities = securities.ToArray();
}
/// <summary>
/// Securities.
/// </summary>
public Security[] Securities { get; private set; }
}
/// <summary>
/// Argument which contains orders.
/// </summary>
public class OrdersEventArgs : EventArgs
{
internal OrdersEventArgs(IEnumerable<Order> orders)
{
if (orders == null)
throw new ArgumentNullException(nameof(orders));
Orders = orders.ToArray();
}
/// <summary>
/// Orders.
/// </summary>
public Order[] Orders { get; private set; }
}
/// <summary>
/// Argument which contains order errors (registration or cancellation).
/// </summary>
public class OrderFailsEventArgs : EventArgs
{
internal OrderFailsEventArgs(IEnumerable<OrderFail> orderFails)
{
if (orderFails == null)
throw new ArgumentNullException(nameof(orderFails));
OrderFails = orderFails.ToArray();
}
/// <summary>
/// Errors.
/// </summary>
public OrderFail[] OrderFails { get; private set; }
}
/// <summary>
/// Argument which contains tick teades.
/// </summary>
public class TradesEventArgs : EventArgs
{
internal TradesEventArgs(IEnumerable<Trade> trades)
{
if (trades == null)
throw new ArgumentNullException(nameof(trades));
Trades = trades.ToArray();
}
/// <summary>
/// Trades.
/// </summary>
public Trade[] Trades { get; private set; }
}
/// <summary>
/// Argument which contains own trades.
/// </summary>
public class MyTradesEventArgs : EventArgs
{
internal MyTradesEventArgs(IEnumerable<MyTrade> trades)
{
if (trades == null)
throw new ArgumentNullException(nameof(trades));
Trades = trades.ToArray();
}
/// <summary>
/// Trades.
/// </summary>
public MyTrade[] Trades { get; private set; }
}
/// <summary>
/// Argument which contains portfolios.
/// </summary>
public class PortfoliosEventArgs : EventArgs
{
internal PortfoliosEventArgs(IEnumerable<Portfolio> portfolios)
{
if (portfolios == null)
throw new ArgumentNullException(nameof(portfolios));
Portfolios = portfolios.ToArray();
}
/// <summary>
/// Portfolios.
/// </summary>
public Portfolio[] Portfolios { get; private set; }
}
/// <summary>
/// Argument which contains positions.
/// </summary>
public class PositionsEventArgs : EventArgs
{
internal PositionsEventArgs(IEnumerable<Position> positions)
{
if (positions == null)
throw new ArgumentNullException(nameof(positions));
Positions = positions.ToArray();
}
/// <summary>
/// Positions.
/// </summary>
public Position[] Positions { get; private set; }
}
/// <summary>
/// Argument which contains order books.
/// </summary>
public class MarketDepthsEventArgs : EventArgs
{
internal MarketDepthsEventArgs(IEnumerable<MarketDepth> depths)
{
if (depths == null)
throw new ArgumentNullException(nameof(depths));
Depths = depths.ToArray();
}
/// <summary>
/// Market depths.
/// </summary>
public MarketDepth[] Depths { get; private set; }
}
/// <summary>
/// Argument which contains order logs.
/// </summary>
public class OrderLogItemsEventArg : EventArgs
{
internal OrderLogItemsEventArg(IEnumerable<OrderLogItem> items)
{
if (items == null)
throw new ArgumentNullException(nameof(items));
Items = items.ToArray();
}
/// <summary>
/// Order log.
/// </summary>
public OrderLogItem[] Items { get; private set; }
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace HoneycombRush
{
/// <summary>
/// This is the class the handle the entire game
/// </summary>
public class GameplayScreen : GameScreen
{
#region Fields/Properties
SpriteFont font16px;
SpriteFont font36px;
Texture2D arrowTexture;
Texture2D background;
Texture2D controlstickBoundry;
Texture2D controlstick;
Texture2D beehiveTexture;
Texture2D smokeButton;
ScoreBar smokeButtonScorebar;
Vector2 controlstickStratupPosition;
Vector2 controlstickBoundryPosition;
Vector2 smokeButtonPosition;
Vector2 lastTouchPosition;
bool isSmokebuttonClicked;
bool drawArrow;
bool drawArrowInInterval;
bool isInMotion;
bool isLevelEnd;
Dictionary<string, Animation> animations;
int amountOfSoldierBee;
int amountOfWorkerBee;
int arrowCounter;
List<Beehive> beehives = new List<Beehive>();
List<Bee> bees = new List<Bee>();
const string SmokeText = "Smoke";
TimeSpan gameElapsed;
BeeKeeper beeKeeper;
HoneyJar jar;
Vat vat;
DifficultyMode gameDifficultyLevel;
private bool IsInMotion
{
get
{
return isInMotion;
}
set
{
isInMotion = value;
if (beeKeeper != null)
{
beeKeeper.IsInMotion = isInMotion;
}
}
}
#endregion
#region Initializations
/// <summary>
/// Creates a new gameplay screen.
/// </summary>
/// <param name="gameDifficultyMode">The desired game difficulty.</param>
public GameplayScreen(DifficultyMode gameDifficultyMode)
{
TransitionOnTime = TimeSpan.FromSeconds(0.0);
TransitionOffTime = TimeSpan.FromSeconds(0.0);
//Loads configuration
ConfigurationManager.LoadConfiguration(XDocument.Load("Content/Configuration/Configuration.xml"));
ConfigurationManager.DifficultyMode = gameDifficultyMode;
gameDifficultyLevel = gameDifficultyMode;
gameElapsed = ConfigurationManager.ModesConfiguration[gameDifficultyLevel].GameElapsed;
amountOfSoldierBee = 4;
amountOfWorkerBee = 16;
controlstickBoundryPosition = new Vector2(34, 347);
smokeButtonPosition = new Vector2(664, 346);
controlstickStratupPosition = new Vector2(55, 369);
IsInMotion = false;
isLevelEnd = false;
EnabledGestures = GestureType.Tap;
}
#endregion
#region Loading and Unloading
/// <summary>
/// Load the game content
/// </summary>
public override void LoadContent()
{
LoadAssets();
base.LoadContent();
}
/// <summary>
/// Loads content and assets.
/// </summary>
public void LoadAssets()
{
// Loads the animation dictionary from an xml file
animations = new Dictionary<string, Animation>();
LoadAnimiationFromXML();
// Loads all textures that are required
LoadTextures();
// Create all game components
CreateGameComponents();
}
/// <summary>
/// Unloads game components which are no longer needed once the game ends.
/// </summary>
public override void UnloadContent()
{
var componentList = ScreenManager.Game.Components;
for (int index = 0; index < componentList.Count; index++)
{
if (componentList[index] != this && componentList[index] != ScreenManager &&
!(componentList[index] is AudioManager))
{
componentList.RemoveAt(index);
index--;
}
}
base.UnloadContent();
}
#endregion
#region Update
/// <summary>
/// Handle the player's input.
/// </summary>
/// <param name="input"></param>
public override void HandleInput(GameTime gameTime, InputState input)
{
if (IsActive)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
VirtualThumbsticks.Update(input);
}
if (input.TouchState.Count > 0)
{
foreach (TouchLocation touch in input.TouchState)
{
lastTouchPosition = touch.Position;
}
}
isSmokebuttonClicked = false;
PlayerIndex player;
// If there was any touch
if (VirtualThumbsticks.RightThumbstickCenter.HasValue)
{
// Button Bounds
Rectangle buttonRectangle = new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y,
smokeButton.Width / 2, smokeButton.Height);
// Touch Bounds
Rectangle touchRectangle = new Rectangle((int)VirtualThumbsticks.RightThumbstickCenter.Value.X,
(int)VirtualThumbsticks.RightThumbstickCenter.Value.Y,
1, 1);
// If the touch is in the button
if (buttonRectangle.Contains(touchRectangle) && !beeKeeper.IsCollectingHoney && !beeKeeper.IsStung)
{
isSmokebuttonClicked = true;
}
}
if (input.IsKeyDown(Keys.Space, ControllingPlayer, out player) && !beeKeeper.IsCollectingHoney &&
!beeKeeper.IsStung)
{
isSmokebuttonClicked = true;
}
if (input.Gestures.Count > 0)
{
if (isLevelEnd)
{
if (input.Gestures[0].GestureType == GestureType.Tap)
{
ScreenManager.RemoveScreen(this);
ScreenManager.AddScreen(new GameplayScreen(DifficultyMode.Easy), null);
}
}
}
}
/// <summary>
/// Perform the game's update logic.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="otherScreenHasFocus">Whether or not another screen currently has the focus.</param>
/// <param name="coveredByOtherScreen">Whether or not this screen is covered by another.</param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
gameElapsed -= gameTime.ElapsedGameTime;
if (vat.CurrentVatCapacity >= vat.MaxVatCapacity || gameElapsed <= TimeSpan.Zero)
{
isLevelEnd = true;
}
if (isLevelEnd)
{
return;
}
// Update the time remaining displayed by the vat
vat.DrawTimeLeft(gameElapsed);
// If active and running handle all game component
if (!IsActive)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
return;
}
HandleThumbStick();
HandleSmoke();
beeKeeper.SetDirection(VirtualThumbsticks.LeftThumbstick);
HandleCollision(gameTime);
HandleVatHoneyArrow();
beeKeeper.DrawOrder = 1;
int beeKeeperY = (int)(beeKeeper.Position.Y + beeKeeper.Bounds.Height - 2);
// We want to determine the draw order of the beekeeper,
// if the beekeeper is under half the height of the beehive
// it should be drawn over the beehive.
foreach (Beehive beehive in beehives)
{
if (beeKeeperY > beehive.Bounds.Y)
{
if (beehive.Bounds.Y + beehive.Bounds.Height / 2 < beeKeeperY)
{
beeKeeper.DrawOrder = Math.Max(beeKeeper.DrawOrder, beehive.Bounds.Y + 1);
}
}
}
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
#endregion
#region Render
/// <summary>
/// Draw the game screen.
/// </summary>
/// <param name="gameTime">Game time information.</param>
public override void Draw(GameTime gameTime)
{
ScreenManager.SpriteBatch.Begin();
// Draw the background
ScreenManager.SpriteBatch.Draw(background,
new Rectangle(0, 0, ScreenManager.Game.GraphicsDevice.Viewport.Width,
ScreenManager.Game.GraphicsDevice.Viewport.Height),
null, Color.White, 0f, Vector2.Zero, SpriteEffects.None, 1);
if (IsActive)
{
DrawSmokeButton();
ScreenManager.SpriteBatch.Draw(controlstickBoundry, controlstickBoundryPosition, Color.White);
ScreenManager.SpriteBatch.Draw(controlstick, controlstickStratupPosition, Color.White);
ScreenManager.SpriteBatch.DrawString(font16px, SmokeText, new Vector2(684, 456), Color.White);
DrawVatHoneyArrow();
}
DrawLevelEndIfNessecry();
ScreenManager.SpriteBatch.End();
base.Draw(gameTime);
}
#endregion
#region Private Methods
/// <summary>
/// If the level is over, draws text describing the level's outocme.
/// </summary>
private void DrawLevelEndIfNessecry()
{
if (isLevelEnd)
{
string stringToDisplay = "Game Over";
var stringVector = font36px.MeasureString(stringToDisplay);
ScreenManager.SpriteBatch.DrawString(font36px, stringToDisplay,
new Vector2(ScreenManager.GraphicsDevice.Viewport.Width / 2 - stringVector.X / 2,
ScreenManager.GraphicsDevice.Viewport.Height / 2 - stringVector.Y / 2),
Color.White);
}
}
/// <summary>
/// Loads animation setting from xml file.
/// </summary>
private void LoadAnimiationFromXML()
{
XDocument doc = XDocument.Load("Content/Textures/AnimationsDefinition.xml");
XName name = XName.Get("Definition");
var definitions = doc.Document.Descendants(name);
// Loop over all definitions in the XML
foreach (var animationDefinition in definitions)
{
// Get the name of the animation
string animatonAlias = animationDefinition.Attribute("Alias").Value;
Texture2D texture =
ScreenManager.Game.Content.Load<Texture2D>(animationDefinition.Attribute("SheetName").Value);
// Get the frame size (width & height)
Point frameSize = new Point();
frameSize.X = int.Parse(animationDefinition.Attribute("FrameWidth").Value);
frameSize.Y = int.Parse(animationDefinition.Attribute("FrameHeight").Value);
// Get the frames sheet dimensions
Point sheetSize = new Point();
sheetSize.X = int.Parse(animationDefinition.Attribute("SheetColumns").Value);
sheetSize.Y = int.Parse(animationDefinition.Attribute("SheetRows").Value);
Animation animation = new Animation(texture, frameSize, sheetSize);
// Checks for sub-animation definition
if (animationDefinition.Element("SubDefinition") != null)
{
int startFrame = int.Parse(
animationDefinition.Element("SubDefinition").Attribute("StartFrame").Value);
int endFrame = int.Parse
(animationDefinition.Element("SubDefinition").Attribute("EndFrame").Value);
animation.SetSubAnimation(startFrame, endFrame);
}
if (animationDefinition.Attribute("Speed") != null)
{
animation.SetFrameInvterval(TimeSpan.FromMilliseconds(
double.Parse(animationDefinition.Attribute("Speed").Value)));
}
// If the definition has an offset defined - it should be
// rendered relative to some element/animation
if (null != animationDefinition.Attribute("OffsetX") &&
null != animationDefinition.Attribute("OffsetY"))
{
animation.Offset = new Vector2(int.Parse(animationDefinition.Attribute("OffsetX").Value),
int.Parse(animationDefinition.Attribute("OffsetY").Value));
}
animations.Add(animatonAlias, animation);
}
}
/// <summary>
/// Create all the game components.
/// </summary>
private void CreateGameComponents()
{
ScoreBar scoreBar = new ScoreBar(ScreenManager.Game, 0, 100, new Vector2(8, 65), 10, 70, Color.Blue,
ScoreBar.ScoreBarOrientation.Horizontal, 0, this, true);
ScreenManager.Game.Components.Add(scoreBar);
// Create the honey jar
jar = new HoneyJar(ScreenManager.Game, this, new Vector2(20, 8), scoreBar);
ScreenManager.Game.Components.Add(jar);
// Create all the beehives and the bees
CreateBeehives();
// Create the smoke gun's score bar
int totalSmokeAmount = ConfigurationManager.ModesConfiguration[gameDifficultyLevel].TotalSmokeAmount;
Vector2 smokeButtonPosition = new Vector2(664, 346) + new Vector2(22, smokeButton.Height - 8);
smokeButtonScorebar = new ScoreBar(ScreenManager.Game, 0, totalSmokeAmount, smokeButtonPosition, 12, 70,
Color.White, ScoreBar.ScoreBarOrientation.Horizontal, totalSmokeAmount, this, false);
ScreenManager.Game.Components.Add(smokeButtonScorebar);
// Creates the BeeKeeper
beeKeeper = new BeeKeeper(ScreenManager.Game, this);
beeKeeper.AnimationDefinitions = animations;
beeKeeper.ThumbStickArea =
new Rectangle((int)controlstickBoundryPosition.X, (int)controlstickBoundryPosition.Y,
controlstickBoundry.Width, controlstickBoundry.Height);
ScreenManager.Game.Components.Add(beeKeeper);
// Create the vat's score bar
scoreBar = new ScoreBar(ScreenManager.Game, 0, 300, new Vector2(306, 440), 10, 190, Color.White,
ScoreBar.ScoreBarOrientation.Horizontal, 0, this, true);
ScreenManager.Game.Components.Add(scoreBar);
// Create the vat
vat = new Vat(ScreenManager.Game, this, ScreenManager.Game.Content.Load<Texture2D>("Textures/vat"),
new Vector2(294, 355), scoreBar);
ScreenManager.Game.Components.Add(vat);
scoreBar.DrawOrder = vat.DrawOrder + 1;
}
/// <summary>
/// Creates all the beehives and bees.
/// </summary>
private void CreateBeehives()
{
// Init position parameters
Vector2 scorebarPosition = new Vector2(18, beehiveTexture.Height - 15);
Vector2[] beehivePositions =
new Vector2[5]
{
new Vector2(83, 8),
new Vector2(347, 8),
new Vector2(661, 8),
new Vector2(83, 201),
new Vector2(661, 201)
};
// Create the beehives
for (int beehiveCounter = 0; beehiveCounter < beehivePositions.Length; beehiveCounter++)
{
ScoreBar scoreBar = new ScoreBar(ScreenManager.Game, 0, 100, beehivePositions[beehiveCounter] +
scorebarPosition, 10, 68, Color.Green, ScoreBar.ScoreBarOrientation.Horizontal, 100, this, false);
ScreenManager.Game.Components.Add(scoreBar);
Beehive beehive =
new Beehive(ScreenManager.Game, this, beehiveTexture, scoreBar, beehivePositions[beehiveCounter]);
beehive.AnimationDefinitions = animations;
ScreenManager.Game.Components.Add(beehive);
beehives.Add(beehive);
scoreBar.DrawOrder = beehive.DrawOrder;
}
for (int beehiveIndex = 0; beehiveIndex < beehivePositions.Length; beehiveIndex++)
{
// Create the Soldier bees
for (int SoldierBeeCounter = 0; SoldierBeeCounter < amountOfSoldierBee; SoldierBeeCounter++)
{
SoldierBee bee = new SoldierBee(ScreenManager.Game, this, beehives[beehiveIndex]);
bee.AnimationDefinitions = animations;
ScreenManager.Game.Components.Add(bee);
bees.Add(bee);
}
// Creates the worker bees
for (int workerBeeCounter = 0; workerBeeCounter < amountOfWorkerBee; workerBeeCounter++)
{
WorkerBee bee = new WorkerBee(ScreenManager.Game, this, beehives[beehiveIndex]);
bee.AnimationDefinitions = animations;
ScreenManager.Game.Components.Add(bee);
bees.Add(bee);
}
}
}
/// <summary>
/// Loads all the necessary textures.
/// </summary>
private void LoadTextures()
{
beehiveTexture = ScreenManager.Game.Content.Load<Texture2D>("Textures/beehive");
background = ScreenManager.Game.Content.Load<Texture2D>("Textures/Backgrounds/GamePlayBackground");
controlstickBoundry = ScreenManager.Game.Content.Load<Texture2D>("Textures/controlstickBoundary");
controlstick = ScreenManager.Game.Content.Load<Texture2D>("Textures/controlstick");
smokeButton = ScreenManager.Game.Content.Load<Texture2D>("Textures/smokeBtn");
font16px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont16px");
arrowTexture = ScreenManager.Game.Content.Load<Texture2D>("Textures/arrow");
font16px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont16px");
font36px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont36px");
}
/// <summary>
/// Handle thumbstick logic
/// </summary>
private void HandleThumbStick()
{
// Calculate the rectangle of the outer circle of the thumbstick
Rectangle outerControlstick = new Rectangle(0, (int)controlstickBoundryPosition.Y - 35,
controlstickBoundry.Width + 60, controlstickBoundry.Height + 60);
// Reset the thumbstick position when it is idle
if (VirtualThumbsticks.LeftThumbstick == Vector2.Zero)
{
IsInMotion = false;
beeKeeper.SetMovement(Vector2.Zero);
controlstickStratupPosition = new Vector2(55, 369);
}
else
{
// If not in motion and the touch point is not in the control bounds - there is no movement
Rectangle touchRectangle = new Rectangle((int)lastTouchPosition.X, (int)lastTouchPosition.Y, 1, 1);
if (!outerControlstick.Contains(touchRectangle))
{
controlstickStratupPosition = new Vector2(55, 369);
IsInMotion = false;
return;
}
// Move the beekeeper
SetMotion();
// Moves the thumbstick's inner circle
float radious = controlstick.Width / 2 + 35;
controlstickStratupPosition = new Vector2(55, 369) + (VirtualThumbsticks.LeftThumbstick * radious);
}
}
/// <summary>
/// Moves the beekeeper.
/// </summary>
private void SetMotion()
{
// Calculate the beekeeper's location
Vector2 leftThumbstick = Vector2.Zero;
leftThumbstick = VirtualThumbsticks.LeftThumbstick;
Vector2 tempVector = beeKeeper.Position + leftThumbstick * 12f;
if (tempVector.X < 0 ||
tempVector.X + beeKeeper.Bounds.Width > ScreenManager.GraphicsDevice.Viewport.Width)
{
leftThumbstick.X = 0;
}
if (tempVector.Y < 0 ||
tempVector.Y + beeKeeper.Bounds.Height > ScreenManager.GraphicsDevice.Viewport.Height)
{
leftThumbstick.Y = 0;
}
if (leftThumbstick == Vector2.Zero)
{
isInMotion = false;
}
else
{
Vector2 beekeeperCalculatedPosition =
new Vector2(beeKeeper.CentralCollisionArea.X, beeKeeper.CentralCollisionArea.Y) +
leftThumbstick * 12;
if (!CheckBeehiveCollision(beekeeperCalculatedPosition))
{
beeKeeper.SetMovement(leftThumbstick * 12f);
IsInMotion = true;
}
}
}
/// <summary>
/// Checks if the beekeeper collides with a beehive.
/// </summary>
/// <param name="beekeeperPosition">The beekeeper's position.</param>
/// <returns>True if the beekeeper collides with a beehive and false otherwise.</returns>
private bool CheckBeehiveCollision(Vector2 beekeeperPosition)
{
// We do not use the beekeeper's collision area property as he has not actually moved at this point and
// is still in his previous position
Rectangle beekeeperTempCollisionArea = new Rectangle((int)beekeeperPosition.X, (int)beekeeperPosition.Y,
beeKeeper.CentralCollisionArea.Width, beeKeeper.CentralCollisionArea.Height);
foreach (Beehive currentBeehive in beehives)
{
if (beekeeperTempCollisionArea.Intersects(currentBeehive.CentralCollisionArea))
{
return true;
}
}
return false;
}
/// <summary>
/// Check for any of the possible collisions.
/// </summary>
/// <param name="gameTime">Game time information.</param>
private void HandleCollision(GameTime gameTime)
{
bool isCollectiongHoney = HandleBeeKeeperBeehiveCollision();
HandleSmokeBeehiveCollision();
bool hasCollisionWithVat = HandleVatCollision();
HandleBeeInteractions(gameTime, hasCollisionWithVat, isCollectiongHoney);
}
/// <summary>
/// Handle the interaction of the bees with other game components.
/// </summary>
/// <param name="gameTime">Game time information.</param>
private void HandleBeeInteractions(GameTime gameTime, bool isBeeKeeperCollideWithVat,
bool isBeeKeeperCollideWithBeehive)
{
// Goes over all the bees
foreach (Bee bee in bees)
{
// Check for smoke collisions
SmokePuff intersectingPuff = beeKeeper.CheckSmokeCollision(bee.Bounds);
if (intersectingPuff != null)
{
bee.HitBySmoke(intersectingPuff);
}
// Check for vat collision
if (vat.Bounds.HasCollision(bee.Bounds))
{
bee.Collide(vat.Bounds);
}
// Check for beekeeper collision
if (beeKeeper.Bounds.HasCollision(bee.Bounds))
{
if (!bee.IsBeeHit && !isBeeKeeperCollideWithVat && !beeKeeper.IsStung && !beeKeeper.IsFlashing &&
!isBeeKeeperCollideWithBeehive)
{
jar.DecreaseHoneyByPercent(20);
beeKeeper.Stung(gameTime.TotalGameTime);
}
bee.Collide(beeKeeper.Bounds);
}
// Soldier bee chase logic
if (bee is SoldierBee)
{
SoldierBee SoldierBee = bee as SoldierBee;
SoldierBee.DistanceFromBeeKeeper =
(Vector2.Distance(beeKeeper.Bounds.GetVector(), SoldierBee.Bounds.GetVector()));
SoldierBee.BeeKeeperVector = beeKeeper.Bounds.GetVector() - SoldierBee.Bounds.GetVector();
}
}
}
/// <summary>
/// Handle the beekeeper's collision with the vat component.
/// </summary>
/// <returns>True if the beekeeper collides with the vat and false otherwise.</returns>
private bool HandleVatCollision()
{
if (beeKeeper.Bounds.HasCollision(vat.VatDepositArea))
{
if (jar.HasHoney && !beeKeeper.IsStung && !beeKeeper.IsDepostingHoney &&
VirtualThumbsticks.LeftThumbstick == Vector2.Zero)
{
beeKeeper.StartTransferHoney(4, EndHoneyDeposit);
}
return true;
}
beeKeeper.EndTransferHoney();
return false;
}
/// <summary>
/// Handler for finalizing the honey deposit to the vat.
/// </summary>
/// <param name="result"></param>
public void EndHoneyDeposit(IAsyncResult result)
{
int HoneyAmount = jar.DecreaseHoneyByPercent(100);
vat.IncreaseHoney(HoneyAmount);
}
/// <summary>
/// Handle the beekeeper's collision with beehive components.
/// </summary>
/// <returns>True if the beekeeper collides with a beehive and false otherwise.</returns>
/// <remarks>This method is also responsible for allowing bees to regenerate when the beekeeper is not
/// intersecting with a specific hive.</remarks>
private bool HandleBeeKeeperBeehiveCollision()
{
bool isCollidingWithBeehive = false;
Beehive collidedBeehive = null;
// Goes over all the beehives
foreach (Beehive beehive in beehives)
{
// If the beekeeper intersects with the beehive
if (beeKeeper.Bounds.HasCollision(beehive.Bounds))
{
if (VirtualThumbsticks.LeftThumbstick == Vector2.Zero)
{
collidedBeehive = beehive;
isCollidingWithBeehive = true;
}
}
else
{
beehive.AllowBeesToGenerate = true;
}
}
if (collidedBeehive != null)
{
// The beehive has honey, the jar can carry more honey, and the beekeeper is not stung
if (collidedBeehive.HasHoney && jar.CanCarryMore && !beeKeeper.IsStung)
{
// Take honey from the beehive and put it in the jar
collidedBeehive.DecreaseHoney(1);
jar.IncreaseHoney(1);
beeKeeper.IsCollectingHoney = true;
}
else
{
beeKeeper.IsCollectingHoney = false;
}
// Bees are not allowed to regenerate while the beekeeper is colliding with their beehive
isCollidingWithBeehive = true;
collidedBeehive.AllowBeesToGenerate = false;
}
else
{
beeKeeper.IsCollectingHoney = false;
}
return isCollidingWithBeehive;
}
/// <summary>
/// Handle the smoke puff collision with beehive components.
/// </summary>
/// <remarks>Only disables bee regeneration, as it assumes that it will be enabled by
/// <see cref="HandleBeeKeeperBeehiveCollision"/></remarks>
private void HandleSmokeBeehiveCollision()
{
foreach (Beehive beehive in beehives)
{
foreach (SmokePuff smokePuff in beeKeeper.FiredSmokePuffs)
{
if (beehive.Bounds.HasCollision(smokePuff.CentralCollisionArea))
{
beehive.AllowBeesToGenerate = false;
}
}
}
}
/// <summary>
/// Sets an internal value which determines whether or not to display an arrow above the vat.
/// </summary>
private void HandleVatHoneyArrow()
{
if (jar.HasHoney)
{
drawArrow = true;
}
else
{
drawArrow = false;
}
}
/// <summary>
/// Handle smoke logic.
/// </summary>
private void HandleSmoke()
{
// If not currently shooting, refill the gun
if (!isSmokebuttonClicked)
{
smokeButtonScorebar.IncreaseCurrentValue(
ConfigurationManager.ModesConfiguration[gameDifficultyLevel].IncreaseAmountSpeed);
beeKeeper.IsShootingSmoke = false;
}
else
{
// Check that the gun is not empty
if (smokeButtonScorebar.CurrentValue <= smokeButtonScorebar.MinValue)
{
beeKeeper.IsShootingSmoke = false;
}
else
{
beeKeeper.IsShootingSmoke = true;
smokeButtonScorebar.DecreaseCurrentValue(
ConfigurationManager.ModesConfiguration[gameDifficultyLevel].DecreaseAmountSpeed);
}
}
}
/// <summary>
/// Draws the arrow in intervals of 20 game update loops.
/// </summary>
private void DrawVatHoneyArrow()
{
// If the arrow needs to be drawn, and it is not invisible during the current interval
if (drawArrow && drawArrowInInterval)
{
ScreenManager.SpriteBatch.Draw(arrowTexture, new Vector2(370, 314), Color.White);
if (arrowCounter == 20)
{
drawArrowInInterval = false;
arrowCounter = 0;
}
arrowCounter++;
}
else
{
if (arrowCounter == 20)
{
drawArrowInInterval = true;
arrowCounter = 0;
}
arrowCounter++;
}
}
/// <summary>
/// Draws the smoke button.
/// </summary>
private void DrawSmokeButton()
{
if (isSmokebuttonClicked)
{
ScreenManager.SpriteBatch.Draw(
smokeButton, new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y, 109, 109),
new Rectangle(109, 0, 109, 109), Color.White);
}
else
{
ScreenManager.SpriteBatch.Draw(
smokeButton, new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y, 109, 109),
new Rectangle(0, 0, 109, 109), Color.White);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
{
public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Version of this service
private const string m_Version = "SIMULATION/0.1";
private List<Scene> m_sceneList = new List<Scene>();
private IEntityTransferModule m_AgentTransferModule;
protected IEntityTransferModule AgentTransferModule
{
get
{
if (m_AgentTransferModule == null)
m_AgentTransferModule = m_sceneList[0].RequestModuleInterface<IEntityTransferModule>();
return m_AgentTransferModule;
}
}
private bool m_ModuleEnabled = false;
#region IRegionModule
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("SimulationServices", "");
if (name == Name)
{
//IConfig userConfig = config.Configs["SimulationService"];
//if (userConfig == null)
//{
// m_log.Error("[AVATAR CONNECTOR]: SimulationService missing from OpenSim.ini");
// return;
//}
m_ModuleEnabled = true;
m_log.Info("[SIMULATION CONNECTOR]: Local simulation enabled");
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (!m_ModuleEnabled)
return;
Init(scene);
scene.RegisterModuleInterface<ISimulationService>(this);
}
public void RemoveRegion(Scene scene)
{
if (!m_ModuleEnabled)
return;
RemoveScene(scene);
scene.UnregisterModuleInterface<ISimulationService>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalSimulationConnectorModule"; }
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void RemoveScene(Scene scene)
{
lock (m_sceneList)
{
if (m_sceneList.Contains(scene))
{
m_sceneList.Remove(scene);
}
}
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void Init(Scene scene)
{
if (!m_sceneList.Contains(scene))
{
lock (m_sceneList)
{
m_sceneList.Add(scene);
}
}
}
#endregion /* IRegionModule */
#region ISimulation
public IScene GetScene(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionhandle)
return s;
}
// ? weird. should not happen
return m_sceneList[0];
}
public ISimulationService GetInnerService()
{
return this;
}
/**
* Agent-related communications
*/
public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
if (destination == null)
{
reason = "Given destination was null";
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination");
return false;
}
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
return s.NewUserConnection(aCircuit, teleportFlags, out reason);
}
}
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Did not find region {0} for SendCreateChildAgent", destination.RegionName);
reason = "Did not find region " + destination.RegionName;
return false;
}
public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
{
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{
m_log.DebugFormat(
"[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
s.RegionInfo.RegionName, destination.RegionHandle);
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
return false;
}
public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
{
if (destination == null)
return false;
// We limit the number of messages sent for a position change to just one per
// simulator so when we receive the update we need to hand it to each of the
// scenes; scenes each check to see if the is a scene presence for the avatar
// note that we really don't need the GridRegion for this call
foreach (Scene s in m_sceneList)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
s.IncomingChildAgentDataUpdate(cAgentData);
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return true;
}
public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
{
agent = null;
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
return s.IncomingRetrieveRootAgent(id, out agent);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason)
{
reason = "Communications failure";
version = m_Version;
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionID == destination.RegionID)
return s.QueryAccess(id, position, out reason);
}
//m_log.Debug("[LOCAL COMMS]: region not found for QueryAccess");
return false;
}
public bool ReleaseAgent(UUID origin, UUID id, string uri)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionID == origin)
{
m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
AgentTransferModule.AgentArrivedAtDestination(id);
return true;
// return s.IncomingReleaseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin);
return false;
}
public bool CloseAgent(GridRegion destination, UUID id)
{
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionID == destination.RegionID)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
// Let's spawn a threadlet right here, because this may take
// a while
Util.FireAndForget(delegate { s.IncomingCloseAgent(id); });
return true;
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
return false;
}
/**
* Object-related communications
*/
public bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall)
{
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
if (isLocalCall)
{
// We need to make a local copy of the object
ISceneObject sogClone = sog.CloneForNewScene();
sogClone.SetState(sog.GetStateSnapshot(), s);
return s.IncomingCreateObject(sogClone);
}
else
{
// Use the object as it came through the wire
return s.IncomingCreateObject(sog);
}
}
}
return false;
}
public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
{
if (destination == null)
return false;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{
return s.IncomingCreateObject(userID, itemID);
}
}
return false;
}
#endregion /* IInterregionComms */
#region Misc
public bool IsLocalRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return true;
return false;
}
public bool IsLocalRegion(UUID id)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionID == id)
return true;
return false;
}
#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.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.DirectoryServices.ActiveDirectory
{
public class GlobalCatalog : DomainController
{
// private variables
private ActiveDirectorySchema _schema = null;
private bool _disabled = false;
#region constructors
internal GlobalCatalog(DirectoryContext context, string globalCatalogName)
: base(context, globalCatalogName)
{ }
internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr)
: base(context, globalCatalogName, directoryEntryMgr)
{ }
#endregion constructors
#region public methods
public static GlobalCatalog GetGlobalCatalog(DirectoryContext context)
{
string gcDnsName = null;
bool isGlobalCatalog = false;
DirectoryEntryManager directoryEntryMgr = null;
// check that the context argument is not null
if (context == null)
throw new ArgumentNullException(nameof(context));
// target should be GC
if (context.ContextType != DirectoryContextType.DirectoryServer)
{
throw new ArgumentException(SR.TargetShouldBeGC, nameof(context));
}
// target should be a server
if (!(context.isServer()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
// work with copy of the context
context = new DirectoryContext(context);
try
{
// Get dns name of the dc
// by binding to root dse and getting the "dnsHostName" attribute
// (also check that the "isGlobalCatalogReady" attribute is true)
directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
isGlobalCatalog = (bool)bool.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady));
if (!isGlobalCatalog)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
return new GlobalCatalog(context, gcDnsName, directoryEntryMgr);
}
public static new GlobalCatalog FindOne(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
return FindOneWithCredentialValidation(context, null, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return FindOneWithCredentialValidation(context, siteName, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
return FindOneWithCredentialValidation(context, null, flag);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return FindOneWithCredentialValidation(context, siteName, flag);
}
public static new GlobalCatalogCollection FindAll(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, null);
}
public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.TargetShouldBeForest, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, siteName);
}
public override GlobalCatalog EnableGlobalCatalog()
{
CheckIfDisposed();
throw new InvalidOperationException(SR.CannotPerformOnGCObject);
}
public DomainController DisableGlobalCatalog()
{
CheckIfDisposed();
CheckIfDisabled();
// bind to the server object
DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName);
// reset the NTDSDSA_OPT_IS_GC flag on the "options" property
int options = 0;
try
{
if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null)
{
options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value;
}
serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1);
serverNtdsaEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// mark as disbaled
_disabled = true;
// return a domain controller object
return new DomainController(context, Name);
}
public override bool IsGlobalCatalog()
{
CheckIfDisposed();
CheckIfDisabled();
// since this is a global catalog object, this should always return true
return true;
}
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties()
{
CheckIfDisposed();
CheckIfDisabled();
// create an ActiveDirectorySchema object
if (_schema == null)
{
string schemaNC = null;
try
{
schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
DirectoryContext schemaContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
_schema = new ActiveDirectorySchema(context, schemaNC);
}
// return the global catalog replicated properties
return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog);
}
public override DirectorySearcher GetDirectorySearcher()
{
CheckIfDisposed();
CheckIfDisabled();
return InternalGetDirectorySearcher();
}
#endregion public methods
#region private methods
private void CheckIfDisabled()
{
if (_disabled)
{
throw new InvalidOperationException(SR.GCDisabled);
}
}
internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string siteName, LocatorOptions flag)
{
GlobalCatalog gc;
bool retry = false;
bool credsValidated = false;
// work with copy of the context
context = new DirectoryContext(context);
// authenticate against this GC to validate the credentials
gc = FindOneInternal(context, context.Name, siteName, flag);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down , so try again with force rediscovery if the flags did not already contain force rediscovery
if ((flag & LocatorOptions.ForceRediscovery) == 0)
{
retry = true;
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
if (retry)
{
credsValidated = false;
gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
}
return gc;
}
internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string forestName, string siteName, LocatorOptions flag)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
// check that the flags passed have only the valid bits set
if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, nameof(flag));
}
if (forestName == null)
{
// get the dns name of the logged on forest
DomainControllerInfo tempDomainControllerInfo;
int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out tempDomainControllerInfo);
if (error == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// throw not found exception
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(GlobalCatalog), null);
}
else if (error != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(tempDomainControllerInfo.DnsForestName != null);
forestName = tempDomainControllerInfo.DnsForestName;
}
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
{
throw new ArgumentException(SR.InvalidFlags, nameof(flag));
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
// create a GlobalCatalog object
// the name is returned in the form "\\servername", so skip the "\\"
Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2);
string globalCatalogName = domainControllerInfo.DomainControllerName.Substring(2);
// create a new context object for the global catalog
DirectoryContext gcContext = Utils.GetNewDirectoryContext(globalCatalogName, DirectoryContextType.DirectoryServer, context);
return new GlobalCatalog(gcContext, globalCatalogName);
}
internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context, string siteName)
{
ArrayList gcList = new ArrayList();
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */))
{
DirectoryContext gcContext = Utils.GetNewDirectoryContext(gcName, DirectoryContextType.DirectoryServer, context);
gcList.Add(new GlobalCatalog(gcContext, gcName));
}
return new GlobalCatalogCollection(gcList);
}
private DirectorySearcher InternalGetDirectorySearcher()
{
DirectoryEntry de = new DirectoryEntry("GC://" + Name);
de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind;
de.Username = context.UserName;
de.Password = context.Password;
return new DirectorySearcher(de);
}
#endregion
}
}
| |
// Copyright (C) Josh Smith - January 2007
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Input;
namespace MafiaAutoName
{
#region ListViewDragDropManager
/// <summary>
/// Manages the dragging and dropping of ListViewItems in a ListView.
/// The ItemType type parameter indicates the type of the objects in
/// the ListView's items source. The ListView's ItemsSource must be
/// set to an instance of ObservableCollection of ItemType, or an
/// Exception will be thrown.
/// </summary>
/// <typeparam name="ItemType">The type of the ListView's items.</typeparam>
public class ListViewDragDropManager<ItemType> where ItemType : class
{
#region Data
bool canInitiateDrag;
DragAdorner dragAdorner;
double dragAdornerOpacity;
int indexToSelect;
bool isDragInProgress;
ItemType itemUnderDragCursor;
ListView listView;
Point ptMouseDown;
bool showDragAdorner;
#endregion // Data
#region Constructors
/// <summary>
/// Initializes a new instance of ListViewDragManager.
/// </summary>
public ListViewDragDropManager()
{
this.canInitiateDrag = false;
this.dragAdornerOpacity = 0.7;
this.indexToSelect = -1;
this.showDragAdorner = true;
}
/// <summary>
/// Initializes a new instance of ListViewDragManager.
/// </summary>
/// <param name="listView"></param>
public ListViewDragDropManager( ListView listView )
: this()
{
this.ListView = listView;
}
/// <summary>
/// Initializes a new instance of ListViewDragManager.
/// </summary>
/// <param name="listView"></param>
/// <param name="dragAdornerOpacity"></param>
public ListViewDragDropManager( ListView listView, double dragAdornerOpacity )
: this( listView )
{
this.DragAdornerOpacity = dragAdornerOpacity;
}
/// <summary>
/// Initializes a new instance of ListViewDragManager.
/// </summary>
/// <param name="listView"></param>
/// <param name="showDragAdorner"></param>
public ListViewDragDropManager( ListView listView, bool showDragAdorner )
: this( listView )
{
this.ShowDragAdorner = showDragAdorner;
}
#endregion // Constructors
#region Public Interface
#region DragAdornerOpacity
/// <summary>
/// Gets/sets the opacity of the drag adorner. This property has no
/// effect if ShowDragAdorner is false. The default value is 0.7
/// </summary>
public double DragAdornerOpacity
{
get { return this.dragAdornerOpacity; }
set
{
if( this.IsDragInProgress )
throw new InvalidOperationException( "Cannot set the DragAdornerOpacity property during a drag operation." );
if( value < 0.0 || value > 1.0 )
throw new ArgumentOutOfRangeException( "DragAdornerOpacity", value, "Must be between 0 and 1." );
this.dragAdornerOpacity = value;
}
}
#endregion // DragAdornerOpacity
#region IsDragInProgress
/// <summary>
/// Returns true if there is currently a drag operation being managed.
/// </summary>
public bool IsDragInProgress
{
get { return this.isDragInProgress; }
private set { this.isDragInProgress = value; }
}
#endregion // IsDragInProgress
#region ListView
/// <summary>
/// Gets/sets the ListView whose dragging is managed. This property
/// can be set to null, to prevent drag management from occuring. If
/// the ListView's AllowDrop property is false, it will be set to true.
/// </summary>
public ListView ListView
{
get { return listView; }
set
{
if( this.IsDragInProgress )
throw new InvalidOperationException( "Cannot set the ListView property during a drag operation." );
if( this.listView != null )
{
#region Unhook Events
this.listView.PreviewMouseLeftButtonDown -= listView_PreviewMouseLeftButtonDown;
this.listView.PreviewMouseMove -= listView_PreviewMouseMove;
this.listView.DragOver -= listView_DragOver;
this.listView.DragLeave -= listView_DragLeave;
this.listView.DragEnter -= listView_DragEnter;
this.listView.Drop -= listView_Drop;
#endregion // Unhook Events
}
this.listView = value;
if( this.listView != null )
{
if( !this.listView.AllowDrop )
this.listView.AllowDrop = true;
#region Hook Events
this.listView.PreviewMouseLeftButtonDown += listView_PreviewMouseLeftButtonDown;
this.listView.PreviewMouseMove += listView_PreviewMouseMove;
this.listView.DragOver += listView_DragOver;
this.listView.DragLeave += listView_DragLeave;
this.listView.DragEnter += listView_DragEnter;
this.listView.Drop += listView_Drop;
#endregion // Hook Events
}
}
}
#endregion // ListView
#region ProcessDrop [event]
/// <summary>
/// Raised when a drop occurs. By default the dropped item will be moved
/// to the target index. Handle this event if relocating the dropped item
/// requires custom behavior. Note, if this event is handled the default
/// item dropping logic will not occur.
/// </summary>
public event EventHandler<ProcessDropEventArgs<ItemType>> ProcessDrop;
#endregion // ProcessDrop [event]
#region ShowDragAdorner
/// <summary>
/// Gets/sets whether a visual representation of the ListViewItem being dragged
/// follows the mouse cursor during a drag operation. The default value is true.
/// </summary>
public bool ShowDragAdorner
{
get { return this.showDragAdorner; }
set
{
if( this.IsDragInProgress )
throw new InvalidOperationException( "Cannot set the ShowDragAdorner property during a drag operation." );
this.showDragAdorner = value;
}
}
#endregion // ShowDragAdorner
#endregion // Public Interface
#region Event Handling Methods
#region listView_PreviewMouseLeftButtonDown
void listView_PreviewMouseLeftButtonDown( object sender, MouseButtonEventArgs e )
{
if( this.IsMouseOverScrollbar )
{
// 4/13/2007 - Set the flag to false when cursor is over scrollbar.
this.canInitiateDrag = false;
return;
}
int index = this.IndexUnderDragCursor;
this.canInitiateDrag = index > -1;
if( this.canInitiateDrag )
{
// Remember the location and index of the ListViewItem the user clicked on for later.
this.ptMouseDown = MouseUtilities.GetMousePosition( this.listView );
this.indexToSelect = index;
}
else
{
this.ptMouseDown = new Point( -10000, -10000 );
this.indexToSelect = -1;
}
}
#endregion // listView_PreviewMouseLeftButtonDown
#region listView_PreviewMouseMove
void listView_PreviewMouseMove( object sender, MouseEventArgs e )
{
if( !this.CanStartDragOperation )
return;
// Select the item the user clicked on.
if( this.listView.SelectedIndex != this.indexToSelect )
this.listView.SelectedIndex = this.indexToSelect;
// If the item at the selected index is null, there's nothing
// we can do, so just return;
if( this.listView.SelectedItem == null )
return;
ListViewItem itemToDrag = this.GetListViewItem( this.listView.SelectedIndex );
if( itemToDrag == null )
return;
AdornerLayer adornerLayer = this.ShowDragAdornerResolved ? this.InitializeAdornerLayer( itemToDrag ) : null;
this.InitializeDragOperation( itemToDrag );
this.PerformDragOperation();
this.FinishDragOperation( itemToDrag, adornerLayer );
}
#endregion // listView_PreviewMouseMove
#region listView_DragOver
void listView_DragOver( object sender, DragEventArgs e )
{
e.Effects = DragDropEffects.Move;
if( this.ShowDragAdornerResolved )
this.UpdateDragAdornerLocation();
// Update the item which is known to be currently under the drag cursor.
int index = this.IndexUnderDragCursor;
this.ItemUnderDragCursor = index < 0 ? null : this.ListView.Items[index] as ItemType;
}
#endregion // listView_DragOver
#region listView_DragLeave
void listView_DragLeave( object sender, DragEventArgs e )
{
if( !this.IsMouseOver( this.listView ) )
{
if( this.ItemUnderDragCursor != null )
this.ItemUnderDragCursor = null;
if( this.dragAdorner != null )
this.dragAdorner.Visibility = Visibility.Collapsed;
}
}
#endregion // listView_DragLeave
#region listView_DragEnter
void listView_DragEnter( object sender, DragEventArgs e )
{
if( this.dragAdorner != null && this.dragAdorner.Visibility != Visibility.Visible )
{
// Update the location of the adorner and then show it.
this.UpdateDragAdornerLocation();
this.dragAdorner.Visibility = Visibility.Visible;
}
}
#endregion // listView_DragEnter
#region listView_Drop
void listView_Drop( object sender, DragEventArgs e )
{
if( this.ItemUnderDragCursor != null )
this.ItemUnderDragCursor = null;
e.Effects = DragDropEffects.None;
if( !e.Data.GetDataPresent( typeof( ItemType ) ) )
return;
// Get the data object which was dropped.
ItemType data = e.Data.GetData( typeof( ItemType ) ) as ItemType;
if( data == null )
return;
// Get the ObservableCollection<ItemType> which contains the dropped data object.
ObservableCollection<ItemType> itemsSource = this.listView.ItemsSource as ObservableCollection<ItemType>;
if( itemsSource == null )
throw new Exception(
"A ListView managed by ListViewDragManager must have its ItemsSource set to an ObservableCollection<ItemType>." );
int oldIndex = itemsSource.IndexOf( data );
int newIndex = this.IndexUnderDragCursor;
if( newIndex < 0 )
{
// The drag started somewhere else, and our ListView is empty
// so make the new item the first in the list.
if( itemsSource.Count == 0 )
newIndex = 0;
// The drag started somewhere else, but our ListView has items
// so make the new item the last in the list.
else if( oldIndex < 0 )
newIndex = itemsSource.Count;
// The user is trying to drop an item from our ListView into
// our ListView, but the mouse is not over an item, so don't
// let them drop it.
else
return;
}
// Dropping an item back onto itself is not considered an actual 'drop'.
if( oldIndex == newIndex )
return;
if( this.ProcessDrop != null )
{
// Let the client code process the drop.
ProcessDropEventArgs<ItemType> args = new ProcessDropEventArgs<ItemType>( itemsSource, data, oldIndex, newIndex, e.AllowedEffects );
this.ProcessDrop( this, args );
e.Effects = args.Effects;
}
else
{
// Move the dragged data object from it's original index to the
// new index (according to where the mouse cursor is). If it was
// not previously in the ListBox, then insert the item.
if( oldIndex > -1 )
itemsSource.Move( oldIndex, newIndex );
else
itemsSource.Insert( newIndex, data );
// Set the Effects property so that the call to DoDragDrop will return 'Move'.
e.Effects = DragDropEffects.Move;
}
}
#endregion // listView_Drop
#endregion // Event Handling Methods
#region Private Helpers
#region CanStartDragOperation
bool CanStartDragOperation
{
get
{
if( Mouse.LeftButton != MouseButtonState.Pressed )
return false;
if( !this.canInitiateDrag )
return false;
if( this.indexToSelect == -1 )
return false;
if( !this.HasCursorLeftDragThreshold )
return false;
return true;
}
}
#endregion // CanStartDragOperation
#region FinishDragOperation
void FinishDragOperation( ListViewItem draggedItem, AdornerLayer adornerLayer )
{
// Let the ListViewItem know that it is not being dragged anymore.
ListViewItemDragState.SetIsBeingDragged( draggedItem, false );
this.IsDragInProgress = false;
if( this.ItemUnderDragCursor != null )
this.ItemUnderDragCursor = null;
// Remove the drag adorner from the adorner layer.
if( adornerLayer != null )
{
adornerLayer.Remove( this.dragAdorner );
this.dragAdorner = null;
}
}
#endregion // FinishDragOperation
#region GetListViewItem
ListViewItem GetListViewItem( int index )
{
if( this.listView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated )
return null;
return this.listView.ItemContainerGenerator.ContainerFromIndex( index ) as ListViewItem;
}
ListViewItem GetListViewItem( ItemType dataItem )
{
if( this.listView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated )
return null;
return this.listView.ItemContainerGenerator.ContainerFromItem( dataItem ) as ListViewItem;
}
#endregion // GetListViewItem
#region HasCursorLeftDragThreshold
bool HasCursorLeftDragThreshold
{
get
{
if( this.indexToSelect < 0 )
return false;
ListViewItem item = this.GetListViewItem( this.indexToSelect );
Rect bounds = VisualTreeHelper.GetDescendantBounds( item );
Point ptInItem = this.listView.TranslatePoint( this.ptMouseDown, item );
// In case the cursor is at the very top or bottom of the ListViewItem
// we want to make the vertical threshold very small so that dragging
// over an adjacent item does not select it.
double topOffset = Math.Abs( ptInItem.Y );
double btmOffset = Math.Abs( bounds.Height - ptInItem.Y );
double vertOffset = Math.Min( topOffset, btmOffset );
double width = SystemParameters.MinimumHorizontalDragDistance * 2;
double height = Math.Min( SystemParameters.MinimumVerticalDragDistance, vertOffset ) * 2;
Size szThreshold = new Size( width, height );
Rect rect = new Rect( this.ptMouseDown, szThreshold );
rect.Offset( szThreshold.Width / -2, szThreshold.Height / -2 );
Point ptInListView = MouseUtilities.GetMousePosition( this.listView );
return !rect.Contains( ptInListView );
}
}
#endregion // HasCursorLeftDragThreshold
#region IndexUnderDragCursor
/// <summary>
/// Returns the index of the ListViewItem underneath the
/// drag cursor, or -1 if the cursor is not over an item.
/// </summary>
int IndexUnderDragCursor
{
get
{
int index = -1;
for( int i = 0; i < this.listView.Items.Count; ++i )
{
ListViewItem item = this.GetListViewItem( i );
if( this.IsMouseOver( item ) )
{
index = i;
break;
}
}
return index;
}
}
#endregion // IndexUnderDragCursor
#region InitializeAdornerLayer
AdornerLayer InitializeAdornerLayer( ListViewItem itemToDrag )
{
// Create a brush which will paint the ListViewItem onto
// a visual in the adorner layer.
VisualBrush brush = new VisualBrush( itemToDrag );
// Create an element which displays the source item while it is dragged.
this.dragAdorner = new DragAdorner( this.listView, itemToDrag.RenderSize, brush );
// Set the drag adorner's opacity.
this.dragAdorner.Opacity = this.DragAdornerOpacity;
AdornerLayer layer = AdornerLayer.GetAdornerLayer( this.listView );
layer.Add( dragAdorner );
// Save the location of the cursor when the left mouse button was pressed.
this.ptMouseDown = MouseUtilities.GetMousePosition( this.listView );
return layer;
}
#endregion // InitializeAdornerLayer
#region InitializeDragOperation
void InitializeDragOperation( ListViewItem itemToDrag )
{
// Set some flags used during the drag operation.
this.IsDragInProgress = true;
this.canInitiateDrag = false;
// Let the ListViewItem know that it is being dragged.
ListViewItemDragState.SetIsBeingDragged( itemToDrag, true );
}
#endregion // InitializeDragOperation
#region IsMouseOver
bool IsMouseOver( Visual target )
{
// We need to use MouseUtilities to figure out the cursor
// coordinates because, during a drag-drop operation, the WPF
// mechanisms for getting the coordinates behave strangely.
Rect bounds = VisualTreeHelper.GetDescendantBounds( target );
Point mousePos = MouseUtilities.GetMousePosition( target );
return bounds.Contains( mousePos );
}
#endregion // IsMouseOver
#region IsMouseOverScrollbar
/// <summary>
/// Returns true if the mouse cursor is over a scrollbar in the ListView.
/// </summary>
bool IsMouseOverScrollbar
{
get
{
Point ptMouse = MouseUtilities.GetMousePosition( this.listView );
HitTestResult res = VisualTreeHelper.HitTest( this.listView, ptMouse );
if( res == null )
return false;
DependencyObject depObj = res.VisualHit;
while( depObj != null )
{
if( depObj is ScrollBar )
return true;
// VisualTreeHelper works with objects of type Visual or Visual3D.
// If the current object is not derived from Visual or Visual3D,
// then use the LogicalTreeHelper to find the parent element.
if( depObj is Visual || depObj is System.Windows.Media.Media3D.Visual3D )
depObj = VisualTreeHelper.GetParent( depObj );
else
depObj = LogicalTreeHelper.GetParent( depObj );
}
return false;
}
}
#endregion // IsMouseOverScrollbar
#region ItemUnderDragCursor
ItemType ItemUnderDragCursor
{
get { return this.itemUnderDragCursor; }
set
{
if( this.itemUnderDragCursor == value )
return;
// The first pass handles the previous item under the cursor.
// The second pass handles the new one.
for( int i = 0; i < 2; ++i )
{
if( i == 1 )
this.itemUnderDragCursor = value;
if( this.itemUnderDragCursor != null )
{
ListViewItem listViewItem = this.GetListViewItem( this.itemUnderDragCursor );
if( listViewItem != null )
ListViewItemDragState.SetIsUnderDragCursor( listViewItem, i == 1 );
}
}
}
}
#endregion // ItemUnderDragCursor
#region PerformDragOperation
void PerformDragOperation()
{
ItemType selectedItem = this.listView.SelectedItem as ItemType;
DragDropEffects allowedEffects = DragDropEffects.Move | DragDropEffects.Move | DragDropEffects.Link;
if( DragDrop.DoDragDrop( this.listView, selectedItem, allowedEffects ) != DragDropEffects.None )
{
// The item was dropped into a new location,
// so make it the new selected item.
this.listView.SelectedItem = selectedItem;
}
}
#endregion // PerformDragOperation
#region ShowDragAdornerResolved
bool ShowDragAdornerResolved
{
get { return this.ShowDragAdorner && this.DragAdornerOpacity > 0.0; }
}
#endregion // ShowDragAdornerResolved
#region UpdateDragAdornerLocation
void UpdateDragAdornerLocation()
{
if( this.dragAdorner != null )
{
Point ptCursor = MouseUtilities.GetMousePosition( this.ListView );
double left = ptCursor.X - this.ptMouseDown.X;
// 4/13/2007 - Made the top offset relative to the item being dragged.
ListViewItem itemBeingDragged = this.GetListViewItem( this.indexToSelect );
Point itemLoc = itemBeingDragged.TranslatePoint( new Point( 0, 0 ), this.ListView );
double top = itemLoc.Y + ptCursor.Y - this.ptMouseDown.Y;
this.dragAdorner.SetOffsets( left, top );
}
}
#endregion // UpdateDragAdornerLocation
#endregion // Private Helpers
}
#endregion // ListViewDragDropManager
#region ListViewItemDragState
/// <summary>
/// Exposes attached properties used in conjunction with the ListViewDragDropManager class.
/// Those properties can be used to allow triggers to modify the appearance of ListViewItems
/// in a ListView during a drag-drop operation.
/// </summary>
public static class ListViewItemDragState
{
#region IsBeingDragged
/// <summary>
/// Identifies the ListViewItemDragState's IsBeingDragged attached property.
/// This field is read-only.
/// </summary>
public static readonly DependencyProperty IsBeingDraggedProperty =
DependencyProperty.RegisterAttached(
"IsBeingDragged",
typeof( bool ),
typeof( ListViewItemDragState ),
new UIPropertyMetadata( false ) );
/// <summary>
/// Returns true if the specified ListViewItem is being dragged, else false.
/// </summary>
/// <param name="item">The ListViewItem to check.</param>
public static bool GetIsBeingDragged( ListViewItem item )
{
return (bool)item.GetValue( IsBeingDraggedProperty );
}
/// <summary>
/// Sets the IsBeingDragged attached property for the specified ListViewItem.
/// </summary>
/// <param name="item">The ListViewItem to set the property on.</param>
/// <param name="value">Pass true if the element is being dragged, else false.</param>
internal static void SetIsBeingDragged( ListViewItem item, bool value )
{
item.SetValue( IsBeingDraggedProperty, value );
}
#endregion // IsBeingDragged
#region IsUnderDragCursor
/// <summary>
/// Identifies the ListViewItemDragState's IsUnderDragCursor attached property.
/// This field is read-only.
/// </summary>
public static readonly DependencyProperty IsUnderDragCursorProperty =
DependencyProperty.RegisterAttached(
"IsUnderDragCursor",
typeof( bool ),
typeof( ListViewItemDragState ),
new UIPropertyMetadata( false ) );
/// <summary>
/// Returns true if the specified ListViewItem is currently underneath the cursor
/// during a drag-drop operation, else false.
/// </summary>
/// <param name="item">The ListViewItem to check.</param>
public static bool GetIsUnderDragCursor( ListViewItem item )
{
return (bool)item.GetValue( IsUnderDragCursorProperty );
}
/// <summary>
/// Sets the IsUnderDragCursor attached property for the specified ListViewItem.
/// </summary>
/// <param name="item">The ListViewItem to set the property on.</param>
/// <param name="value">Pass true if the element is underneath the drag cursor, else false.</param>
internal static void SetIsUnderDragCursor( ListViewItem item, bool value )
{
item.SetValue( IsUnderDragCursorProperty, value );
}
#endregion // IsUnderDragCursor
}
#endregion // ListViewItemDragState
#region ProcessDropEventArgs
/// <summary>
/// Event arguments used by the ListViewDragDropManager.ProcessDrop event.
/// </summary>
/// <typeparam name="ItemType">The type of data object being dropped.</typeparam>
public class ProcessDropEventArgs<ItemType> : EventArgs where ItemType : class
{
#region Data
ObservableCollection<ItemType> itemsSource;
ItemType dataItem;
int oldIndex;
int newIndex;
DragDropEffects allowedEffects = DragDropEffects.None;
DragDropEffects effects = DragDropEffects.None;
#endregion // Data
#region Constructor
internal ProcessDropEventArgs(
ObservableCollection<ItemType> itemsSource,
ItemType dataItem,
int oldIndex,
int newIndex,
DragDropEffects allowedEffects )
{
this.itemsSource = itemsSource;
this.dataItem = dataItem;
this.oldIndex = oldIndex;
this.newIndex = newIndex;
this.allowedEffects = allowedEffects;
}
#endregion // Constructor
#region Public Properties
/// <summary>
/// The items source of the ListView where the drop occurred.
/// </summary>
public ObservableCollection<ItemType> ItemsSource
{
get { return this.itemsSource; }
}
/// <summary>
/// The data object which was dropped.
/// </summary>
public ItemType DataItem
{
get { return this.dataItem; }
}
/// <summary>
/// The current index of the data item being dropped, in the ItemsSource collection.
/// </summary>
public int OldIndex
{
get { return this.oldIndex; }
}
/// <summary>
/// The target index of the data item being dropped, in the ItemsSource collection.
/// </summary>
public int NewIndex
{
get { return this.newIndex; }
}
/// <summary>
/// The drag drop effects allowed to be performed.
/// </summary>
public DragDropEffects AllowedEffects
{
get { return allowedEffects; }
}
/// <summary>
/// The drag drop effect(s) performed on the dropped item.
/// </summary>
public DragDropEffects Effects
{
get { return effects; }
set { effects = value; }
}
#endregion // Public Properties
}
#endregion // ProcessDropEventArgs
}
| |
//------------------------------------------------------------------------------
// <copyright file="EtwListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Text;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.Eventing
{
public class EventProviderTraceListener : TraceListener
{
//
// The listener uses the EtwProvider base class.
// Because Listener data is not schematized at the moment the listener will
// log events using WriteMessageEvent method.
//
// Because WriteMessageEvent takes a string as the event payload
// all the overriden loging methods convert the arguments into strings.
// Event payload is "delimiter" separated, which can be configured
//
//
private EventProvider _provider;
private const string s_nullStringValue = "null";
private const string s_nullStringComaValue = "null,";
private const string s_nullCStringValue = ": null";
private string _delimiter = ";";
private const uint s_keyWordMask = 0xFFFFFF00;
private const int s_defaultPayloadSize = 512;
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
public string Delimiter
{
get
{
return _delimiter;
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
set
{
if (value == null)
throw new ArgumentNullException("Delimiter");
if (value.Length == 0)
throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter);
_delimiter = value;
}
}
/// <summary>
/// This method creates an instance of the ETW provider.
/// The guid argument must be a valid GUID or a format exeption will be
/// thrown when creating an instance of the ControlGuid.
/// We need to be running on Vista or above. If not an
/// PlatformNotSupported exception will be thrown by the EventProvider.
/// </summary>
public EventProviderTraceListener(string providerId)
{
InitProvider(providerId);
}
public EventProviderTraceListener(string providerId, string name)
: base(name)
{
InitProvider(providerId);
}
public EventProviderTraceListener(string providerId, string name, string delimiter)
: base(name)
{
if (delimiter == null)
throw new ArgumentNullException("delimiter");
if (delimiter.Length == 0)
throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter);
_delimiter = delimiter;
InitProvider(providerId);
}
private void InitProvider(string providerId)
{
Guid controlGuid = new Guid(providerId);
//
// Create The ETW TraceProvider
//
_provider = new EventProvider(controlGuid);
}
//
// override Listener methods
//
public sealed override void Flush()
{
}
public sealed override bool IsThreadSafe
{
get
{
return true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_provider.Close();
}
}
public sealed override void Write(string message)
{
if (!_provider.IsEnabled())
{
return;
}
_provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0);
}
public sealed override void WriteLine(string message)
{
Write(message);
}
//
// For all the methods below the string to be logged contains:
// m_delimeter seperated data converted to string
//
// The source parameter is ignored.
//
public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (!_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
if (data != null)
{
dataString.Append(data.ToString());
}
else
{
dataString.Append(s_nullCStringValue);
}
_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
public sealed override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data)
{
if (!_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
int index;
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
if ((data != null) && (data.Length > 0))
{
for (index = 0; index < (data.Length - 1); index++)
{
if (data[index] != null)
{
dataString.Append(data[index].ToString());
dataString.Append(Delimiter);
}
else
{
dataString.Append(s_nullStringComaValue);
}
}
if (data[index] != null)
{
dataString.Append(data[index].ToString());
}
else
{
dataString.Append(s_nullStringValue);
}
}
else
{
dataString.Append(s_nullStringValue);
}
_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
{
if (!_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
_provider.WriteMessageEvent(String.Empty,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (!_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
StringBuilder dataString = new StringBuilder(s_defaultPayloadSize);
dataString.Append(message);
_provider.WriteMessageEvent(dataString.ToString(),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (!_provider.IsEnabled())
{
return;
}
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null))
{
return;
}
if (args == null)
{
_provider.WriteMessageEvent(format,
(byte)eventType,
(long)eventType & s_keyWordMask);
}
else
{
_provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args),
(byte)eventType,
(long)eventType & s_keyWordMask);
}
}
public override void Fail(string message, string detailMessage)
{
StringBuilder failMessage = new StringBuilder(message);
if (detailMessage != null)
{
failMessage.Append(" ");
failMessage.Append(detailMessage);
}
this.TraceEvent(null, null, TraceEventType.Error, 0, failMessage.ToString());
}
}
}
| |
/*
* PROPRIETARY INFORMATION. This software is proprietary to
* Side Effects Software Inc., and is not to be reproduced,
* transmitted, or disclosed in any way without written permission.
*
* Produced by:
* Side Effects Software Inc
* 123 Front Street West, Suite 1401
* Toronto, Ontario
* Canada M5J 2M2
* 416-504-9876
*
* COMMENTS:
* Contains HAPI_Host which is a singleton class that maintains the singleton Houdini scene and
* all access to the Houdini runtime.
*
*/
// Master control for enabling runtime.
#if ( UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX || ( UNITY_METRO && UNITY_EDITOR ) )
#define HAPI_ENABLE_RUNTIME
#endif
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif // UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
public delegate void RepaintDelegate();
public delegate void DeselectionDelegate();
public delegate void PlaymodeStateChangeDelegate();
public class HoudiniError : System.Exception
{
public HoudiniError()
{
myErrorMessage = "Unknown Error";
}
public HoudiniError( string msg )
{
myErrorMessage = msg;
}
public void addMessagePrefix( string prefix )
{
myErrorMessage = prefix + ": " + myErrorMessage;
}
public void addMessageDetail( string detail )
{
myErrorMessage = myErrorMessage + "\n" + detail;
}
public override string ToString()
{
return myErrorMessage;
}
protected string myErrorMessage;
}
public class HoudiniErrorUnsupportedPlatform : HoudiniError
{
public HoudiniErrorUnsupportedPlatform() : base( HoudiniConstants.HAPI_UNSUPPORTED_PLATFORM_MSG ) {}
}
public class HoudiniErrorInvalidArgument : HoudiniError
{
public HoudiniErrorInvalidArgument() : base( "Invalid arugment error." ) {}
public HoudiniErrorInvalidArgument( string msg ) : base( msg ) {}
}
public class HoudiniErrorAssetDefOverride : HoudiniError
{
public HoudiniErrorAssetDefOverride() : base( "Asset definition already loaded." ) {}
public HoudiniErrorAssetDefOverride( string msg ) : base( msg ) {}
}
public class HoudiniErrorNotFound : HoudiniErrorInvalidArgument
{
public HoudiniErrorNotFound() : base( "Item not found." ) {}
public HoudiniErrorNotFound( string msg ) : base( msg ) {}
}
public class HoudiniErrorProgressCancelled : HoudiniError
{
public HoudiniErrorProgressCancelled() : base( "Load Cancelled by User" ) {}
}
public class HoudiniErrorIgnorable : HoudiniError
{
public HoudiniErrorIgnorable() : base( "Ignorable Error" ) {}
public HoudiniErrorIgnorable( string msg ) : base( msg ) {}
}
/// <summary>
/// Singleton Houdini host object that maintains the singleton Houdini scene and all access to the
/// Houdini runtime.
/// </summary>
//
#if UNITY_EDITOR
[ InitializeOnLoad ]
#endif // UNITY_EDITOR
public static partial class HoudiniHost
{
// Global Settings Defaults ---------------------------------------------------------------------------------
private const string myDefaultCollisionGroupName = "collision_geo";
private const string myDefaultRenderedCollisionGroupName = "rendered_collision_geo";
private const string myDefaultUnityMaterialAttribName = "unity_material";
private const string myDefaultUnitySubMaterialNameAttribName = "unity_sub_material_name";
private const string myDefaultUnitySubMaterialIndexAttribName = "unity_sub_material_index";
private const float myDefaultPinSize = 1.0f;
private static Color myDefaultPinColour = new Color( 0.7f, 0.0f, 0.0f, 1.0f );
private const bool myDefaultAutoPinInstances = true;
private const bool myDefaultEnableSupportWarnings = true;
private const bool myDefaultEnablePointsAsParticles = true;
public const float myDefaultGamma = 2.2f;
private const bool myDefaultDontCreateTextureFiles = false;
private const bool myDefaultExtractTexturesInRawFormat = false;
public const bool myDefaultEnableCooking = true;
public const bool myDefaultCookingTriggersDownCooks = true;
public const bool myDefaultPlaymodePerFrameCooking = false;
public const bool myDefaultPushUnityTransformToHoudini = true;
public const bool myDefaultTransformChangeTriggersCooks = false;
public const bool myDefaultImportTemplatedGeos = false;
public const bool myDefaultSplitGeosByGroup = true;
public const bool myDefaultSplitPointsByVertexAttributes = true;
private const string myDefaultUnityTagAttribName = "unity_tag";
private const float myDefaultPaintBrushRate = 0.2f; // Should be between zero and one.
private const KeyCode myDefaultPaintingModeHotKey = KeyCode.LeftShift;
private static Color myDefaultPaintingModeColour = new Color( 0.7f, 0.9f, 0.7f, 1.0f );
private const KeyCode myDefaultPaintingNodeSwitchHotKey = KeyCode.Q;
private const KeyCode myDefaultPaintingAttributeSwitchHotKey = KeyCode.W;
private const KeyCode myDefaultPaintingValueChangeHotKey = KeyCode.E;
private const KeyCode myDefaultPaintingFalloffChangeHotKey = KeyCode.R;
private const KeyCode myDefaultAddingPointsModeHotKey = KeyCode.LeftShift;
private static Color myDefaultAddingPointsModeColour = Color.yellow;
private const KeyCode myDefaultEditingPointsModeHotKey = KeyCode.LeftControl;
private static Color myDefaultEditingPointsModeColour = new Color( 0.7f, 0.7f, 0.9f, 1.0f );
private static Color myDefaultWireframeColour = new Color( 0.0f, 1.0f, 0.0f, 1.0f );
private static Color myDefaultGuideWireframeColour = new Color( 0.1f, 0.1f, 0.1f, 1.0f );
private static Color myDefaultUnselectableGuideWireframeColour = new Color( 0.1f, 0.1f, 0.1f, 1.0f );
private static Color myDefaultUnselectedGuideWireframeColour = Color.white;
private static Color myDefaultSelectedGuideWireframeColour = Color.yellow;
private const float myDefaultGuidePointSize = 10.0f;
private const float myDefaultMinDistanceForPointSelection = 8.0f;
private const float myDefaultGuideMinDistanceForMidPointInsertion = 5.0f;
private const bool myDefaultCreateGroupsFromBoolAttributes = false;
private const int myDefaultCurvePrimitiveTypeDefault = 1;
private const int myDefaultCurveMethodDefault = 1;
// Global Settings Undo Info --------------------------------------------------------------------------------
private static HoudiniHostUndoInfo myHostUndoInfo;
// Global Settings Initializations --------------------------------------------------------------------------
// This is to keep track whether we actually initialized Houdini Engine in this session/state/runtime of C#.
private static bool myCurrentCSharpSessionInitialized = false;
// License Type
private static HAPI_License myCurrentHoudiniLicense = HAPI_License.HAPI_LICENSE_NONE;
static HoudiniHost()
{
// Initialize the global session.
mySession.type = HAPI_SessionType.HAPI_SESSION_INPROCESS;
mySession.id = 0;
#if UNITY_EDITOR
EditorApplication.update += update;
EditorApplication.playmodeStateChanged += playmodeStateChanged;
EditorApplication.hierarchyWindowItemOnGUI += hierarchyWindowItemOnGUI;
SceneView.onSceneGUIDelegate += onSceneGUIDelegate;
#endif // UNITY_EDITOR
// Preferences
setString( "HAPI_CollisionGroupName", myDefaultCollisionGroupName, true );
setString( "HAPI_RenderedCollisionGroupName", myDefaultRenderedCollisionGroupName, true );
setString( "HAPI_UnityMaterialAttribName", myDefaultUnityMaterialAttribName, true );
setString( "HAPI_UnitySubMaterialNameAttribName", myDefaultUnitySubMaterialNameAttribName, true );
setString( "HAPI_UnitySubMaterialIndexAttribName", myDefaultUnitySubMaterialIndexAttribName, true );
setFloat( "HAPI_PinSize", myDefaultPinSize, true );
setColour( "HAPI_PinColour", myDefaultPinColour, true );
setBool( "HAPI_AutoPinInstances", myDefaultAutoPinInstances, true );
setBool( "HAPI_EnableSupportWarnings", myDefaultEnableSupportWarnings, true );
setBool( "HAPI_EnablePointsAsParticles", myDefaultEnablePointsAsParticles, true );
setFloat( "HAPI_Gamma", myDefaultGamma, true );
setBool( "HAPI_DontCreateTextureFiles", myDefaultDontCreateTextureFiles, true );
setBool( "HAPI_ExtractTexturesInRawFormat", myDefaultExtractTexturesInRawFormat, true );
setBool( "HAPI_EnableCooking", myDefaultEnableCooking, true );
setBool( "HAPI_CookingTriggersDownCooks", myDefaultCookingTriggersDownCooks, true );
setBool( "HAPI_PlaymodePerFrameCooking", myDefaultPlaymodePerFrameCooking, true );
setBool( "HAPI_PushUnityTransformToHoudini", myDefaultPushUnityTransformToHoudini, true );
setBool( "HAPI_TransformChangeTriggersCooks", myDefaultTransformChangeTriggersCooks, true );
setBool( "HAPI_ImportTemplatedGeos", myDefaultImportTemplatedGeos, true );
setBool( "HAPI_SplitGeosByGroup", myDefaultSplitGeosByGroup, true );
setBool( "HAPI_SplitPointsByVertexAttributes", myDefaultSplitPointsByVertexAttributes, true );
setString( "HAPI_UnityTagAttribName", myDefaultUnityTagAttribName, true );
setFloat( "HAPI_PaintBrushRate", myDefaultPaintBrushRate, true );
setKeyCode( "HAPI_PaintingHotKey", myDefaultPaintingModeHotKey, true );
setColour( "HAPI_PaintingModeColour", myDefaultPaintingModeColour, true );
setKeyCode( "HAPI_PaintingNodeSwitchHotKey", myDefaultPaintingNodeSwitchHotKey, true );
setKeyCode( "HAPI_PaintingAttributeSwitchHotKey", myDefaultPaintingAttributeSwitchHotKey, true );
setKeyCode( "HAPI_PaintingValueChangeHotKey", myDefaultPaintingValueChangeHotKey, true );
setKeyCode( "HAPI_PaintingFalloffChangeHotKey", myDefaultPaintingFalloffChangeHotKey, true );
setKeyCode( "HAPI_AddingPointsHotKey", myDefaultAddingPointsModeHotKey, true );
setColour( "HAPI_AddingPointsModeColour", myDefaultAddingPointsModeColour, true );
setKeyCode( "HAPI_EditingPointsHotKey", myDefaultEditingPointsModeHotKey, true );
setColour( "HAPI_EditingPointsModeColour", myDefaultEditingPointsModeColour, true );
setColour( "HAPI_WireframeColour", myDefaultWireframeColour, true );
setColour( "HAPI_GuideWireframeColour", myDefaultGuideWireframeColour, true );
setColour( "HAPI_UnselectableGuideWireframeColour", myDefaultUnselectableGuideWireframeColour, true );
setColour( "HAPI_UnselectedGuideWireframeColour", myDefaultUnselectedGuideWireframeColour, true );
setColour( "HAPI_SelectedGuideWireframeColour", myDefaultSelectedGuideWireframeColour, true );
setFloat( "HAPI_GuidePointSize", myDefaultGuidePointSize, true );
setFloat( "HAPI_MinDistanceForPointSelection", myDefaultMinDistanceForPointSelection, true );
setFloat( "HAPI_GuideMinDistanceForMidPointInsertion", myDefaultGuideMinDistanceForMidPointInsertion, true );
setBool( "HAPI_CreateGroupsFromBoolAttributes", myDefaultCreateGroupsFromBoolAttributes, true );
setInt( "HAPI_CurvePrimitiveTypeDefault", myDefaultCurvePrimitiveTypeDefault, true );
setInt( "HAPI_CurveMethodDefault", myDefaultCurveMethodDefault, true );
myRepaintDelegate = null;
myDeselectionDelegate = null;
mySelectionTarget = null;
}
public static bool initializeHost()
{
#if ( HAPI_ENABLE_RUNTIME )
// During the batch creation of our .unitypackage file we don't want to actually
// initialize We use this environment variable to inhibit initialization.
string no_init = System.Environment.GetEnvironmentVariable( "HAPI_UNITY_NO_INIT" );
if ( no_init != null )
return false;
#endif // ( HAPI_ENABLE_RUNTIME )
if ( isRuntimeInitialized() )
{
// Just make sure the session is properly initialized.
return initializeSession();
}
else
{
#if ( HAPI_ENABLE_RUNTIME )
#if UNITY_EDITOR
// It's important here to reset prMidPlaymodeStateChange to the playmode state,
// not just reset it to false. This is because this part will be called DURING
// a playmode change because myCurrentCSharpSessionInitialized will be
// invalidated at that point.
prMidPlaymodeStateChange = EditorApplication.isPlayingOrWillChangePlaymode;
#endif // UNITY_EDITOR
#endif // ( HAPI_ENABLE_RUNTIME )
// Call HAPI_Initialize() if needed.
if ( !initialize() )
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public
// Global Settings Properties -------------------------------------------------------------------------------
public static bool prHoudiniSceneExists {
get { return HoudiniDataFile.getBool( "HoudiniSceneExists", false ); }
private set { HoudiniDataFile.setBool( "HoudiniSceneExists", value ); } }
public static bool prMidPlaymodeStateChange {
get { return getBool( "HAPI_MidPlaymodeStateChange" ); }
private set { setBool( "HAPI_MidPlaymodeStateChange", value ); } }
public static string prCollisionGroupName {
get { return getString( "HAPI_CollisionGroupName" ); }
set { setString( "HAPI_CollisionGroupName", value ); } }
public static string prRenderedCollisionGroupName {
get { return getString( "HAPI_RenderedCollisionGroupName" ); }
set { setString( "HAPI_RenderedCollisionGroupName", value ); } }
public static string prUnityMaterialAttribName {
get { return getString( "HAPI_UnityMaterialAttribName" ); }
set { setString( "HAPI_UnityMaterialAttribName", value ); } }
public static string prUnitySubMaterialNameAttribName {
get { return getString( "HAPI_UnitySubMaterialNameAttribName" ); }
set { setString( "HAPI_UnitySubMaterialNameAttribName", value ); } }
public static string prUnitySubMaterialIndexAttribName {
get { return getString( "HAPI_UnitySubMaterialIndexAttribName" ); }
set { setString( "HAPI_UnitySubMaterialIndexAttribName", value ); } }
public static float prPinSize {
get { return getFloat( "HAPI_PinSize" ); }
set { setFloat( "HAPI_PinSize", value ); } }
public static Color prPinColour {
get { return getColour( "HAPI_PinColour" ); }
set { setColour( "HAPI_PinColour", value ); } }
public static bool prAutoPinInstances {
get { return getBool( "HAPI_AutopinInstances" ); }
set { setBool( "HAPI_AutopinInstances", value ); } }
public static bool prEnableSupportWarnings {
get { return getBool( "HAPI_EnableSupportWarnings" ); }
set { setBool( "HAPI_EnableSupportWarnings", value ); } }
public static bool prEnablePointsAsParticles {
get { return getBool( "HAPI_EnablePointsAsParticles" ); }
set { setBool( "HAPI_EnablePointsAsParticles", value ); } }
public static float prGamma {
get { return getFloat( "HAPI_Gamma" ); }
set { setFloat( "HAPI_Gamma", value ); } }
public static bool prDontCreateTextureFiles {
get { return getBool( "HAPI_DontCreateTextureFiles" ); }
set { setBool( "HAPI_DontCreateTextureFiles", value ); } }
public static bool prExtractTexturesInRawFormat {
get { return getBool( "HAPI_ExtractTexturesInRawFormat" ); }
set { setBool( "HAPI_ExtractTexturesInRawFormat", value ); } }
public static bool prEnableCooking {
#if UNITY_EDITOR
get { return getBool( "HAPI_EnableCooking" ); }
set { setBool( "HAPI_EnableCooking", value ); }
#else
get { return getBool( "HAPI_EnableCooking" ); }
set {}
#endif // UNITY_EDITOR
}
public static bool prCookingTriggersDownCooks {
get { return getBool( "HAPI_CookingTriggersDownCooks" ); }
set { setBool( "HAPI_CookingTriggersDownCooks", value ); } }
public static bool prPlaymodePerFrameCooking {
get { return getBool( "HAPI_PlaymodePerFrameCooking" ); }
set { setBool( "HAPI_PlaymodePerFrameCooking", value ); } }
public static bool prPushUnityTransformToHoudini {
get { return getBool( "HAPI_PushUnityTransformToHoudini" ); }
set { setBool( "HAPI_PushUnityTransformToHoudini", value ); } }
public static bool prTransformChangeTriggersCooks {
get { return getBool( "HAPI_TransformChangeTriggersCooks" ); }
set { setBool( "HAPI_TransformChangeTriggersCooks", value ); } }
public static bool prImportTemplatedGeos {
get { return getBool( "HAPI_ImportTemplatedGeos" ); }
set { setBool( "HAPI_ImportTemplatedGeos", value ); } }
public static bool prSplitGeosByGroup {
get { return getBool( "HAPI_SplitGeosByGroup" ); }
set { setBool( "HAPI_SplitGeosByGroup", value ); } }
public static bool prSplitPointsByVertexAttributes {
get { return getBool( "HAPI_SplitPointsByVertexAttributes" ); }
set { setBool( "HAPI_SplitPointsByVertexAttributes", value ); } }
public static string prUnityTagAttribName {
get { return getString( "HAPI_UnityTagAttribName" ); }
set { setString( "HAPI_UnityTagAttribName", value ); } }
public static float prPaintBrushRate {
get { return getFloat( "HAPI_PaintBrushRate" ); }
set { setFloat(
"HAPI_PaintBrushRate",
Mathf.Clamp( value, 0.0f, 1.0f ) ); } }
public static KeyCode prPaintingModeHotKey {
get { KeyCode key = getKeyCode( "HAPI_PaintingModeHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultPaintingModeHotKey;
setKeyCode( "HAPI_PaintingModeHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_PaintingModeHotKey", value ); } }
public static Color prPaintingModeColour {
get { return getColour( "HAPI_PaintingModeColour" ); }
set { setColour( "HAPI_PaintingModeColour", value ); } }
public static KeyCode prPaintingNodeSwitchHotKey {
get { KeyCode key = getKeyCode( "HAPI_PaintingNodeSwitchHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultPaintingNodeSwitchHotKey;
setKeyCode( "HAPI_PaintingNodeSwitchHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_PaintingNodeSwitchHotKey", value ); } }
public static KeyCode prPaintingAttributeSwitchHotKey {
get { KeyCode key = getKeyCode( "HAPI_PaintingAttributeSwitchHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultPaintingAttributeSwitchHotKey;
setKeyCode( "HAPI_PaintingAttributeSwitchHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_PaintingAttributeSwitchHotKey", value ); } }
public static KeyCode prPaintingValueChangeHotKey {
get { KeyCode key = getKeyCode( "HAPI_PaintingValueChangeHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultPaintingValueChangeHotKey;
setKeyCode( "HAPI_PaintingValueChangeHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_PaintingValueChangeHotKey", value ); } }
public static KeyCode prPaintingFalloffChangeHotKey {
get { KeyCode key = getKeyCode( "HAPI_PaintingFalloffChangeHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultPaintingFalloffChangeHotKey;
setKeyCode( "HAPI_PaintingFalloffChangeHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_PaintingFalloffChangeHotKey", value ); } }
public static KeyCode prAddingPointsModeHotKey {
get { KeyCode key = getKeyCode( "HAPI_AddingPointsModeHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultAddingPointsModeHotKey;
setKeyCode( "HAPI_AddingPointsModeHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_AddingPointsModeHotKey", value ); } }
public static Color prAddingPointsModeColour {
get { return getColour( "HAPI_AddingPointsModeColour" ); }
set { setColour( "HAPI_AddingPointsModeColour", value ); } }
public static KeyCode prEditingPointsModeHotKey {
get { KeyCode key = getKeyCode( "HAPI_EditingPointsModeHotKey" );
if ( key == KeyCode.None ) {
key = myDefaultEditingPointsModeHotKey;
setKeyCode( "HAPI_EditingPointsModeHotKey", key ); }
return key; }
set { setKeyCode( "HAPI_EditingPointsModeHotKey", value ); } }
public static Color prEditingPointsModeColour {
get { return getColour( "HAPI_EditingPointsModeColour" ); }
set { setColour( "HAPI_EditingPointsModeColour", value ); } }
public static Color prWireframeColour {
get { return getColour( "HAPI_WireframeColour" ); }
set { setColour( "HAPI_WireframeColour", value ); } }
public static Color prGuideWireframeColour {
get { return getColour( "HAPI_GuideWireframeColour" ); }
set { setColour( "HAPI_GuideWireframeColour", value ); } }
public static Color prUnselectableGuideWireframeColour {
get { return getColour( "HAPI_UnselectableGuideWireframeColour" ); }
set { setColour( "HAPI_UnselectableGuideWireframeColour", value ); } }
public static Color prUnselectedGuideWireframeColour {
get { return getColour( "HAPI_UnselectedGuideWireframeColour" ); }
set { setColour( "HAPI_UnselectedGuideWireframeColour", value ); } }
public static Color prSelectedGuideWireframeColour {
get { return getColour( "HAPI_SelectedGuideWireframeColour" ); }
set { setColour( "HAPI_SelectedGuideWireframeColour", value ); } }
public static float prGuidePointSize {
get { return getFloat( "HAPI_GuidePointSize" ); }
set { setFloat( "HAPI_GuidePointSize", value ); } }
public static float prMinDistanceForPointSelection {
get { return getFloat( "HAPI_MinDistanceForPointSelection" ); }
set { setFloat( "HAPI_MinDistanceForPointSelection", value ); } }
public static float prGuideMinDistanceForMidPointInsertion {
get { return getFloat( "HAPI_GuideMinDistanceForMidPointInsertion" ); }
set { setFloat( "HAPI_GuideMinDistanceForMidPointInsertion", value ); } }
public static bool prCreateGroupsFromBoolAttributes {
get { return getBool( "HAPI_CreateGroupsFromBoolAttributes" ); }
set { setBool( "HAPI_CreateGroupsFromBoolAttributes", value ); } }
public static int prCurvePrimitiveTypeDefault {
get { return getInt( "HAPI_CurvePrimitiveTypeDefault" ); }
set { setInt( "HAPI_CurvePrimitiveTypeDefault", value ); } }
public static int prCurveMethodDefault {
get { return getInt( "HAPI_CurveMethodDefault" ); }
set { setInt( "HAPI_CurveMethodDefault", value ); } }
// Global Settings Undo Info --------------------------------------------------------------------------------
public static HoudiniHostUndoInfo prHostUndoInfo
{
get
{
if ( myHostUndoInfo == null )
myHostUndoInfo = ScriptableObject.CreateInstance< HoudiniHostUndoInfo >();
return myHostUndoInfo;
}
set { myHostUndoInfo = value; }
}
// Global Settings Default Checks ---------------------------------------------------------------------------
public static bool isCollisionGroupNameDefault()
{ return prCollisionGroupName ==
myDefaultCollisionGroupName; }
public static bool isRenderedCollisionGroupNameDefault()
{ return prRenderedCollisionGroupName ==
myDefaultRenderedCollisionGroupName; }
public static bool isUnityMaterialAttribNameDefault()
{ return prUnityMaterialAttribName ==
myDefaultUnityMaterialAttribName; }
public static bool isUnitySubMaterialNameAttribNameDefault()
{ return prUnitySubMaterialNameAttribName ==
myDefaultUnitySubMaterialNameAttribName; }
public static bool isUnitySubMaterialIndexAttribNameDefault()
{ return prUnitySubMaterialIndexAttribName ==
myDefaultUnitySubMaterialIndexAttribName; }
public static bool isPinSizeDefault()
{ return prPinSize ==
myDefaultPinSize; }
public static bool isPinColourDefault()
{ return prPinColour ==
myDefaultPinColour; }
public static bool isAutoPinInstancesDefault()
{ return prAutoPinInstances ==
myDefaultAutoPinInstances; }
public static bool isEnableSupportWarningsDefault()
{ return prEnableSupportWarnings ==
myDefaultEnableSupportWarnings; }
public static bool isGammaDefault()
{ return Mathf.Approximately(
prGamma, myDefaultGamma ); }
public static bool isDontCreateTextureFilesDefault()
{ return prDontCreateTextureFiles ==
myDefaultDontCreateTextureFiles; }
public static bool isExtractTexturesInRawFormatDefault()
{ return prExtractTexturesInRawFormat ==
myDefaultExtractTexturesInRawFormat; }
public static bool isEnableCookingDefault()
{ return prEnableCooking ==
myDefaultEnableCooking; }
public static bool isCookingTriggersDownCooksDefault()
{ return prCookingTriggersDownCooks ==
myDefaultCookingTriggersDownCooks; }
public static bool isPlaymodePerFrameCookingDefault()
{ return prPlaymodePerFrameCooking ==
myDefaultPlaymodePerFrameCooking; }
public static bool isPushUnityTransformToHoudiniDefault()
{ return prPushUnityTransformToHoudini ==
myDefaultPushUnityTransformToHoudini; }
public static bool isTransformChangeTriggersCooksDefault()
{ return prTransformChangeTriggersCooks ==
myDefaultTransformChangeTriggersCooks; }
public static bool isImportTemplatedGeosDefault()
{ return prImportTemplatedGeos ==
myDefaultImportTemplatedGeos; }
public static bool isSplitGeosByGroupDefault()
{ return prSplitGeosByGroup ==
myDefaultSplitGeosByGroup; }
public static bool isSplitPointsByVertexAttributesDefault()
{ return prSplitPointsByVertexAttributes ==
myDefaultSplitPointsByVertexAttributes; }
public static bool isUnityTagAttribNameDefault()
{ return prUnityTagAttribName ==
myDefaultUnityTagAttribName; }
public static bool isPaintBrushRateDefault()
{ return prPaintBrushRate ==
myDefaultPaintBrushRate; }
public static bool isPaintingModeHotKeyDefault()
{ return prPaintingModeHotKey ==
myDefaultPaintingModeHotKey; }
public static bool isPaintingModeColourDefault()
{ return prPaintingModeColour ==
myDefaultPaintingModeColour; }
public static bool isPaintingNodeSwitchHotKeyDefault()
{ return prPaintingNodeSwitchHotKey ==
myDefaultPaintingNodeSwitchHotKey; }
public static bool isPaintingAttributeSwitchHotKeyDefault()
{ return prPaintingAttributeSwitchHotKey ==
myDefaultPaintingAttributeSwitchHotKey; }
public static bool isPaintingValueChangeHotKeyDefault()
{ return prPaintingValueChangeHotKey ==
myDefaultPaintingValueChangeHotKey; }
public static bool isPaintingFalloffChangeHotKeyDefault()
{ return prPaintingFalloffChangeHotKey ==
myDefaultPaintingFalloffChangeHotKey; }
public static bool isAddingPointsModeHotKeyDefault()
{ return prAddingPointsModeHotKey ==
myDefaultAddingPointsModeHotKey; }
public static bool isAddingPointsModeColourDefault()
{ return prAddingPointsModeColour ==
myDefaultAddingPointsModeColour; }
public static bool isEditingPointsModeHotKeyDefault()
{ return prEditingPointsModeHotKey ==
myDefaultEditingPointsModeHotKey; }
public static bool isEditingPointsModeColourDefault()
{ return prEditingPointsModeColour ==
myDefaultEditingPointsModeColour; }
public static bool isWireframeColourDefault()
{ return prWireframeColour ==
myDefaultWireframeColour; }
public static bool isGuideWireframeColourDefault()
{ return prGuideWireframeColour ==
myDefaultGuideWireframeColour; }
public static bool isUnselectableGuideWireframeColourDefault()
{ return prUnselectableGuideWireframeColour ==
myDefaultUnselectableGuideWireframeColour; }
public static bool isUnselectedGuideWireframeColourDefault()
{ return prUnselectedGuideWireframeColour ==
myDefaultUnselectedGuideWireframeColour; }
public static bool isSelectedGuideWireframeColourDefault()
{ return prSelectedGuideWireframeColour ==
myDefaultSelectedGuideWireframeColour; }
public static bool isGuidePointSizeDefault()
{ return prGuidePointSize ==
myDefaultGuidePointSize; }
public static bool isMinDistanceForPointSelectionDefault()
{ return prMinDistanceForPointSelection ==
myDefaultMinDistanceForPointSelection; }
public static bool isGuideMinDistanceForMidPointInsertionDefault()
{ return prGuideMinDistanceForMidPointInsertion ==
myDefaultGuideMinDistanceForMidPointInsertion; }
public static bool isCreateGroupsFromBoolAttributes()
{ return prCreateGroupsFromBoolAttributes ==
myDefaultCreateGroupsFromBoolAttributes; }
public static bool isCurvePrimitiveTypeDefaultDefault()
{ return prCurvePrimitiveTypeDefault ==
myDefaultCurvePrimitiveTypeDefault; }
public static bool isCurveMethodDefaultDefault()
{ return prCurveMethodDefault ==
myDefaultCurveMethodDefault; }
// Global Settings Revert To Defaults -----------------------------------------------------------------------
public static void revertAllSettingsToDefaults()
{
prCollisionGroupName = myDefaultCollisionGroupName;
prRenderedCollisionGroupName = myDefaultRenderedCollisionGroupName;
prUnityMaterialAttribName = myDefaultUnityMaterialAttribName;
prUnitySubMaterialNameAttribName = myDefaultUnitySubMaterialNameAttribName;
prUnitySubMaterialIndexAttribName = myDefaultUnitySubMaterialIndexAttribName;
prPinSize = myDefaultPinSize;
prPinColour = myDefaultPinColour;
prAutoPinInstances = myDefaultAutoPinInstances;
prEnableSupportWarnings = myDefaultEnableSupportWarnings;
prEnablePointsAsParticles = myDefaultEnablePointsAsParticles;
prGamma = myDefaultGamma;
prDontCreateTextureFiles = myDefaultDontCreateTextureFiles;
prExtractTexturesInRawFormat = myDefaultExtractTexturesInRawFormat;
prEnableCooking = myDefaultEnableCooking;
prCookingTriggersDownCooks = myDefaultCookingTriggersDownCooks;
prPlaymodePerFrameCooking = myDefaultPlaymodePerFrameCooking;
prPushUnityTransformToHoudini = myDefaultPushUnityTransformToHoudini;
prTransformChangeTriggersCooks = myDefaultTransformChangeTriggersCooks;
prImportTemplatedGeos = myDefaultImportTemplatedGeos;
prSplitGeosByGroup = myDefaultSplitGeosByGroup;
prSplitPointsByVertexAttributes = myDefaultSplitPointsByVertexAttributes;
prUnityTagAttribName = myDefaultUnityTagAttribName;
prPaintBrushRate = myDefaultPaintBrushRate;
prPaintingModeHotKey = myDefaultPaintingModeHotKey;
prPaintingModeColour = myDefaultPaintingModeColour;
prPaintingNodeSwitchHotKey = myDefaultPaintingNodeSwitchHotKey;
prPaintingAttributeSwitchHotKey = myDefaultPaintingAttributeSwitchHotKey;
prPaintingValueChangeHotKey = myDefaultPaintingValueChangeHotKey;
prPaintingFalloffChangeHotKey = myDefaultPaintingFalloffChangeHotKey;
prAddingPointsModeHotKey = myDefaultAddingPointsModeHotKey;
prAddingPointsModeColour = myDefaultAddingPointsModeColour;
prEditingPointsModeHotKey = myDefaultEditingPointsModeHotKey;
prEditingPointsModeColour = myDefaultEditingPointsModeColour;
prWireframeColour = myDefaultWireframeColour;
prGuideWireframeColour = myDefaultGuideWireframeColour;
prUnselectableGuideWireframeColour = myDefaultUnselectableGuideWireframeColour;
prUnselectedGuideWireframeColour = myDefaultUnselectedGuideWireframeColour;
prSelectedGuideWireframeColour = myDefaultSelectedGuideWireframeColour;
prGuidePointSize = myDefaultGuidePointSize;
prMinDistanceForPointSelection = myDefaultMinDistanceForPointSelection;
prGuideMinDistanceForMidPointInsertion = myDefaultGuideMinDistanceForMidPointInsertion;
prCreateGroupsFromBoolAttributes = myDefaultCreateGroupsFromBoolAttributes;
prCurvePrimitiveTypeDefault = myDefaultCurvePrimitiveTypeDefault;
prCurveMethodDefault = myDefaultCurveMethodDefault;
// Reset undo info so values match with above settings.
prHostUndoInfo.initialize();
}
public static RepaintDelegate myRepaintDelegate;
public static DeselectionDelegate myDeselectionDelegate;
public static PlaymodeStateChangeDelegate myPlaymodeStateChangeDelegate;
public static GameObject mySelectionTarget;
public static void saveScene( string file_name, bool lock_nodes )
{
#if ( HAPI_ENABLE_RUNTIME )
HAPI_SaveHIPFile( ref mySession, file_name, lock_nodes );
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static int loadOTL(
string path, bool split_geos_by_group, bool split_points_by_vertex_attributes, bool import_templated_geos,
HoudiniProgressBar progress_bar )
{
return loadOTL(
path,
split_geos_by_group,
split_points_by_vertex_attributes,
import_templated_geos,
progress_bar,
true );
}
public static int loadOTL(
string path, bool split_geos_by_group, bool split_points_by_vertex_attributes, bool import_templated_geos,
HoudiniProgressBar progress_bar, bool allow_asset_def_overwrite )
{
#if ( HAPI_ENABLE_RUNTIME )
if ( !isInstallationOk() )
throw new HoudiniError( "DLL Not Found." );
int library_id = -1;
HAPI_Result status_code;
// This can be used to test in-memory OTL loading.
#if false
byte[] file = File.ReadAllBytes( path );
status_code = HAPI_LoadAssetLibraryFromMemory(
file, file.Length, allow_asset_def_overwrite, out library_id );
#else
#if UNITY_EDITOR
status_code = HAPI_LoadAssetLibraryFromFile(
ref mySession, path, allow_asset_def_overwrite, out library_id );
if ( status_code == HAPI_Result.HAPI_RESULT_ASSET_DEF_ALREADY_LOADED )
{
if ( EditorUtility.DisplayDialog(
"Houdini Asset Definition Overwriting",
"The asset library file being loaded: \n" + path + "\n" +
"contains asset defintions that have already been loaded before from " +
"another asset library file. \n\nWould you like to overwrite them?",
"Yes", "No" ) )
{
status_code = HAPI_LoadAssetLibraryFromFile( ref mySession, path, true, out library_id );
}
}
#else
status_code = HAPI_LoadAssetLibraryFromFile( ref mySession, path, true, out library_id );
#endif // UNITY_EDITOR
#endif // HAPI_LoadAssetLibraryFromMemory
processStatusCode( status_code );
int asset_count = 0;
status_code = HAPI_GetAvailableAssetCount( ref mySession, library_id, out asset_count );
processStatusCode( status_code );
int[] asset_names_sh = new int[ asset_count ];
status_code = HAPI_GetAvailableAssets( ref mySession, library_id, asset_names_sh, asset_count );
processStatusCode( status_code );
string[] asset_names = new string[ asset_count ];
for ( int i = 0; i < asset_count; ++i )
{
asset_names[ i ] = getString( asset_names_sh[ i ] );
//Debug.Log( asset_names[ i ] );
}
int asset_id = -1;
string first_asset_name = asset_names[ 0 ];
bool cook_on_load = false;
status_code = HAPI_InstantiateAsset( ref mySession, first_asset_name, cook_on_load, out asset_id );
processStatusCode( status_code );
progress_bar.statusCheckLoop();
cookAsset( asset_id, split_geos_by_group, split_points_by_vertex_attributes, import_templated_geos );
progress_bar.statusCheckLoop();
return asset_id;
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static void loadHip( string path )
{
#if ( HAPI_ENABLE_RUNTIME )
if ( !isInstallationOk() )
throw new HoudiniError( "DLL Not Found." );
HAPI_Result status_code = HAPI_LoadHIPFile( ref mySession, path, true );
processStatusCode( status_code );
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static int[] getNewAssetIds()
{
#if ( HAPI_ENABLE_RUNTIME )
int asset_count = 0;
HAPI_Result status_code = HAPI_CheckForNewAssets( ref mySession, ref asset_count );
processStatusCode( status_code );
int[] asset_ids_array = new int[ asset_count ];
status_code = HAPI_GetNewAssetIds( ref mySession, asset_ids_array, asset_count );
processStatusCode( status_code );
return asset_ids_array;
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static int createCurve()
{
#if ( HAPI_ENABLE_RUNTIME )
if ( !isInstallationOk() )
throw new HoudiniError( "DLL Not Found." );
int asset_id = -1;
HAPI_Result status_code = HAPI_CreateCurve( ref mySession, out asset_id );
processStatusCode( status_code );
return asset_id;
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static int createInputAsset( string name )
{
#if ( HAPI_ENABLE_RUNTIME )
if ( !isInstallationOk() )
throw new HoudiniError( "DLL Not Found." );
int asset_id = -1;
HAPI_Result status_code = HAPI_CreateInputAsset( ref mySession, out asset_id, name );
processStatusCode( status_code );
return asset_id;
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static bool destroyAsset( int asset_id )
{
#if ( HAPI_ENABLE_RUNTIME )
if ( asset_id < 0 || !isInstallationOk() )
return false;
HAPI_Result result = HAPI_DestroyAsset( ref mySession, asset_id );
processStatusCode( result );
return true;
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static HAPI_CookOptions getCookOptions(
bool split_geos_by_group, bool split_points_by_vertex_attributes, bool import_templated_geos )
{
HAPI_CookOptions cook_options = new HAPI_CookOptions();
cook_options.splitGeosByGroup = split_geos_by_group;
cook_options.maxVerticesPerPrimitive = HoudiniConstants.HAPI_MAX_VERTICES_PER_FACE;
cook_options.refineCurveToLinear = HoudiniConstants.HAPI_CURVE_REFINE_TO_LINEAR;
cook_options.curveRefineLOD = HoudiniConstants.HAPI_CURVE_LOD;
cook_options.cookTemplatedGeos = import_templated_geos;
cook_options.clearErrorsAndWarnings = split_points_by_vertex_attributes;
cook_options.packedPrimInstancingMode =
HAPI_PackedPrimInstancingMode.HAPI_PACKEDPRIM_INSTANCING_MODE_DISABLED;
return cook_options;
}
public static HAPI_CookOptions getCookOptions()
{
return getCookOptions( prSplitGeosByGroup, prSplitPointsByVertexAttributes, prImportTemplatedGeos );
}
public static bool isRealDestroy()
{
#if UNITY_EDITOR
bool is_playing_or_will_change_playmode = !EditorApplication.isPlayingOrWillChangePlaymode;
bool is_mid_playmode_state_change = prMidPlaymodeStateChange;
bool answer = !is_playing_or_will_change_playmode && !is_mid_playmode_state_change;
return answer;
#else
return true;
#endif // UNITY_EDITOR
}
public static string getCallErrorMessage()
{
// It is important that we use the NoExceptions version of getStatusString because
// getStatusString() will also call throwCallError() if it fails which then
// ends up calling itself and...stack overflow. :)
return getStatusStringNoExceptions(
HAPI_StatusType.HAPI_STATUS_CALL_RESULT,
HAPI_StatusVerbosity.HAPI_STATUSVERBOSITY_WARNINGS );
}
public static string getCookErrorMessage()
{
// It is important that we use the NoExceptions version of getStatusString because
// getStatusString() will also call throwCallError() if it fails which then
// ends up calling itself and...stack overflow. :)
return getStatusStringNoExceptions(
HAPI_StatusType.HAPI_STATUS_COOK_RESULT,
HAPI_StatusVerbosity.HAPI_STATUSVERBOSITY_WARNINGS );
}
public static void throwCallError()
{
#if ( HAPI_ENABLE_RUNTIME )
int code;
HAPI_GetStatus( ref mySession, HAPI_StatusType.HAPI_STATUS_CALL_RESULT, out code );
string status_string = getCallErrorMessage();
if ( code == (int) HAPI_Result.HAPI_RESULT_INVALID_ARGUMENT )
throw new HoudiniErrorInvalidArgument( status_string );
else if ( code == (int) HAPI_Result.HAPI_RESULT_ASSET_DEF_ALREADY_LOADED )
throw new HoudiniErrorAssetDefOverride( status_string );
else
throw new HoudiniError( status_string );
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static void throwCookError()
{
#if ( HAPI_ENABLE_RUNTIME )
int code;
HAPI_GetStatus( ref mySession, HAPI_StatusType.HAPI_STATUS_COOK_RESULT, out code );
string status_string = getCookErrorMessage();
if ( code == (int) HAPI_Result.HAPI_RESULT_INVALID_ARGUMENT )
throw new HoudiniErrorInvalidArgument( status_string );
else
throw new HoudiniError( status_string );
#else
throw new HoudiniErrorUnsupportedPlatform();
#endif // ( HAPI_ENABLE_RUNTIME )
}
public static void repaint()
{
if ( myRepaintDelegate != null )
myRepaintDelegate();
}
public static HoudiniAsset[] getAssets()
{
return UnityEngine.Object.FindObjectsOfType( typeof( HoudiniAsset ) ) as HoudiniAsset[];
}
public static void log( string message )
{
message = processStringForConsole( message );
Debug.Log( message );
}
public static void logWarning( string message )
{
message = processStringForConsole( message );
Debug.LogWarning( message );
}
public static void logError( string message )
{
message = processStringForConsole( message );
Debug.LogError( message );
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private
private static string processStringForConsole( string str )
{
// Truncate the message manually due to bug:
// http://fogbugz.unity3d.com/default.asp?621738_mhks4v903k1799iv
if ( str.Length > 10000 )
{
str = str.Substring( 0, 9000 );
str += "...";
}
return str;
}
private static void update()
{
#if UNITY_EDITOR
// We need to catch any exceptions here because if we let any out they will stall
// the entire callback chain bound to EditorApplication.update which
// causes other bound functions in this callback list to never be called.
try
{
if ( HoudiniHost.mySelectionTarget != null && myDeselectionDelegate != null )
{
GameObject selected = Selection.activeGameObject;
if ( selected != mySelectionTarget )
myDeselectionDelegate();
}
}
catch ( System.Exception error )
{
Debug.Log( error.ToString() + "\nSource: " + error.Source );
}
#endif // UNITY_EDITOR
}
private static void playmodeStateChanged()
{
#if UNITY_EDITOR && ( HAPI_ENABLE_RUNTIME )
// We need to catch any exceptions here because if we let any out they will stall
// the entire callback chain bound to EditorApplication.playmodeStateChanged which
// causes other bound functions in this callback list to never be called.
try
{
prMidPlaymodeStateChange = !prMidPlaymodeStateChange;
if ( prMidPlaymodeStateChange )
{
if ( isInstallationOk() )
setTime( 0.0f );
if ( myPlaymodeStateChangeDelegate != null )
myPlaymodeStateChangeDelegate();
}
}
catch ( System.Exception error )
{
Debug.Log( error.ToString() + "\nSource: " + error.Source );
}
#endif // UNITY_EDITOR && ( HAPI_ENABLE_RUNTIME )
}
#if UNITY_EDITOR
private static void hierarchyWindowItemOnGUI( int instanceID, Rect selectionRect )
{
processDragEvent( Event.current, null );
}
private static void onSceneGUIDelegate( SceneView sceneView )
{
processDragEvent( Event.current, sceneView );
}
private static bool isHoudiniAssetFile( string path )
{
return ( path.EndsWith( ".otl" ) || path.EndsWith( ".otllc" ) || path.EndsWith( ".otlnc" )
|| path.EndsWith( ".hda" ) || path.EndsWith( ".hdalc" ) || path.EndsWith( ".hdanc" ) );
}
private static void processDragEvent( Event drag_event, SceneView scene_view )
{
if ( drag_event != null &&
( drag_event.type == EventType.DragUpdated || drag_event.type == EventType.DragPerform ) )
{
bool drag_contains_otls = false;
foreach ( string path in DragAndDrop.paths )
if ( isHoudiniAssetFile( path ) )
{
drag_contains_otls = true;
DragAndDrop.visualMode = DragAndDropVisualMode.Move;
break;
}
if ( drag_event.type == EventType.DragPerform )
{
Vector3 initial_asset_position = new Vector3( 0.0f, 0.0f, 0.0f );
if ( scene_view )
{
Camera camera = scene_view.camera;
Vector3 mouse_position = drag_event.mousePosition;
// Camera.current.pixelHeight != Screen.height for some reason.
mouse_position.y = camera.pixelHeight - mouse_position.y;
Ray ray = camera.ScreenPointToRay( mouse_position );
ray.origin = camera.transform.position;
Plane plane = new Plane();
plane.SetNormalAndPosition( Vector3.up, Vector3.zero );
float enter = 0.0f;
plane.Raycast( ray, out enter );
enter = Mathf.Clamp( enter, camera.nearClipPlane, camera.farClipPlane );
initial_asset_position = ray.origin + ray.direction * enter;
}
for ( int i = 0; i < DragAndDrop.paths.Length; ++i )
{
string path = DragAndDrop.paths[ i ];
if ( isHoudiniAssetFile( path ) )
{
if ( !isInstallationOk() )
displayHoudiniEngineInstallInfo();
else
HoudiniAssetUtility.instantiateAsset( path, initial_asset_position );
}
}
}
if ( drag_contains_otls )
drag_event.Use();
}
}
#endif // UNITY_EDITOR
private static bool hasCallFailed( HAPI_Result code )
{
return ( (int) code > 0 );
}
private static void processStatusCode( HAPI_Result code )
{
if ( hasCallFailed( code ) )
throwCallError();
}
private static int getInt( string name )
{
#if UNITY_EDITOR
return EditorPrefs.GetInt( name );
#else
return PlayerPrefs.GetInt( name );
#endif // UNITY_EDITOR
}
private static void setInt( string name, int value )
{
setInt( name, value, false );
}
private static void setInt( string name, int value, bool only_if_new )
{
#if UNITY_EDITOR
if ( !only_if_new || !EditorPrefs.HasKey( name ) )
{
EditorPrefs.SetInt( name, value );
PlayerPrefs.SetInt( name, value );
}
#else
if ( !only_if_new || !PlayerPrefs.HasKey( name ) )
PlayerPrefs.SetInt( name, value );
#endif // UNITY_EDITOR
}
private static bool getBool( string name )
{
#if UNITY_EDITOR
return EditorPrefs.GetInt( name ) == 0 ? false : true;
#else
return PlayerPrefs.GetInt( name ) == 0 ? false : true;
#endif // UNITY_EDITOR
}
private static void setBool( string name, bool value )
{
setBool( name, value, false );
}
private static void setBool( string name, bool value, bool only_if_new )
{
#if UNITY_EDITOR
if ( !only_if_new || !EditorPrefs.HasKey( name ) )
{
EditorPrefs.SetInt( name, value ? 1 : 0 );
PlayerPrefs.SetInt( name, value ? 1 : 0 );
}
#else
if ( !only_if_new || !PlayerPrefs.HasKey( name ) )
PlayerPrefs.SetInt( name, value ? 1 : 0 );
#endif // UNITY_EDITOR
}
private static float getFloat( string name )
{
#if UNITY_EDITOR
return EditorPrefs.GetFloat( name );
#else
return PlayerPrefs.GetFloat( name );
#endif // UNITY_EDITOR
}
private static void setFloat( string name, float value )
{
setFloat( name, value, false );
}
private static void setFloat( string name, float value, bool only_if_new )
{
#if UNITY_EDITOR
if ( !only_if_new || !EditorPrefs.HasKey( name ) )
{
EditorPrefs.SetFloat( name, value );
PlayerPrefs.SetFloat( name, value );
}
#else
if ( !only_if_new || !PlayerPrefs.HasKey( name ) )
PlayerPrefs.SetFloat( name, value );
#endif // UNITY_EDITOR
}
private static string getString( string name )
{
#if UNITY_EDITOR
return EditorPrefs.GetString( name );
#else
return PlayerPrefs.GetString( name );
#endif // UNITY_EDITOR
}
private static void setString( string name, string value )
{
setString( name, value, false );
}
private static void setString( string name, string value, bool only_if_new )
{
#if UNITY_EDITOR
if ( !only_if_new || !EditorPrefs.HasKey( name ) )
{
EditorPrefs.SetString( name, value );
PlayerPrefs.SetString( name, value );
}
#else
if ( !only_if_new || !PlayerPrefs.HasKey( name ) )
PlayerPrefs.SetString( name, value );
#endif // UNITY_EDITOR
}
private static KeyCode getKeyCode( string name )
{
return (KeyCode) getInt( name );
}
private static void setKeyCode( string name, KeyCode value )
{
setKeyCode( name, value, false );
}
private static void setKeyCode( string name, KeyCode value, bool only_if_new )
{
setInt( name, (int) value, only_if_new );
}
private static Color getColour( string name )
{
return new Color( getFloat( name + "_r" ), getFloat( name + "_g" ),
getFloat( name + "_b" ), getFloat( name + "_a" ) );
}
private static void setColour( string name, Color value )
{
setColour( name, value, false );
}
private static void setColour( string name, Color value, bool only_if_new )
{
setFloat( name + "_r", value.r, only_if_new );
setFloat( name + "_g", value.g, only_if_new );
setFloat( name + "_b", value.b, only_if_new );
setFloat( name + "_a", value.a, only_if_new );
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentQueueTests
{
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
var q = new ConcurrentQueue<int>();
Assert.True(q.IsEmpty);
Assert.Equal(0, q.Count);
Assert.Equal(Enumerable.Empty<int>(), q);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
var q = new ConcurrentQueue<int>(Enumerable.Range(1, count));
Assert.Equal(count == 0, q.IsEmpty);
Assert.Equal(count, q.Count);
Assert.Equal(Enumerable.Range(1, count), q);
}
[Fact]
public void Ctor_NullEnumerable_Throws()
{
Assert.Throws<ArgumentNullException>("collection", () => new ConcurrentQueue<int>(null));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public static void ToArray_ItemsAndCountMatch(int count)
{
ConcurrentQueue<int> q = new ConcurrentQueue<int>(Enumerable.Range(42, count));
Assert.Equal(Enumerable.Range(42, count), q.ToArray());
if (count > 0)
{
int item;
Assert.True(q.TryDequeue(out item));
Assert.Equal(42, item);
Assert.Equal(Enumerable.Range(43, count - 1), q.ToArray());
}
}
[Fact]
public void DebuggerAttributes_Success()
{
var q = new ConcurrentQueue<int>(Enumerable.Range(0, 10));
DebuggerAttributes.ValidateDebuggerDisplayReferences(q);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(q);
}
[Fact]
public void Enqueue_TryDequeue_MatchesQueue()
{
var q = new Queue<int>();
var cq = new ConcurrentQueue<int>();
Action dequeue = () =>
{
int item1 = q.Dequeue();
int item2;
Assert.True(cq.TryDequeue(out item2));
Assert.Equal(item1, item2);
Assert.Equal(q.Count, cq.Count);
Assert.Equal(q, cq);
};
for (int i = 0; i < 100; i++)
{
cq.Enqueue(i);
q.Enqueue(i);
Assert.Equal(q.Count, cq.Count);
Assert.Equal(q, cq);
// Start dequeueing some after we've added some
if (i > 50)
{
dequeue();
}
}
// Dequeue the rest
while (q.Count > 0)
{
dequeue();
}
}
[Fact]
public void TryPeek_Idempotent()
{
var cq = new ConcurrentQueue<int>();
int item;
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
cq.Enqueue(42);
Assert.True(cq.TryPeek(out item));
Assert.Equal(42, item);
Assert.True(cq.TryPeek(out item));
Assert.Equal(42, item);
Assert.True(cq.TryDequeue(out item));
Assert.Equal(42, item);
Assert.False(cq.TryPeek(out item));
Assert.Equal(0, item);
}
[Fact]
public void Concurrent_Enqueue_TryDequeue_AllItemsReceived()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer dequeues items until it gets as many as it expects
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryDequeue(out item))
{
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
else
{
Assert.Equal(0, item);
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
// Consumer peeks and then dequeues the expected number of items
Task consumer = Task.Run(() =>
{
int lastReceived = 0;
int item;
while (true)
{
if (q.TryPeek(out item))
{
Assert.Equal(lastReceived + 1, item);
Assert.True(q.TryDequeue(out item));
Assert.Equal(lastReceived + 1, item);
lastReceived = item;
if (item == items) break;
}
}
});
// Producer queues the expected number of items
Task producer = Task.Run(() =>
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_EnqueueDequeue_IsEmpty_AlwaysFalse()
{
int items = 1000;
var q = new ConcurrentQueue<int>();
q.Enqueue(0); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(q.IsEmpty);
});
// Producer enqueues/dequeues a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
q.Enqueue(i);
Assert.True(q.TryDequeue(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void Concurrent_EnqueueObjects_Enumerate_NeverEmptyOrNull()
{
int items = 1000;
object obj = new object();
var q = new ConcurrentQueue<object>();
q.Enqueue(obj); // ensure always at least one item
var cts = new CancellationTokenSource();
// Consumer repeatedly iterates the collection until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
bool gotOne = false;
foreach (object o in q)
{
gotOne = true;
Assert.NotNull(o);
}
Assert.True(gotOne);
}
});
// Producer enqueues and dequeues a bunch of items, then tells consumer to stop
Task producer = Task.Run(() =>
{
for (int iters = 0; iters < 3; iters++)
{
for (int i = 1; i <= items; i++) q.Enqueue(i);
object item;
for (int i = 1; i <= items; i++) Assert.True(q.TryDequeue(out item));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Theory]
[InlineData(1, 4, 1024)]
[InlineData(4, 1, 1024)]
[InlineData(3, 3, 1024)]
public void MultipleProducerConsumer_AllItemsTransferred(int producers, int consumers, int itemsPerProducer)
{
var cq = new ConcurrentQueue<int>();
var tasks = new List<Task>();
int totalItems = producers * itemsPerProducer;
int remainingItems = totalItems;
int sum = 0;
for (int i = 0; i < consumers; i++)
{
tasks.Add(Task.Run(() =>
{
while (Volatile.Read(ref remainingItems) > 0)
{
int item;
if (cq.TryDequeue(out item))
{
Interlocked.Add(ref sum, item);
Interlocked.Decrement(ref remainingItems);
}
}
}));
}
for (int i = 0; i < producers; i++)
{
tasks.Add(Task.Run(() =>
{
for (int item = 1; item <= itemsPerProducer; item++)
{
cq.Enqueue(item);
}
}));
}
Task.WaitAll(tasks.ToArray());
Assert.Equal(producers * (itemsPerProducer * (itemsPerProducer + 1) / 2), sum);
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
Assert.Throws<ArgumentNullException>("array", () => new ConcurrentQueue<int>().CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentQueue<int>().CopyTo(new int[1], -1));
Assert.Throws<ArgumentException>(() => new ConcurrentQueue<int>().CopyTo(new int[1], 2));
}
[Fact]
public void CopyTo_Empty_Success()
{
var q = new ConcurrentQueue<int>();
q.CopyTo(Array.Empty<int>(), 0);
}
[Theory]
[InlineData(1, false)]
[InlineData(100, false)]
[InlineData(512, false)]
[InlineData(1, true)]
[InlineData(100, true)]
[InlineData(512, true)]
public void CopyTo_AllItemsCopiedAtCorrectLocation(int count, bool viaInterface)
{
var q = new ConcurrentQueue<int>(Enumerable.Range(0, count));
var c = (ICollection)q;
int[] arr = new int[count];
if (viaInterface)
{
c.CopyTo(arr, 0);
}
else
{
q.CopyTo(arr, 0);
}
Assert.Equal(q, arr);
if (count > 1)
{
int toRemove = count / 2;
int remaining = count - toRemove;
for (int i = 0; i < toRemove; i++)
{
int item;
Assert.True(q.TryDequeue(out item));
Assert.Equal(i, item);
}
if (viaInterface)
{
c.CopyTo(arr, 1);
}
else
{
q.CopyTo(arr, 1);
}
Assert.Equal(0, arr[0]);
for (int i = 0; i < remaining; i++)
{
Assert.Equal(arr[1 + i], i + toRemove);
}
}
}
[Fact]
public void ICollection_Count_Success()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.Equal(5, c.Count);
}
[Fact]
public void ICollection_IsSynchronized_AlwaysFalse()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.False(c.IsSynchronized);
}
[Fact]
public void ICollection_SyncRoot_AlwaysNull()
{
ICollection c = new ConcurrentQueue<int>(Enumerable.Range(0, 5));
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ICollection_CopyTo_InvalidArg_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(new int[0], -1));
Assert.Throws<ArgumentException>(() => ((ICollection)new ConcurrentQueue<int>()).CopyTo(new int[0], 1));
}
[Fact]
public void IProducerConsumerCollection_TryAddTryTake_Success()
{
IProducerConsumerCollection<int> pcc = new ConcurrentQueue<int>();
Assert.True(pcc.TryAdd(1));
Assert.True(pcc.TryAdd(2));
int item;
Assert.True(pcc.TryTake(out item));
Assert.Equal(1, item);
Assert.True(pcc.TryTake(out item));
Assert.Equal(2, item);
}
[Fact]
public void IEnumerable_GetAllExpectedItems()
{
IEnumerable<int> enumerable1 = new ConcurrentQueue<int>(Enumerable.Range(1, 5));
IEnumerable enumerable2 = enumerable1;
int expectedNext = 1;
using (IEnumerator<int> enumerator1 = enumerable1.GetEnumerator())
{
IEnumerator enumerator2 = enumerable2.GetEnumerator();
while (enumerator1.MoveNext())
{
Assert.True(enumerator2.MoveNext());
Assert.Equal(expectedNext, enumerator1.Current);
Assert.Equal(expectedNext, enumerator2.Current);
expectedNext++;
}
Assert.False(enumerator2.MoveNext());
Assert.Equal(expectedNext, 6);
}
}
[Fact]
public void ReferenceTypes_NulledAfterDequeue()
{
int iterations = 10; // any number <32 will do
var mres = new ManualResetEventSlim[iterations];
// Separated out into another method to ensure that even in debug
// the JIT doesn't force anything to be kept alive for longer than we need.
var queue = ((Func<ConcurrentQueue<Finalizable>>)(() =>
{
var q = new ConcurrentQueue<Finalizable>();
for (int i = 0; i < iterations; i++)
{
mres[i] = new ManualResetEventSlim();
q.Enqueue(new Finalizable(mres[i]));
}
for (int i = 0; i < iterations; i++)
{
Finalizable temp;
Assert.True(q.TryDequeue(out temp));
}
return q;
}))();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(Array.TrueForAll(mres, e => e.IsSet));
GC.KeepAlive(queue);
}
/// <summary>Sets an event when finalized.</summary>
private sealed class Finalizable
{
private ManualResetEventSlim _mres;
public Finalizable(ManualResetEventSlim mres) { _mres = mres; }
~Finalizable() { _mres.Set(); }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.IO.Tests
{
public class FileStream_Dispose : FileSystemTest
{
[Fact]
public void CanDispose()
{
new FileStream(GetTestFilePath(), FileMode.Create).Dispose();
}
[Fact]
public void DisposeClosesHandle()
{
SafeFileHandle handle;
using(FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
handle = fs.SafeFileHandle;
}
Assert.True(handle.IsClosed);
}
[Fact]
public void HandlesMultipleDispose()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
fs.Dispose();
} // disposed as we leave using
}
private class MyFileStream : FileStream
{
public MyFileStream(string path, FileMode mode)
: base(path, mode)
{ }
public MyFileStream(SafeFileHandle handle, FileAccess access, Action<bool> disposeMethod) : base(handle, access)
{
DisposeMethod = disposeMethod;
}
public Action<bool> DisposeMethod { get; set; }
protected override void Dispose(bool disposing)
{
Action<bool> disposeMethod = DisposeMethod;
if (disposeMethod != null)
disposeMethod(disposing);
base.Dispose(disposing);
}
}
[Fact]
public void Dispose_CallsVirtualDisposeTrueArg_ThrowsDuringFlushWriteBuffer_DisposeThrows()
{
RemoteExecutor.Invoke(() =>
{
string fileName = GetTestFilePath();
using (FileStream fscreate = new FileStream(fileName, FileMode.Create))
{
fscreate.WriteByte(0);
}
bool writeDisposeInvoked = false;
Action<bool> writeDisposeMethod = _ => writeDisposeInvoked = true;
using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
using (var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod))
{
fswrite.WriteByte(0);
// Normal dispose should call Dispose(true). Throws due to FS trying to flush write buffer
Assert.Throws<UnauthorizedAccessException>(() => fswrite.Dispose());
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()");
writeDisposeInvoked = false;
// Only throws on first Dispose call
fswrite.Dispose();
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose()");
writeDisposeInvoked = false;
}
Assert.True(writeDisposeInvoked, "Expected Dispose(true) to be called from Dispose() again");
writeDisposeInvoked = false;
};
act();
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.False(writeDisposeInvoked, "Expected finalizer to have been suppressed");
}
}).Dispose();
}
[Fact]
public void NoDispose_CallsVirtualDisposeFalseArg_ThrowsDuringFlushWriteBuffer_FinalizerWontThrow()
{
RemoteExecutor.Invoke(() =>
{
string fileName = GetTestFilePath();
using (FileStream fscreate = new FileStream(fileName, FileMode.Create))
{
fscreate.WriteByte(0);
}
bool writeDisposeInvoked = false;
Action<bool> writeDisposeMethod = (disposing) =>
{
writeDisposeInvoked = true;
Assert.False(disposing, "Expected false arg to Dispose(bool)");
};
using (var fsread = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
var fswrite = new MyFileStream(fsread.SafeFileHandle, FileAccess.Write, writeDisposeMethod);
fswrite.WriteByte(0);
};
act();
// Dispose is not getting called here.
// instead, make sure finalizer gets called and doesnt throw exception
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.True(writeDisposeInvoked, "Expected finalizer to be invoked but not throw exception");
}
}).Dispose();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public void Dispose_CallsVirtualDispose_TrueArg()
{
bool disposeInvoked = false;
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
using (MyFileStream fs = new MyFileStream(GetTestFilePath(), FileMode.Create))
{
fs.DisposeMethod = (disposing) =>
{
disposeInvoked = true;
Assert.True(disposing, "Expected true arg to Dispose(bool)");
};
// Normal dispose should call Dispose(true)
fs.Dispose();
Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose()");
disposeInvoked = false;
}
// Second dispose leaving the using should still call dispose
Assert.True(disposeInvoked, "Expected Dispose(true) to be called from Dispose() again");
disposeInvoked = false;
};
act();
// Make sure we suppressed finalization
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.False(disposeInvoked, "Expected finalizer to have been suppressed");
}
[Fact]
public void Finalizer_CallsVirtualDispose_FalseArg()
{
bool disposeInvoked = false;
Action act = () => // separate method to avoid JIT lifetime-extension issues
{
var fs2 = new MyFileStream(GetTestFilePath(), FileMode.Create)
{
DisposeMethod = (disposing) =>
{
disposeInvoked = true;
Assert.False(disposing, "Expected false arg to Dispose(bool)");
}
};
};
act();
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
Assert.True(disposeInvoked, "Expected finalizer to be invoked and set called");
}
[Fact]
public void DisposeFlushesWriteBuffer()
{
string fileName = GetTestFilePath();
using(FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(TestBuffer, 0, TestBuffer.Length);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(buffer.Length, fs.Length);
fs.Read(buffer, 0, buffer.Length);
Assert.Equal(TestBuffer, buffer);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public void FinalizeFlushesWriteBuffer()
{
string fileName = GetTestFilePath();
// use a separate method to be sure that fs isn't rooted at time of GC.
Action leakFs = () =>
{
// we must specify useAsync:false, otherwise the finalizer just kicks off an async write.
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false);
fs.Write(TestBuffer, 0, TestBuffer.Length);
fs = null;
};
leakFs();
GC.Collect();
GC.WaitForPendingFinalizers();
using (FileStream fsr = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(buffer.Length, fsr.Length);
fsr.Read(buffer, 0, buffer.Length);
Assert.Equal(TestBuffer, buffer);
}
}
}
}
| |
// Copyright (c) 2013 Krkadoni.com - Released under The MIT License.
// Full license text can be found at http://opensource.org/licenses/MIT
using System;
using System.Runtime.Serialization;
using Krkadoni.EnigmaSettings.Interfaces;
namespace Krkadoni.EnigmaSettings
{
[DataContract]
public class TransponderDVBT : Transponder, ITransponderDVBT
{
#region "IEditable"
private bool _isEditing;
private string _mBandwidth;
private string _mFecHigh;
private string _mFecLow;
private string _mFlags;
private string _mGuardInterval;
private string _mHierarchy;
private string _mInversion;
private string _mModulation;
private string _mTransmission;
private string _mSystem;
private string _mPlpId;
public override void BeginEdit()
{
base.BeginEdit();
if (_isEditing) return;
_mBandwidth = _bandwidth;
_mFecHigh = _fecHigh;
_mFecLow = _fecLow;
_mFlags = _flags;
_mGuardInterval = _guardInterval;
_mHierarchy = _hierarchy;
_mInversion = _inversion;
_mModulation = _modulation;
_mTransmission = _transmission;
_mSystem = _system;
_mPlpId = _plp_id;
_isEditing = true;
}
public override void EndEdit()
{
base.EndEdit();
_isEditing = false;
}
public override void CancelEdit()
{
base.CancelEdit();
if (!_isEditing) return;
Bandwidth = _mBandwidth;
FECHigh = _mFecHigh;
FECLow = _mFecLow;
Flags = _mFlags;
GuardInterval = _mGuardInterval;
Hierarchy = _mHierarchy;
Inversion = _mInversion;
Modulation = _mModulation;
Transmission = _mTransmission;
System = _mSystem;
PlpId = _mPlpId;
_isEditing = false;
}
#endregion
private string _bandwidth = "0";
private string _fecHigh = "0";
private string _fecLow = "0";
private string _flags = "0";
private string _guardInterval = "0";
private string _hierarchy = "0";
private string _inversion = "0";
private string _modulation = "0";
private string _transmission = "0";
private string _system;
private string _plp_id;
/// <summary>
/// Initializes new terrestrial transponder from data found in services file
/// </summary>
/// <param name="transponderData">0xNamespace:0xTSID:0xNID</param>
/// <param name="transponderFrequency">
/// s
/// freq(khz):bandwidth:fecHigh:fec_low:modulation:transmission:guard:hierarchy:inversion:flags
/// </param>
/// <remarks></remarks>
/// <exception cref="ArgumentNullException">
/// Throws argument null exception if transponderData or transponderFrequency are
/// null/empty
/// </exception>
/// <exception cref="ArgumentException">Throws argument exception if frequency does not start with 't'</exception>
public TransponderDVBT(string transponderData, string transponderFrequency)
{
if (string.IsNullOrEmpty(transponderData))
throw new ArgumentNullException();
if (string.IsNullOrEmpty(transponderFrequency))
throw new ArgumentNullException();
_TransponderType = Enums.TransponderType.DVBT;
string[] tData = transponderData.Split(':');
string[] tFreq = transponderFrequency.Split(':');
NameSpc = tData[0];
TSID = tData[1];
NID = tData[2];
if (transponderFrequency.Trim().ToLower().StartsWith("s"))
{
Frequency = tFreq[0].Split(' ')[1];
if (tFreq.Length > 5)
Inversion = tFreq[5];
}
else
{
Frequency = tFreq[0].Split(' ')[1].Trim();
Bandwidth = tFreq[1];
FECHigh = tFreq[2];
FECLow = tFreq[3];
Modulation = tFreq[4];
if (tFreq.Length > 5)
Transmission = tFreq[5];
if (tFreq.Length > 6)
GuardInterval = tFreq[6];
if (tFreq.Length > 7)
Hierarchy = tFreq[7];
if (tFreq.Length > 8)
Inversion = tFreq[8];
if (tFreq.Length > 9)
Flags = tFreq[9];
if (tFreq.Length > 10)
System = tFreq[10];
if (tFreq.Length > 11)
PlpId = tFreq[11];
}
}
/// <summary>
/// 0=Auto, 1=8Mhz, 2=7Mhz, 3=6Mhz
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Bandwidth values</see>
[DataMember]
public string Bandwidth
{
get { return _bandwidth; }
set
{
if (value == null)
value = "0";
if (value == _bandwidth) return;
_bandwidth = value;
OnPropertyChanged("Bandwidth");
OnPropertyChanged("BandwidthType");
}
}
/// <summary>
/// Code rate High Pass FEC: 0=Auto, 1=1/2, 2=2/3, 3=3/4, 4=5/6, 5=7/8.
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">FEC types</see>
[DataMember]
public string FECHigh
{
get { return _fecHigh; }
set
{
if (value == null)
value = "0";
if (value == _fecHigh) return;
_fecHigh = value;
OnPropertyChanged("FECHigh");
OnPropertyChanged("FECHighType");
}
}
/// <summary>
/// Code rate Low Pass FEC: 0=Auto, 1=1/2, 2=2/3, 3=3/4, 4=5/6, 5=7/8
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">FEC types</see>
[DataMember]
public string FECLow
{
get { return _fecLow; }
set
{
if (value == null)
value = "0";
if (value == _fecLow) return;
_fecLow = value;
OnPropertyChanged("FECLow");
OnPropertyChanged("FECLowType");
}
}
/// <summary>
/// 0=Auto, 1=QPSK, 2=QAM16, 3=QAM64
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Modulation types</see>
[DataMember]
public string Modulation
{
get { return _modulation; }
set
{
if (value == null)
value = "0";
if (value == _modulation) return;
_modulation = value;
OnPropertyChanged("Modulation");
OnPropertyChanged("ModulationType");
}
}
/// <summary>
/// 0=Auto, 1=2k, 3=8k
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Transmission types</see>
[DataMember]
public string Transmission
{
get { return _transmission; }
set
{
if (value == null)
value = "0";
if (value == _transmission) return;
_transmission = value;
OnPropertyChanged("Transmission");
OnPropertyChanged("TransmissionType");
}
}
/// <summary>
/// 0=Auto, 1=1/32, 2=1/16, 3=1/8, 4=1/4
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Guard interval types</see>
[DataMember]
public string GuardInterval
{
get { return _guardInterval; }
set
{
if (value == null)
value = "0";
if (value == _guardInterval) return;
_guardInterval = value;
OnPropertyChanged("GuardInterval");
OnPropertyChanged("GuardIntervalType");
}
}
/// <summary>
/// 0=Auto, 1=None, 2=1, 3=2, 4=4
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Hierarchy types</see>
[DataMember]
public string Hierarchy
{
get { return _hierarchy; }
set
{
if (value == null)
value = "0";
if (value == _hierarchy) return;
_hierarchy = value;
OnPropertyChanged("Hierarchy");
OnPropertyChanged("HierarchyType");
}
}
/// <summary>
/// 0=Auto, 1=On, 2=Off
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Inversion types</see>
[DataMember]
public string Inversion
{
get { return _inversion; }
set
{
if (value == null)
value = "0";
if (value == _inversion) return;
_inversion = value;
OnPropertyChanged("Inversion");
OnPropertyChanged("InversionType");
}
}
/// <summary>
/// Transponder flags
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
[DataMember]
public string Flags
{
get { return _flags; }
set
{
if (value == null)
value = "0";
if (value == Flags) return;
_flags = value;
OnPropertyChanged("Flags");
}
}
/// <summary>
/// https://github.com/OpenViX/enigma2/blob/master/lib/dvb/db.cpp#L793
/// </summary>
[DataMember]
public string System
{
get { return _system; }
set
{
if (value == _system) return;
_system = value;
OnPropertyChanged("System");
}
}
/// <summary>
/// https://github.com/OpenViX/enigma2/blob/master/lib/dvb/db.cpp#L793
/// </summary>
[DataMember]
public string PlpId
{
get { return _plp_id; }
set
{
if (value == _plp_id) return;
_plp_id = value;
OnPropertyChanged("PlpId");
}
}
/// <summary>
/// 0=Auto, 1=8Mhz, 2=7Mhz, 3=6Mhz
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Bandwidth types</see>
[DataMember]
public Enums.DVBTBandwidthType BandwidthType
{
get
{
switch (Bandwidth)
{
case "0":
return Enums.DVBTBandwidthType.Auto;
case "1":
return Enums.DVBTBandwidthType.B8Mhz;
case "2":
return Enums.DVBTBandwidthType.B7Mhz;
case "3":
return Enums.DVBTBandwidthType.B6Mhz;
default:
return Enums.DVBTBandwidthType.Unknown;
}
}
}
/// <summary>
/// Code rate High Pass FEC: 0=Auto, 1=1/2, 2=2/3, 3=3/4, 4=5/6, 5=7/8.
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">FEC types</see>
[DataMember]
public Enums.DVBTFECHighType FECHighType
{
get
{
switch (FECHigh)
{
case "0":
return Enums.DVBTFECHighType.Auto;
case "1":
return Enums.DVBTFECHighType.F12;
case "2":
return Enums.DVBTFECHighType.F23;
case "3":
return Enums.DVBTFECHighType.F34;
case "4":
return Enums.DVBTFECHighType.F56;
case "5":
return Enums.DVBTFECHighType.F78;
default:
return Enums.DVBTFECHighType.Unknown;
}
}
}
/// <summary>
/// Code rate Low Pass FEC: 0=Auto, 1=1/2, 2=2/3, 3=3/4, 4=5/6, 5=7/8
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">FEC types</see>
[DataMember]
public Enums.DVBTFECLowType FECLowType
{
get
{
switch (FECLow)
{
case "0":
return Enums.DVBTFECLowType.Auto;
case "1":
return Enums.DVBTFECLowType.F12;
case "2":
return Enums.DVBTFECLowType.F23;
case "3":
return Enums.DVBTFECLowType.F34;
case "4":
return Enums.DVBTFECLowType.F56;
case "5":
return Enums.DVBTFECLowType.F78;
default:
return Enums.DVBTFECLowType.Unknown;
}
}
}
/// <summary>
/// 0=Auto, 1=QPSK, 2=QAM16, 3=QAM64
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Modulation types</see>
[DataMember]
public Enums.DVBTModulationType ModulationType
{
get
{
switch (Modulation)
{
case "0":
return Enums.DVBTModulationType.Auto;
case "1":
return Enums.DVBTModulationType.QPSK;
case "2":
return Enums.DVBTModulationType.Qam16;
case "3":
return Enums.DVBTModulationType.Qam64;
default:
return Enums.DVBTModulationType.Unknown;
}
}
}
/// <summary>
/// 0=Auto, 1=2k, 3=8k
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Transmission types</see>
[DataMember]
public Enums.DVBTTransmissionType TransmissionType
{
get
{
switch (Transmission)
{
case "0":
return Enums.DVBTTransmissionType.Auto;
case "1":
return Enums.DVBTTransmissionType.T2K;
case "3":
return Enums.DVBTTransmissionType.T8K;
default:
return Enums.DVBTTransmissionType.Unknown;
}
}
}
/// <summary>
/// 0=Auto, 1=1/32, 2=1/16, 3=1/8, 4=1/4
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Guard interval types</see>
[DataMember]
public Enums.DVBTGuardIntervalType GuardIntervalType
{
get
{
switch (GuardInterval)
{
case "0":
return Enums.DVBTGuardIntervalType.Auto;
case "1":
return Enums.DVBTGuardIntervalType.G132;
case "2":
return Enums.DVBTGuardIntervalType.G116;
case "3":
return Enums.DVBTGuardIntervalType.G18;
case "4":
return Enums.DVBTGuardIntervalType.G14;
default:
return Enums.DVBTGuardIntervalType.Unknown;
}
}
}
/// <summary>
/// 0=Auto, 1=None, 2=1, 3=2, 4=4
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Hierarchy types</see>
[DataMember]
public Enums.DVBTHierarchyType HierarchyType
{
get
{
switch (Hierarchy)
{
case "0":
return Enums.DVBTHierarchyType.Auto;
case "1":
return Enums.DVBTHierarchyType.None;
case "2":
return Enums.DVBTHierarchyType.H1;
case "3":
return Enums.DVBTHierarchyType.H2;
case "4":
return Enums.DVBTHierarchyType.H4;
default:
return Enums.DVBTHierarchyType.Unknown;
}
}
}
/// <summary>
/// 0=Auto, 1=On, 2=Off
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <see href="http://www.satsupreme.com/showthread.php/194074-Lamedb-format-explained">Inversion types</see>
[DataMember]
public Enums.DVBTInversionType InversionType
{
get
{
switch (Inversion)
{
case "0":
return Enums.DVBTInversionType.Auto;
case "1":
return Enums.DVBTInversionType.On;
case "2":
return Enums.DVBTInversionType.Off;
default:
return Enums.DVBTInversionType.Unknown;
}
}
}
public override string ToString()
{
string tType = string.Join("", new[]
{
"\t",
"t",
" ",
Frequency
});
return string.Join("\t", new[]
{
string.Join(":", new[]
{
NameSpc.PadRight(8, '0'),
TSID.PadLeft(4, '0'),
NID.PadLeft(4, '0')
}),
string.Join(":", new[]
{
tType,
Bandwidth,
FECHigh,
FECLow,
Modulation,
Transmission,
GuardInterval,
Hierarchy,
Inversion,
Flags
}),
"/"
});
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
/// <summary>
/// Represents a unit of angular measurement used during trigonometric
/// equations.
/// </summary>
/// <remarks>
/// <para>A radian is a unit of measure of an angle formed by an arc whose length is
/// the same as the circle's radius, making a shape similar to a slice of pizza.
/// Radians are typically used during trigonometric calculations such as calculating
/// the distance between two points on Earth's curved surface.</para>
/// <para>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (its properties can only be changed during constructors).</para>
/// </remarks>
#if !PocketPC || DesignTime
[TypeConverter("DotSpatial.Positioning.Design.RadianConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=2.0.0.0, PublicKeyToken=d77afaeb30e3236a")]
#endif
public struct Radian : IFormattable, IEquatable<Radian>, IComparable<Radian>, IXmlSerializable
{
private double _Value;
#region Constants
// Public?
public const double RadiansPerDegree = Math.PI / 180.0;
public const double DegreesPerRadian = 180.0 / Math.PI;
#endregion
#region Fields
/// <summary>Represents a radian with a value of zero.</summary>
public static readonly Radian Empty = new Radian(0.0);
#endregion
#region Constructors
/// <summary>Creates a new instance with the specified value.</summary>
/// <remarks>
/// this constructor is typically used to initialize an instance when the radian
/// value is already known.
/// </remarks>
/// <param name="value">A value to store in the <strong>Value</strong> property.</param>
public Radian(double value)
{
_Value = value;
}
public Radian(int value)
{
_Value = (double)value;
}
public Radian(string value)
: this(value, CultureInfo.CurrentCulture)
{}
public Radian(string value, CultureInfo culture)
{
_Value = double.Parse(value, culture);
}
/// <summary>
/// Creates a new instance by deserializing the specified XML.
/// </summary>
/// <param name="reader"></param>
public Radian(XmlReader reader)
{
// Initialize all fields
_Value = Double.NaN;
// Deserialize the object from XML
ReadXml(reader);
}
#endregion
#region Public Properties
// Returns/sets the number of radians
/// <summary>Represents the numeric portion of a radian measurement.</summary>
/// <value>
/// A <strong>Double</strong> value indicating an angular measurement expressed in
/// radians.
/// </value>
/// <remarks>
/// This property stores the numeric radian measurement. A radian can be converted into a degree
/// measurements via the <see cref="Radian.ToAngle(Radian)">ToAngle</see> method.
/// </remarks>
public double Value
{
get
{
return _Value;
}
}
#endregion
#region Public Methods
/// <summary>Returns the cosine of the current instance.</summary>
public Radian Cosine()
{
return new Radian(Math.Cos(_Value));
}
public Radian Sine()
{
return new Radian(Math.Sin(_Value));
}
public Radian Tangent()
{
return new Radian(Math.Tan(_Value));
}
public Radian SquareRoot()
{
return new Radian(Math.Sqrt(_Value));
}
/// <summary>Returns the absolute value of the current instance.</summary>
public Radian AbsoluteValue()
{
return new Radian(Math.Abs(_Value));
}
/// <summary>Returns the arccosine of the current instance.</summary>
public Radian ArcCosine()
{
return new Radian(Math.Acos(_Value));
}
/// <summary>Returns the arcsine of the current instance.</summary>
public Radian ArcSine()
{
return new Radian(Math.Asin(_Value));
}
/// <summary>Returns the arctangent of the current instance.</summary>
public Radian ArcTangent()
{
return new Radian(Math.Atan(_Value));
}
#if !PocketPC
public Radian Logarithm(double newBase)
{
return new Radian(Math.Log(_Value, newBase));
}
#endif
public Radian LogarithmBase10()
{
return new Radian(Math.Log10(_Value));
}
/// <summary>Converts the current instance into an <strong>Angle</strong> object.</summary>
/// <returns>An <strong>Angle</strong> object.</returns>
/// <remarks>
/// This method is typically used to convert a radian measurement back to latitude or
/// longitude after a trigonometric formula has completed.
/// </remarks>
public double ToDegrees()
{
return _Value / RadiansPerDegree;
}
/// <summary>Converts the current instance into an <strong>Angle</strong> object.</summary>
/// <returns>An <strong>Angle</strong> object.</returns>
/// <remarks>
/// This method is typically used to convert a radian measurement back to latitude or
/// longitude after a trigonometric formula has completed.
/// </remarks>
public Angle ToAngle()
{
return new Angle(ToDegrees());
}
/// <summary>
/// Converts the current instance to a latitude.
/// </summary>
/// <returns></returns>
public Latitude ToLatitude()
{
return new Latitude(ToDegrees());
}
/// <summary>
/// Converts the current instance to a longitude.
/// </summary>
/// <returns></returns>
public Longitude ToLongitude()
{
return new Longitude(ToDegrees());
}
/// <summary>
/// Outputs the speed measurement as a formatted string using the specified
/// format.
/// </summary>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
// Compare only with objects of the same type
if (obj is Radian)
return Equals((Radian)obj);
return false;
}
/// <summary>Returns the unique code for this instance used in hash tables.</summary>
public override int GetHashCode()
{
return _Value.GetHashCode();
}
public override string ToString()
{
return ToString("g", CultureInfo.CurrentCulture); // Always support "g" as a default format
}
#endregion
#region Static Methods
/// <summary>
/// Converts the specified value in degrees into radians.
/// </summary>
/// <param name="value">A <strong>Double</strong> containing the value to convert.</param>
public static Radian FromDegrees(double value)
{
return new Radian(value * RadiansPerDegree);
}
/// <summary>
/// Converts the specified value in degrees into radians.
/// </summary>
/// <param name="value">An <strong>Angle</strong> containing the value to convert.</param>
public static Radian FromAngle(Angle value)
{
return new Radian(value.DecimalDegrees * RadiansPerDegree);
}
/// <summary>Converts the specified value from radians to degrees.</summary>
/// <returns>A <strong>Double</strong> measuring degrees.</returns>
/// <remarks>
/// This method is typically used to convert a radian measurement back to latitude or
/// longitude after a trigonometric formula has completed.
/// </remarks>
public static double ToDegrees(double radians)
{
return radians / RadiansPerDegree;
}
/// <summary>
/// Converts a Radian object into decimal degrees.
/// </summary>
/// <param name="value">A <strong>Radian</strong> object to convert to an <strong>Angle</strong>.</param>
/// <returns>An <strong>Angle</strong> object containing the converted value.</returns>
/// <remarks>This method is typically used for trigonometric functions which work with values expressed as radians. Then the formula has completed, results are converted from radians to decimal degrees to make them easier to use.</remarks>
public static Angle ToAngle(Radian value)
{
return value.ToAngle();
}
public static Radian Parse(string value)
{
return new Radian(value, CultureInfo.CurrentCulture);
}
public static Radian Parse(string value, CultureInfo culture)
{
return new Radian(value, culture);
}
#endregion
#region Operators
public static Radian operator +(Radian left, Radian right)
{
return left.Add(right);
}
public static Radian operator -(Radian left, Radian right)
{
return left.Subtract(right);
}
public static Radian operator *(Radian left, Radian right)
{
return left.Multiply(right);
}
public static Radian operator /(Radian left, Radian right)
{
return left.Divide(right);
}
public static bool operator <(Radian left, Radian right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(Radian left, Radian right)
{
return left.CompareTo(right) < 0 || left.Equals(right);
}
public static bool operator ==(Radian left, Radian right)
{
return left.Equals(right);
}
public static bool operator !=(Radian left, Radian right)
{
return !(left == right);
}
public static bool operator >=(Radian left, Radian right)
{
return left.CompareTo(right) > 0 || left.Equals(right);
}
public static bool operator >(Radian left, Radian right)
{
return left.CompareTo(right) > 0;
}
public static Radian operator +(Radian left, double right)
{
return left.Add(right);
}
public static Radian operator -(Radian left, double right)
{
return left.Subtract(right);
}
public static Radian operator *(Radian left, double right)
{
return left.Multiply(right);
}
public static Radian operator /(Radian left, double right)
{
return left.Divide(right);
}
public static bool operator <(Radian left, double right)
{
return left.IsLessThan(right);
}
public static bool operator <=(Radian left, double right)
{
return left.IsLessThanOrEqualTo(right);
}
public static bool operator ==(Radian left, double right)
{
return left.Equals(right);
}
public static bool operator !=(Radian left, double right)
{
return !(left == right);
}
public static bool operator >=(Radian left, double right)
{
return left.IsGreaterThanOrEqualTo(right);
}
public static bool operator >(Radian left, double right)
{
return left.IsGreaterThan(right);
}
/// <summary>Adds the current instance to the specified value.</summary>
public Radian Add(Radian value)
{
return Add(value.Value);
}
public Radian Add(double value)
{
return new Radian(_Value + value);
}
public Radian Subtract(Radian value)
{
return Subtract(value.Value);
}
public Radian Subtract(double value)
{
return new Radian(_Value - value);
}
public Radian Multiply(Radian value)
{
return Multiply(value.Value);
}
public Radian Multiply(double value)
{
return new Radian(_Value * value);
}
/// <summary>Returns the current value divided by the specified value.</summary>
public Radian Divide(Radian value)
{
return new Radian(Value / value.Value);
}
public Radian Divide(double value)
{
return new Radian(_Value / value);
}
public Radian Increment()
{
return new Radian(_Value + 1.0);
}
/// <summary>Returns the current value decreased by one.</summary>
public Radian Decrement()
{
return new Radian(_Value - 1.0);
}
public bool IsLessThan(Radian value)
{
return _Value < value.Value;
}
public bool IsLessThan(double value)
{
return _Value < value;
}
public bool IsLessThanOrEqualTo(Radian value)
{
return _Value <= value.Value;
}
public bool IsLessThanOrEqualTo(double value)
{
return _Value <= value;
}
public bool IsGreaterThan(Radian value)
{
return _Value > value.Value;
}
public bool IsGreaterThan(double value)
{
return _Value > value;
}
public bool IsGreaterThanOrEqualTo(Radian value)
{
return _Value >= value.Value;
}
public bool IsGreaterThanOrEqualTo(double value)
{
return _Value >= value;
}
#endregion
#region Conversions
public static explicit operator double(Radian value)
{
return value.Value;
}
public static explicit operator Radian(Longitude value)
{
return value.ToRadians();
}
public static explicit operator Radian(Latitude value)
{
return value.ToRadians();
}
public static explicit operator Radian(Azimuth value)
{
return value.ToRadians();
}
public static explicit operator Radian(Angle value)
{
return value.ToRadians();
}
public static explicit operator Radian(double value)
{
return new Radian(value);
}
public static explicit operator Radian(string value)
{
return new Radian(value, CultureInfo.CurrentCulture);
}
#endregion
#region IEquatable<Radian> Members
public bool Equals(Radian value)
{
return _Value.Equals(value.Value);
}
public bool Equals(Radian value, int decimals)
{
return Math.Round(_Value, decimals) == Math.Round(value.Value, decimals);
}
#endregion
#region IComparable<Radian> Members
/// <summary>Compares the current instance with the specified value.</summary>
public int CompareTo(Radian value)
{
return _Value.CompareTo(value.Value);
}
#endregion
#region IFormattable Members
/// <summary>
/// Outputs the speed measurement as a formatted string using the specified format
/// and culture information.
/// </summary>
public string ToString(string format, IFormatProvider formatProvider)
{
return _Value.ToString(format, formatProvider);
}
#endregion
#region IXmlSerializable Members
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
public void WriteXml(XmlWriter writer)
{
writer.WriteString(_Value.ToString("G17", CultureInfo.InvariantCulture));
}
public void ReadXml(XmlReader reader)
{
if (reader.NodeType == XmlNodeType.Text)
_Value = reader.ReadContentAsDouble();
else
_Value = reader.ReadElementContentAsDouble();
}
#endregion
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET (MIT,from version 3.36.7, see=> https://github.com/rivy/OpenPDN //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See src/Resources/Files/License.txt for full licensing and attribution //
// details. //
// . //
/////////////////////////////////////////////////////////////////////////////////
//MIT, 2017-present, WinterDev
using System;
using PixelFarm.Drawing;
namespace PaintFx
{
/// <summary>
/// Provides a set of standard UnaryPixelOps.
/// </summary>
public sealed class UnaryPixelOps
{
private UnaryPixelOps()
{
}
/// <summary>
/// Passes through the given color value.
/// result(color) = color
/// </summary>
public class Identity : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return color;
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
PlatformMemory.Copy(dst, src, (ulong)length * (ulong)sizeof(ColorBgra));
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
return;
}
}
/// <summary>
/// Always returns a constant color.
/// </summary>
public class Constant : UnaryPixelOp
{
ColorBgra _setColor;
public override ColorBgra Apply(ColorBgra color)
{
return _setColor;
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
*dst = _setColor;
++dst;
--length;
}
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
*ptr = _setColor;
++ptr;
--length;
}
}
public Constant(ColorBgra setColor)
{
_setColor = setColor;
}
}
/// <summary>
/// Blends pixels with the specified constant color.
/// </summary>
public class BlendConstant : UnaryPixelOp
{
ColorBgra _blendColor;
public override ColorBgra Apply(ColorBgra color)
{
int a = _blendColor.A;
int invA = 255 - a;
int r = ((color.R * invA) + (_blendColor.R * a)) / 256;
int g = ((color.G * invA) + (_blendColor.G * a)) / 256;
int b = ((color.B * invA) + (_blendColor.B * a)) / 256;
byte a2 = ComputeAlpha(color.A, _blendColor.A);
return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, a2);
}
public BlendConstant(ColorBgra blendColor)
{
_blendColor = blendColor;
}
}
/// <summary>
/// Used to set a given channel of a pixel to a given, predefined color.
/// Useful if you want to set only the alpha value of a given region.
/// </summary>
public class SetChannel : UnaryPixelOp
{
int _channel;
byte _setValue;
public override ColorBgra Apply(ColorBgra color)
{
color[_channel] = _setValue;
return color;
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
*dst = *src;
(*dst)[_channel] = _setValue;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
(*ptr)[_channel] = _setValue;
++ptr;
--length;
}
}
public SetChannel(int channel, byte setValue)
{
_channel = channel;
_setValue = setValue;
}
}
/// <summary>
/// Specialization of SetChannel that sets the alpha channel.
/// </summary>
/// <remarks>This class depends on the system being litte-endian with the alpha channel
/// occupying the 8 most-significant-bits of a ColorBgra instance.
/// By the way, we use addition instead of bitwise-OR because an addition can be
/// perform very fast (0.5 cycles) on a Pentium 4.</remarks>
public class SetAlphaChannel
: UnaryPixelOp
{
uint _addValue;
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromUInt32((color.Bgra & 0x00ffffff) + _addValue);
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
dst->Bgra = (src->Bgra & 0x00ffffff) + _addValue;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
ptr->Bgra = (ptr->Bgra & 0x00ffffff) + _addValue;
++ptr;
--length;
}
}
public SetAlphaChannel(byte alphaValue)
{
_addValue = (uint)alphaValue << 24;
}
}
/// <summary>
/// Specialization of SetAlphaChannel that always sets alpha to 255.
/// </summary>
public class SetAlphaChannelTo255 : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromUInt32(color.Bgra | 0xff000000);
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
dst->Bgra = src->Bgra | 0xff000000;
++dst;
++src;
--length;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
ptr->Bgra |= 0xff000000;
++ptr;
--length;
}
}
}
/// <summary>
/// Inverts a pixel's color, and passes through the alpha component.
/// </summary>
public class Invert : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra((byte)(255 - color.B), (byte)(255 - color.G), (byte)(255 - color.R), color.A);
}
}
/// <summary>
/// If the color is within the red tolerance, remove it
/// </summary>
public class RedEyeRemove : UnaryPixelOp
{
int _tolerence;
double _setSaturation;
public RedEyeRemove(int tol, int sat)
{
_tolerence = tol;
_setSaturation = (double)sat / 100;
}
public override ColorBgra Apply(ColorBgra color)
{
// The higher the saturation, the more red it is
int saturation = GetSaturation(color);
// The higher the difference between the other colors, the more red it is
int difference = color.R - Math.Max(color.B, color.G);
// If it is within tolerence, and the saturation is high
if ((difference > _tolerence) && (saturation > 100))
{
double i = 255.0 * color.GetIntensity();
byte ib = (byte)(i * _setSaturation); // adjust the red color for user inputted saturation
return ColorBgra.FromBgra((byte)color.B, (byte)color.G, ib, color.A);
}
else
{
return color;
}
}
//Saturation formula from RgbColor.cs, public HsvColor ToHsv()
private int GetSaturation(ColorBgra color)
{
double min;
double max;
double delta;
double r = (double)color.R / 255;
double g = (double)color.G / 255;
double b = (double)color.B / 255;
double s;
min = Math.Min(Math.Min(r, g), b);
max = Math.Max(Math.Max(r, g), b);
delta = max - min;
if (max == 0 || delta == 0)
{
// R, G, and B must be 0, or all the same.
// In this case, S is 0, and H is undefined.
// Using H = 0 is as good as any...
s = 0;
}
else
{
s = delta / max;
}
return (int)(s * 255);
}
}
/// <summary>
/// Inverts a pixel's color and its alpha component.
/// </summary>
public class InvertWithAlpha : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra((byte)(255 - color.B), (byte)(255 - color.G), (byte)(255 - color.R), (byte)(255 - color.A));
}
}
/// <summary>
/// Averages the input color's red, green, and blue channels. The alpha component
/// is unaffected.
/// </summary>
public class AverageChannels : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
byte average = (byte)(((int)color.R + (int)color.G + (int)color.B) / 3);
return ColorBgra.FromBgra(average, average, average, color.A);
}
}
public class Desaturate : UnaryPixelOp
{
public override ColorBgra Apply(ColorBgra color)
{
byte i = color.GetIntensityByte();
return ColorBgra.FromBgra(i, i, i, color.A);
}
public unsafe override void Apply(ColorBgra* ptr, int length)
{
while (length > 0)
{
byte i = ptr->GetIntensityByte();
ptr->R = i;
ptr->G = i;
ptr->B = i;
++ptr;
--length;
}
}
public unsafe override void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (length > 0)
{
byte i = src->GetIntensityByte();
dst->B = i;
dst->G = i;
dst->R = i;
dst->A = src->A;
++dst;
++src;
--length;
}
}
}
public class LuminosityCurve : UnaryPixelOp
{
public byte[] Curve = new byte[256];
public LuminosityCurve()
{
for (int i = 0; i < 256; ++i)
{
Curve[i] = (byte)i;
}
}
public override ColorBgra Apply(ColorBgra color)
{
byte lumi = color.GetIntensityByte();
int diff = Curve[lumi] - lumi;
return ColorBgra.FromBgraClamped(
color.B + diff,
color.G + diff,
color.R + diff,
color.A);
}
}
public class ChannelCurve : UnaryPixelOp
{
public byte[] CurveB = new byte[256];
public byte[] CurveG = new byte[256];
public byte[] CurveR = new byte[256];
public ChannelCurve()
{
for (int i = 0; i < 256; ++i)
{
CurveB[i] = (byte)i;
CurveG[i] = (byte)i;
CurveR[i] = (byte)i;
}
}
public override unsafe void Apply(ColorBgra* dst, ColorBgra* src, int length)
{
while (--length >= 0)
{
dst->B = CurveB[src->B];
dst->G = CurveG[src->G];
dst->R = CurveR[src->R];
dst->A = src->A;
++dst;
++src;
}
}
public override unsafe void Apply(ColorBgra* ptr, int length)
{
while (--length >= 0)
{
ptr->B = CurveB[ptr->B];
ptr->G = CurveG[ptr->G];
ptr->R = CurveR[ptr->R];
++ptr;
}
}
public override ColorBgra Apply(ColorBgra color)
{
return ColorBgra.FromBgra(CurveB[color.B], CurveG[color.G], CurveR[color.R], color.A);
}
public override void Apply(Surface dst, Point dstOffset, Surface src, Point srcOffset, int scanLength)
{
base.Apply(dst, dstOffset, src, srcOffset, scanLength);
}
}
public class Level : ChannelCurve
{
ColorBgra _colorInLow;
public ColorBgra ColorInLow
{
get => _colorInLow;
set
{
if (value.R == 255)
{
value.R = 254;
}
if (value.G == 255)
{
value.G = 254;
}
if (value.B == 255)
{
value.B = 254;
}
if (_colorInHigh.R < value.R + 1)
{
_colorInHigh.R = (byte)(value.R + 1);
}
if (_colorInHigh.G < value.G + 1)
{
_colorInHigh.G = (byte)(value.R + 1);
}
if (_colorInHigh.B < value.B + 1)
{
_colorInHigh.B = (byte)(value.R + 1);
}
_colorInLow = value;
UpdateLookupTable();
}
}
ColorBgra _colorInHigh;
public ColorBgra ColorInHigh
{
get => _colorInHigh;
set
{
if (value.R == 0)
{
value.R = 1;
}
if (value.G == 0)
{
value.G = 1;
}
if (value.B == 0)
{
value.B = 1;
}
if (_colorInLow.R > value.R - 1)
{
_colorInLow.R = (byte)(value.R - 1);
}
if (_colorInLow.G > value.G - 1)
{
_colorInLow.G = (byte)(value.R - 1);
}
if (_colorInLow.B > value.B - 1)
{
_colorInLow.B = (byte)(value.R - 1);
}
_colorInHigh = value;
UpdateLookupTable();
}
}
ColorBgra _colorOutLow;
public ColorBgra ColorOutLow
{
get => _colorOutLow;
set
{
if (value.R == 255)
{
value.R = 254;
}
if (value.G == 255)
{
value.G = 254;
}
if (value.B == 255)
{
value.B = 254;
}
if (_colorOutHigh.R < value.R + 1)
{
_colorOutHigh.R = (byte)(value.R + 1);
}
if (_colorOutHigh.G < value.G + 1)
{
_colorOutHigh.G = (byte)(value.G + 1);
}
if (_colorOutHigh.B < value.B + 1)
{
_colorOutHigh.B = (byte)(value.B + 1);
}
_colorOutLow = value;
UpdateLookupTable();
}
}
ColorBgra _colorOutHigh;
public ColorBgra ColorOutHigh
{
get => _colorOutHigh;
set
{
if (value.R == 0)
{
value.R = 1;
}
if (value.G == 0)
{
value.G = 1;
}
if (value.B == 0)
{
value.B = 1;
}
if (_colorOutLow.R > value.R - 1)
{
_colorOutLow.R = (byte)(value.R - 1);
}
if (_colorOutLow.G > value.G - 1)
{
_colorOutLow.G = (byte)(value.G - 1);
}
if (_colorOutLow.B > value.B - 1)
{
_colorOutLow.B = (byte)(value.B - 1);
}
_colorOutHigh = value;
UpdateLookupTable();
}
}
float[] _gamma = new float[3];
public float GetGamma(int index)
{
if (index < 0 || index >= 3)
{
throw new ArgumentOutOfRangeException("index", index, "Index must be between 0 and 2");
}
return _gamma[index];
}
public void SetGamma(int index, float val)
{
if (index < 0 || index >= 3)
{
throw new ArgumentOutOfRangeException("index", index, "Index must be between 0 and 2");
}
_gamma[index] = PixelUtils.Clamp(val, 0.1f, 10.0f);
UpdateLookupTable();
}
public bool isValid = true;
public static Level AutoFromLoMdHi(ColorBgra lo, ColorBgra md, ColorBgra hi)
{
float[] gamma = new float[3];
for (int i = 0; i < 3; i++)
{
if (lo[i] < md[i] && md[i] < hi[i])
{
gamma[i] = (float)PixelUtils.Clamp(Math.Log(0.5, (float)(md[i] - lo[i]) / (float)(hi[i] - lo[i])), 0.1, 10.0);
}
else
{
gamma[i] = 1.0f;
}
}
return new Level(lo, hi, gamma, ColorBgra.FromColor(Color.Black), ColorBgra.FromColor(Color.White));
}
private void UpdateLookupTable()
{
for (int i = 0; i < 3; i++)
{
if (_colorOutHigh[i] < _colorOutLow[i] ||
_colorInHigh[i] <= _colorInLow[i] ||
_gamma[i] < 0)
{
isValid = false;
return;
}
for (int j = 0; j < 256; j++)
{
ColorBgra col = Apply(j, j, j);
CurveB[j] = col.B;
CurveG[j] = col.G;
CurveR[j] = col.R;
}
}
}
public Level()
: this(ColorBgra.FromColor(Color.Black),
ColorBgra.FromColor(Color.White),
new float[] { 1, 1, 1 },
ColorBgra.FromColor(Color.Black),
ColorBgra.FromColor(Color.White))
{
}
public Level(ColorBgra in_lo, ColorBgra in_hi, float[] gamma, ColorBgra out_lo, ColorBgra out_hi)
{
_colorInLow = in_lo;
_colorInHigh = in_hi;
_colorOutLow = out_lo;
_colorOutHigh = out_hi;
if (gamma.Length != 3)
{
throw new ArgumentException("gamma", "gamma must be a float[3]");
}
_gamma = gamma;
UpdateLookupTable();
}
public ColorBgra Apply(float r, float g, float b)
{
ColorBgra ret = new ColorBgra();
float[] input = new float[] { b, g, r };
for (int i = 0; i < 3; i++)
{
float v = (input[i] - _colorInLow[i]);
if (v < 0)
{
ret[i] = _colorOutLow[i];
}
else if (v + _colorInLow[i] >= _colorInHigh[i])
{
ret[i] = _colorOutHigh[i];
}
else
{
ret[i] = (byte)PixelUtils.Clamp(
_colorOutLow[i] + (_colorOutHigh[i] - _colorOutLow[i]) * Math.Pow(v / (_colorInHigh[i] - _colorInLow[i]), _gamma[i]),
0.0f,
255.0f);
}
}
return ret;
}
public void UnApply(ColorBgra after, float[] beforeOut, float[] slopesOut)
{
if (beforeOut.Length != 3)
{
throw new ArgumentException("before must be a float[3]", "before");
}
if (slopesOut.Length != 3)
{
throw new ArgumentException("slopes must be a float[3]", "slopes");
}
for (int i = 0; i < 3; i++)
{
beforeOut[i] = _colorInLow[i] + (_colorInHigh[i] - _colorInLow[i]) *
(float)Math.Pow((float)(after[i] - _colorOutLow[i]) / (_colorOutHigh[i] - _colorOutLow[i]), 1 / _gamma[i]);
slopesOut[i] = (float)(_colorInHigh[i] - _colorInLow[i]) / ((_colorOutHigh[i] - _colorOutLow[i]) * _gamma[i]) *
(float)Math.Pow((float)(after[i] - _colorOutLow[i]) / (_colorOutHigh[i] - _colorOutLow[i]), 1 / _gamma[i] - 1);
if (float.IsInfinity(slopesOut[i]) || float.IsNaN(slopesOut[i]))
{
slopesOut[i] = 0;
}
}
}
public object Clone()
{
Level copy = new Level(_colorInLow, _colorInHigh, (float[])_gamma.Clone(), _colorOutLow, _colorOutHigh);
copy.CurveB = (byte[])this.CurveB.Clone();
copy.CurveG = (byte[])this.CurveG.Clone();
copy.CurveR = (byte[])this.CurveR.Clone();
return copy;
}
}
public class HueSaturationLightness : UnaryPixelOp
{
readonly int _hueDelta;
readonly int _satFactor;
UnaryPixelOp _blendOp;
public HueSaturationLightness(int hueDelta, int satDelta, int lightness)
{
_hueDelta = hueDelta;
_satFactor = (satDelta * 1024) / 100;
if (lightness == 0)
{
_blendOp = new UnaryPixelOps.Identity();
}
else if (lightness > 0)
{
_blendOp = new UnaryPixelOps.BlendConstant(ColorBgra.FromBgra(255, 255, 255, (byte)((lightness * 255) / 100)));
}
else // if (lightness < 0)
{
_blendOp = new UnaryPixelOps.BlendConstant(ColorBgra.FromBgra(0, 0, 0, (byte)((-lightness * 255) / 100)));
}
}
public override ColorBgra Apply(ColorBgra color)
{
//adjust saturation
byte intensity = color.GetIntensityByte();
color.R = PixelUtils.ClampToByte((intensity * 1024 + (color.R - intensity) * _satFactor) >> 10);
color.G = PixelUtils.ClampToByte((intensity * 1024 + (color.G - intensity) * _satFactor) >> 10);
color.B = PixelUtils.ClampToByte((intensity * 1024 + (color.B - intensity) * _satFactor) >> 10);
HsvColor hsvColor = HsvColor.FromColor(color.ToColor());
int hue = hsvColor.Hue;
hue += _hueDelta;
while (hue < 0)
{
hue += 360;
}
while (hue > 360)
{
hue -= 360;
}
hsvColor.Hue = hue;
ColorBgra newColor = ColorBgra.FromColor(hsvColor.ToColor());
newColor = _blendOp.Apply(newColor);
newColor.A = color.A;
return newColor;
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.FaceAnalysis;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
namespace SDKTemplate
{
/// <summary>
/// Page for demonstrating FaceDetection on a webcam snapshot.
/// </summary>
public sealed partial class DetectFacesInWebcam : Page
{
/// <summary>
/// Brush for drawing the bounding box around each detected face.
/// </summary>
private readonly SolidColorBrush lineBrush = new SolidColorBrush(Windows.UI.Colors.Yellow);
/// <summary>
/// Thickness of the face bounding box lines.
/// </summary>
private readonly double lineThickness = 2.0;
/// <summary>
/// Transparent fill for the bounding box.
/// </summary>
private readonly SolidColorBrush fillBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);
/// <summary>
/// Reference back to the "root" page of the app.
/// </summary>
private MainPage rootPage;
/// <summary>
/// Holds the current scenario state value.
/// </summary>
private ScenarioState currentState;
/// <summary>
/// References a MediaCapture instance; is null when not in Streaming state.
/// </summary>
private MediaCapture mediaCapture;
/// <summary>
/// Cache of properties from the current MediaCapture device which is used for capturing the preview frame.
/// </summary>
private VideoEncodingProperties videoProperties;
/// <summary>
/// References a FaceDetector instance.
/// </summary>
private FaceDetector faceDetector;
/// <summary>
/// Initializes a new instance of the <see cref="DetectFacesInWebcam"/> class.
/// </summary>
public DetectFacesInWebcam()
{
this.InitializeComponent();
this.currentState = ScenarioState.Idle;
App.Current.Suspending += this.OnSuspending;
}
/// <summary>
/// Values for identifying and controlling scenario states.
/// </summary>
private enum ScenarioState
{
/// <summary>
/// Display is blank - default state.
/// </summary>
Idle,
/// <summary>
/// Webcam is actively engaged and a live video stream is displayed.
/// </summary>
Streaming,
/// <summary>
/// Snapshot image has been captured and is being displayed along with detected faces; webcam is not active.
/// </summary>
Snapshot
}
/// <summary>
/// Responds when we navigate to this page.
/// </summary>
/// <param name="e">Event data</param>
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
this.rootPage = MainPage.Current;
// The 'await' operation can only be used from within an async method but class constructors
// cannot be labeled as async, and so we'll initialize FaceDetector here.
if (this.faceDetector == null)
{
this.faceDetector = await FaceDetector.CreateAsync();
}
}
/// <summary>
/// Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state.
/// </summary>
/// <param name="sender">The source of the Suspending event</param>
/// <param name="e">Event data</param>
private void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
if (this.currentState == ScenarioState.Streaming)
{
var deferral = e.SuspendingOperation.GetDeferral();
try
{
this.ChangeScenarioState(ScenarioState.Idle);
}
finally
{
deferral.Complete();
}
}
}
/// <summary>
/// Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element.
/// </summary>
/// <returns>Async Task object returning true if initialization and streaming were successful and false if an exception occurred.</returns>
private async Task<bool> StartWebcamStreaming()
{
bool successful = true;
try
{
this.mediaCapture = new MediaCapture();
// For this scenario, we only need Video (not microphone) so specify this in the initializer.
// NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include
// microphone (default constructor) you must add "microphone" to the manifest or initialization will fail.
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
await this.mediaCapture.InitializeAsync(settings);
this.mediaCapture.CameraStreamStateChanged += this.MediaCapture_CameraStreamStateChanged;
// Cache the media properties as we'll need them later.
var deviceController = this.mediaCapture.VideoDeviceController;
this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
// Immediately start streaming to our CaptureElement UI.
// NOTE: CaptureElement's Source must be set before streaming is started.
this.CamPreview.Source = this.mediaCapture;
await this.mediaCapture.StartPreviewAsync();
}
catch (System.UnauthorizedAccessException)
{
// If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact.
this.rootPage.NotifyUser("Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType.ErrorMessage);
successful = false;
}
catch (Exception ex)
{
this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
successful = false;
}
return successful;
}
/// <summary>
/// Safely stops webcam streaming (if running) and releases MediaCapture object.
/// </summary>
private async void ShutdownWebCam()
{
if (this.mediaCapture != null)
{
if (this.mediaCapture.CameraStreamState == Windows.Media.Devices.CameraStreamState.Streaming)
{
await this.mediaCapture.StopPreviewAsync();
}
this.mediaCapture.Dispose();
}
this.CamPreview.Source = null;
this.mediaCapture = null;
}
/// <summary>
/// Captures a single frame from the running webcam stream and executes the FaceDetector on the image. If successful calls SetupVisualization to display the results.
/// </summary>
/// <returns>Async Task object returning true if the capture was successful and false if an exception occurred.</returns>
private async Task<bool> TakeSnapshotAndFindFaces()
{
bool successful = true;
try
{
if (this.currentState != ScenarioState.Streaming)
{
return false;
}
WriteableBitmap displaySource = null;
IList<DetectedFace> faces = null;
// Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case).
// GetPreviewFrame will convert the native webcam frame into this format.
const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12;
using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, (int)this.videoProperties.Width, (int)this.videoProperties.Height))
{
await this.mediaCapture.GetPreviewFrameAsync(previewFrame);
// The returned VideoFrame should be in the supported NV12 format but we need to verify this.
if (FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat))
{
faces = await this.faceDetector.DetectFacesAsync(previewFrame.SoftwareBitmap);
}
else
{
this.rootPage.NotifyUser("PixelFormat '" + InputPixelFormat.ToString() + "' is not supported by FaceDetector", NotifyType.ErrorMessage);
}
// Create a WritableBitmap for our visualization display; copy the original bitmap pixels to wb's buffer.
// Note that WriteableBitmap doesn't support NV12 and we have to convert it to 32-bit BGRA.
using (SoftwareBitmap convertedSource = SoftwareBitmap.Convert(previewFrame.SoftwareBitmap, BitmapPixelFormat.Bgra8))
{
displaySource = new WriteableBitmap(convertedSource.PixelWidth, convertedSource.PixelHeight);
convertedSource.CopyToBuffer(displaySource.PixelBuffer);
}
// Create our display using the available image and face results.
this.SetupVisualization(displaySource, faces);
}
}
catch (Exception ex)
{
this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
successful = false;
}
return successful;
}
/// <summary>
/// Takes the webcam image and FaceDetector results and assembles the visualization onto the Canvas.
/// </summary>
/// <param name="displaySource">Bitmap object holding the image we're going to display</param>
/// <param name="foundFaces">List of detected faces; output from FaceDetector</param>
private void SetupVisualization(WriteableBitmap displaySource, IList<DetectedFace> foundFaces)
{
ImageBrush brush = new ImageBrush();
brush.ImageSource = displaySource;
brush.Stretch = Stretch.Fill;
this.SnapshotCanvas.Background = brush;
if (foundFaces != null)
{
double widthScale = displaySource.PixelWidth / this.SnapshotCanvas.ActualWidth;
double heightScale = displaySource.PixelHeight / this.SnapshotCanvas.ActualHeight;
foreach (DetectedFace face in foundFaces)
{
// Create a rectangle element for displaying the face box but since we're using a Canvas
// we must scale the rectangles according to the image's actual size.
// The original FaceBox values are saved in the Rectangle's Tag field so we can update the
// boxes when the Canvas is resized.
Rectangle box = new Rectangle();
box.Tag = face.FaceBox;
box.Width = (uint)(face.FaceBox.Width / widthScale);
box.Height = (uint)(face.FaceBox.Height / heightScale);
box.Fill = this.fillBrush;
box.Stroke = this.lineBrush;
box.StrokeThickness = this.lineThickness;
box.Margin = new Thickness((uint)(face.FaceBox.X / widthScale), (uint)(face.FaceBox.Y / heightScale), 0, 0);
this.SnapshotCanvas.Children.Add(box);
}
}
string message;
if (foundFaces == null || foundFaces.Count == 0)
{
message = "Didn't find any human faces in the image";
}
else if (foundFaces.Count == 1)
{
message = "Found a human face in the image";
}
else
{
message = "Found " + foundFaces.Count + " human faces in the image";
}
this.rootPage.NotifyUser(message, NotifyType.StatusMessage);
}
/// <summary>
/// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the
/// passed in state value. Handles failures and resets the state if necessary.
/// </summary>
/// <param name="newState">State to switch to</param>
private async void ChangeScenarioState(ScenarioState newState)
{
switch (newState)
{
case ScenarioState.Idle:
this.ShutdownWebCam();
this.SnapshotCanvas.Background = null;
this.SnapshotCanvas.Children.Clear();
this.CameraSnapshotButton.IsEnabled = false;
this.CameraStreamingButton.Content = "Start Streaming";
this.CameraSnapshotButton.Content = "Take Snapshot";
this.currentState = newState;
break;
case ScenarioState.Streaming:
if (!await this.StartWebcamStreaming())
{
this.ChangeScenarioState(ScenarioState.Idle);
break;
}
this.SnapshotCanvas.Background = null;
this.SnapshotCanvas.Children.Clear();
this.CameraSnapshotButton.IsEnabled = true;
this.CameraStreamingButton.Content = "Stop Streaming";
this.CameraSnapshotButton.Content = "Take Snapshot";
this.currentState = newState;
break;
case ScenarioState.Snapshot:
if (!await this.TakeSnapshotAndFindFaces())
{
this.ChangeScenarioState(ScenarioState.Idle);
break;
}
this.ShutdownWebCam();
this.CameraSnapshotButton.IsEnabled = true;
this.CameraStreamingButton.Content = "Start Streaming";
this.CameraSnapshotButton.Content = "Clear Display";
this.currentState = newState;
break;
}
}
/// <summary>
/// Handles MediaCapture changes by shutting down streaming and returning to Idle state.
/// </summary>
/// <param name="sender">The source of the event, i.e. our MediaCapture object</param>
/// <param name="args">Event data</param>
private void MediaCapture_CameraStreamStateChanged(MediaCapture sender, object args)
{
// MediaCapture is not Agile and so we cannot invoke it's methods on this caller's thread
// and instead need to schedule the state change on the UI thread.
var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChangeScenarioState(ScenarioState.Idle);
});
}
/// <summary>
/// Handles "streaming" button clicks to start/stop webcam streaming.
/// </summary>
/// <param name="sender">Button user clicked</param>
/// <param name="e">Event data</param>
private void CameraStreamingButton_Click(object sender, RoutedEventArgs e)
{
if (this.currentState == ScenarioState.Streaming)
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Idle);
}
else
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Streaming);
}
}
/// <summary>
/// Handles "snapshot" button clicks to take a snapshot or clear the current display.
/// </summary>
/// <param name="sender">Button user clicked</param>
/// <param name="e">Event data</param>
private void CameraSnapshotButton_Click(object sender, RoutedEventArgs e)
{
if (this.currentState == ScenarioState.Streaming)
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Snapshot);
}
else
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Idle);
}
}
/// <summary>
/// Updates any existing face bounding boxes in response to changes in the size of the Canvas.
/// </summary>
/// <param name="sender">Canvas whose size has changed</param>
/// <param name="e">Event data</param>
private void SnapshotCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
try
{
// If the Canvas is resized we must recompute a new scaling factor and
// apply it to each face box.
if (this.currentState == ScenarioState.Snapshot && this.SnapshotCanvas.Background != null)
{
WriteableBitmap displaySource = (this.SnapshotCanvas.Background as ImageBrush).ImageSource as WriteableBitmap;
double widthScale = displaySource.PixelWidth / this.SnapshotCanvas.ActualWidth;
double heightScale = displaySource.PixelHeight / this.SnapshotCanvas.ActualHeight;
foreach (var item in this.SnapshotCanvas.Children)
{
Rectangle box = item as Rectangle;
if (box == null)
{
continue;
}
// We saved the original size of the face box in the rectangles Tag field.
BitmapBounds faceBounds = (BitmapBounds)box.Tag;
box.Width = (uint)(faceBounds.Width / widthScale);
box.Height = (uint)(faceBounds.Height / heightScale);
box.Margin = new Thickness((uint)(faceBounds.X / widthScale), (uint)(faceBounds.Y / heightScale), 0, 0);
}
}
}
catch (Exception ex)
{
this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.UI.CoroutineTween;
#pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
namespace TMPro
{
[ExecuteInEditMode]
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(CanvasRenderer))]
[AddComponentMenu("UI/TextMeshPro - Text (UI)", 11)]
public partial class TextMeshProUGUI : TMP_Text, ILayoutElement
{
/// <summary>
/// Get the material that will be used for rendering.
/// </summary>
public override Material materialForRendering
{
get { return TMP_MaterialManager.GetMaterialForRendering(this, m_sharedMaterial); }
}
/// <summary>
/// Determines if the size of the text container will be adjusted to fit the text object when it is first created.
/// </summary>
public override bool autoSizeTextContainer
{
get { return m_autoSizeTextContainer; }
set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this); SetLayoutDirty(); } }
}
/// <summary>
/// Reference to the Mesh used by the text object.
/// </summary>
public override Mesh mesh
{
get { return m_mesh; }
}
/// <summary>
/// Reference to the CanvasRenderer used by the text object.
/// </summary>
public new CanvasRenderer canvasRenderer
{
get
{
if (m_canvasRenderer == null) m_canvasRenderer = GetComponent<CanvasRenderer>();
return m_canvasRenderer;
}
}
/// <summary>
/// Anchor dampening prevents the anchor position from being adjusted unless the positional change exceeds about 40% of the width of the underline character. This essentially stabilizes the anchor position.
/// </summary>
//public bool anchorDampening
//{
// get { return m_anchorDampening; }
// set { if (m_anchorDampening != value) { havePropertiesChanged = true; m_anchorDampening = value; /* ScheduleUpdate(); */ } }
//}
private bool m_isRebuildingLayout = false;
//private bool m_isLayoutDirty = false;
/// <summary>
/// Function called by Unity when the horizontal layout needs to be recalculated.
/// </summary>
public void CalculateLayoutInputHorizontal()
{
//Debug.Log("*** CalculateLayoutHorizontal() ***"); // at Frame: " + Time.frameCount); // called on Object ID " + GetInstanceID());
//// Check if object is active
if (!this.gameObject.activeInHierarchy)
return;
if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
{
m_preferredWidth = GetPreferredWidth();
ComputeMarginSize();
m_isLayoutDirty = true;
}
}
/// <summary>
/// Function called by Unity when the vertical layout needs to be recalculated.
/// </summary>
public void CalculateLayoutInputVertical()
{
//Debug.Log("*** CalculateLayoutInputVertical() ***"); // at Frame: " + Time.frameCount); // called on Object ID " + GetInstanceID());
//// Check if object is active
if (!this.gameObject.activeInHierarchy) // || IsRectTransformDriven == false)
return;
if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
{
m_preferredHeight = GetPreferredHeight();
ComputeMarginSize();
m_isLayoutDirty = true;
}
m_isCalculateSizeRequired = false;
}
public override void SetVerticesDirty()
{
if (m_verticesAlreadyDirty || this == null || !this.IsActive() || CanvasUpdateRegistry.IsRebuildingGraphics())
return;
m_verticesAlreadyDirty = true;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild((ICanvasElement)this);
if (m_OnDirtyVertsCallback != null)
m_OnDirtyVertsCallback();
}
/// <summary>
///
/// </summary>
public override void SetLayoutDirty()
{
m_isPreferredWidthDirty = true;
m_isPreferredHeightDirty = true;
if ( m_layoutAlreadyDirty || this == null || !this.IsActive())
return;
m_layoutAlreadyDirty = true;
LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform);
m_isLayoutDirty = true;
if (m_OnDirtyLayoutCallback != null)
m_OnDirtyLayoutCallback();
}
/// <summary>
///
/// </summary>
public override void SetMaterialDirty()
{
//Debug.Log("SetMaterialDirty()");
if (this == null || !this.IsActive() || CanvasUpdateRegistry.IsRebuildingGraphics())
return;
m_isMaterialDirty = true;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild((ICanvasElement)this);
if (m_OnDirtyMaterialCallback != null)
m_OnDirtyMaterialCallback();
}
/// <summary>
///
/// </summary>
public override void SetAllDirty()
{
m_isInputParsingRequired = true;
SetLayoutDirty();
SetVerticesDirty();
SetMaterialDirty();
}
/// <summary>
///
/// </summary>
/// <param name="update"></param>
public override void Rebuild(CanvasUpdate update)
{
if (this == null) return;
if (update == CanvasUpdate.Prelayout)
{
if (m_autoSizeTextContainer)
{
m_rectTransform.sizeDelta = GetPreferredValues(Mathf.Infinity, Mathf.Infinity);
}
}
else if (update == CanvasUpdate.PreRender)
{
OnPreRenderCanvas();
m_verticesAlreadyDirty = false;
m_layoutAlreadyDirty = false;
if (!m_isMaterialDirty) return;
UpdateMaterial();
m_isMaterialDirty = false;
}
}
/// <summary>
/// Method to keep the pivot of the sub text objects in sync with the parent pivot.
/// </summary>
private void UpdateSubObjectPivot()
{
if (m_textInfo == null) return;
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
m_subTextObjects[i].SetPivotDirty();
}
//m_isPivotDirty = false;
}
/// <summary>
///
/// </summary>
/// <param name="baseMaterial"></param>
/// <returns></returns>
public override Material GetModifiedMaterial(Material baseMaterial)
{
Material mat = baseMaterial;
if (m_ShouldRecalculateStencil)
{
m_stencilID = TMP_MaterialManager.GetStencilID(gameObject);
m_ShouldRecalculateStencil = false;
}
// Release masking material
//if (m_MaskMaterial != null)
// MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
if (m_stencilID > 0)
{
mat = TMP_MaterialManager.GetStencilMaterial(baseMaterial, m_stencilID);
if (m_MaskMaterial != null)
TMP_MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
m_MaskMaterial = mat;
}
return mat;
}
/// <summary>
///
/// </summary>
protected override void UpdateMaterial()
{
//Debug.Log("*** UpdateMaterial() ***");
//if (!this.IsActive())
// return;
if (m_sharedMaterial == null) return;
if (m_canvasRenderer == null) m_canvasRenderer = this.canvasRenderer;
m_canvasRenderer.materialCount = 1;
m_canvasRenderer.SetMaterial(materialForRendering, 0);
}
//public override void OnRebuildRequested()
//{
// //Debug.Log("OnRebuildRequested");
// base.OnRebuildRequested();
//}
//public override bool Raycast(Vector2 sp, Camera eventCamera)
//{
// //Debug.Log("Raycast Event. ScreenPoint: " + sp);
// return base.Raycast(sp, eventCamera);
//}
// MASKING RELATED PROPERTIES
/// <summary>
/// Sets the masking offset from the bounds of the object
/// </summary>
public Vector4 maskOffset
{
get { return m_maskOffset; }
set { m_maskOffset = value; UpdateMask(); m_havePropertiesChanged = true; }
}
//public override Material defaultMaterial
//{
// get { Debug.Log("Default Material called."); return m_sharedMaterial; }
//}
//protected override void OnCanvasHierarchyChanged()
//{
// //Debug.Log("OnCanvasHierarchyChanged...");
//}
// IClippable implementation
/// <summary>
/// Method called when the state of a parent changes.
/// </summary>
public override void RecalculateClipping()
{
//Debug.Log("***** RecalculateClipping() *****");
base.RecalculateClipping();
}
// IMaskable Implementation
/// <summary>
/// Method called when Stencil Mask needs to be updated on this element and parents.
/// </summary>
public override void RecalculateMasking()
{
//Debug.Log("***** RecalculateMasking() *****");
this.m_ShouldRecalculateStencil = true;
SetMaterialDirty();
}
/// <summary>
/// Override of the Cull function to provide for the ability to override the culling of the text object.
/// </summary>
/// <param name="clipRect"></param>
/// <param name="validRect"></param>
public override void Cull(Rect clipRect, bool validRect)
{
if (m_ignoreRectMaskCulling) return;
base.Cull(clipRect, validRect);
}
//protected override void UpdateGeometry()
//{
// //Debug.Log("UpdateGeometry");
// //base.UpdateGeometry();
//}
//protected override void UpdateMaterial()
//{
// //Debug.Log("UpdateMaterial called.");
//// base.UpdateMaterial();
//}
/*
/// <summary>
/// Sets the mask type
/// </summary>
public MaskingTypes mask
{
get { return m_mask; }
set { m_mask = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Set the masking offset mode (as percentage or pixels)
/// </summary>
public MaskingOffsetMode maskOffsetMode
{
get { return m_maskOffsetMode; }
set { m_maskOffsetMode = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
/*
/// <summary>
/// Sets the softness of the mask
/// </summary>
public Vector2 maskSoftness
{
get { return m_maskSoftness; }
set { m_maskSoftness = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Allows to move / offset the mesh vertices by a set amount
/// </summary>
public Vector2 vertexOffset
{
get { return m_vertexOffset; }
set { m_vertexOffset = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
/// <summary>
/// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
/// </summary>
public override void UpdateMeshPadding()
{
m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
m_havePropertiesChanged = true;
checkPaddingRequired = false;
// Return if text object is not awake yet.
if (m_textInfo == null) return;
// Update sub text objects
for (int i = 1; i < m_textInfo.materialCount; i++)
m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold);
}
/// <summary>
/// Tweens the CanvasRenderer color associated with this Graphic.
/// </summary>
/// <param name="targetColor">Target color.</param>
/// <param name="duration">Tween duration.</param>
/// <param name="ignoreTimeScale">Should ignore Time.scale?</param>
/// <param name="useAlpha">Should also Tween the alpha channel?</param>
protected override void InternalCrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha)
{
int materialCount = m_textInfo.materialCount;
for (int i = 1; i < materialCount; i++)
{
m_subTextObjects[i].CrossFadeColor(targetColor, duration, ignoreTimeScale, useAlpha);
}
}
/// <summary>
/// Tweens the alpha of the CanvasRenderer color associated with this Graphic.
/// </summary>
/// <param name="alpha">Target alpha.</param>
/// <param name="duration">Duration of the tween in seconds.</param>
/// <param name="ignoreTimeScale">Should ignore Time.scale?</param>
protected override void InternalCrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale)
{
int materialCount = m_textInfo.materialCount;
for (int i = 1; i < materialCount; i++)
{
m_subTextObjects[i].CrossFadeAlpha(alpha, duration, ignoreTimeScale);
}
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
public override void ForceMeshUpdate()
{
//if (m_isEnabled == false) this.OnEnable();
m_havePropertiesChanged = true;
OnPreRenderCanvas();
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
/// <param name="ignoreInactive">If set to true, the text object will be regenerated regardless of is active state.</param>
public override void ForceMeshUpdate(bool ignoreInactive)
{
m_havePropertiesChanged = true;
m_ignoreActiveState = true;
OnPreRenderCanvas();
}
/// <summary>
/// Function used to evaluate the length of a text string.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public override TMP_TextInfo GetTextInfo(string text)
{
StringToCharArray(text, ref m_char_buffer);
SetArraySizes(m_char_buffer);
m_renderMode = TextRenderFlags.DontRender;
ComputeMarginSize();
// Need to make sure we have a valid reference to a Canvas.
if (m_canvas == null) m_canvas = this.canvas;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
return this.textInfo;
}
/// <summary>
/// Function to clear the geometry of the Primary and Sub Text objects.
/// </summary>
public override void ClearMesh()
{
m_canvasRenderer.SetMesh(null);
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
m_subTextObjects[i].canvasRenderer.SetMesh(null);
//if (m_linkedTextComponent != null)
// m_linkedTextComponent.ClearMesh();
}
/// <summary>
/// Function to force the regeneration of the text object.
/// </summary>
/// <param name="flags"> Flags to control which portions of the geometry gets uploaded.</param>
//public override void ForceMeshUpdate(TMP_VertexDataUpdateFlags flags) { }
/// <summary>
/// Function to update the geometry of the main and sub text objects.
/// </summary>
/// <param name="mesh"></param>
/// <param name="index"></param>
public override void UpdateGeometry(Mesh mesh, int index)
{
mesh.RecalculateBounds();
if (index == 0)
{
m_canvasRenderer.SetMesh(mesh);
}
else
{
m_subTextObjects[index].canvasRenderer.SetMesh(mesh);
}
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags)
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
// TODO: Causes issues when sorting geometry as last vertex data attribute get wiped out.
//m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices)
mesh.vertices = m_textInfo.meshInfo[i].vertices;
if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0)
mesh.uv = m_textInfo.meshInfo[i].uvs0;
if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2)
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4)
// mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32)
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
if (i == 0)
m_canvasRenderer.SetMesh(mesh);
else
m_subTextObjects[i].canvasRenderer.SetMesh(mesh);
}
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData()
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
//mesh.MarkDynamic();
mesh.vertices = m_textInfo.meshInfo[i].vertices;
mesh.uv = m_textInfo.meshInfo[i].uvs0;
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
if (i == 0)
m_canvasRenderer.SetMesh(mesh);
else
m_subTextObjects[i].canvasRenderer.SetMesh(mesh);
}
}
public void UpdateFontAsset()
{
LoadFontAsset();
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
[ExtendClass(typeof(System.Threading.ThreadPool))]
public static class ThreadPoolImpl
{
const int c_RecycleLimit = 32;
internal class WorkItem
{
//
// State
//
internal WaitCallback m_callBack;
internal Object m_state;
}
internal class Engine
{
Queue< WorkItem > m_queue;
Queue< WorkItem > m_queueFree;
AutoResetEvent m_wakeup;
int m_maxThreads;
int m_activeThreads;
int m_busyThreads;
//
// Helper Methods
//
internal Engine( )
{
m_queue = new Queue< WorkItem >();
m_queueFree = new Queue< WorkItem >();
m_wakeup = new AutoResetEvent( false );
m_maxThreads = Configuration.DefaultThreadPoolThreads;
}
internal Engine( int maxThreads ) : this()
{
m_maxThreads = maxThreads;
}
//
// Helper Methods
//
internal void Queue( WaitCallback callBack ,
Object state )
{
WorkItem item = null;
if(m_queueFree.Count > 0)
{
lock(m_queueFree)
{
if(m_queueFree.Count > 0)
{
item = m_queueFree.Dequeue();
}
}
}
if(item == null)
{
item = new WorkItem();
}
item.m_callBack = callBack;
item.m_state = state;
int count;
lock(m_queue)
{
m_queue.Enqueue( item );
count = m_queue.Count;
}
if(count == 1)
{
m_wakeup.Set();
}
int active = m_activeThreads;
if(active == m_busyThreads)
{
if(active < m_maxThreads)
{
if(Interlocked.CompareExchange( ref m_activeThreads, active + 1, active ) == active)
{
Thread worker = new Thread( Worker );
worker.IsBackground = true;
worker.Start();
}
}
}
}
internal void SetMaxThreads( int workerThreads )
{
m_maxThreads = workerThreads;
m_wakeup.Set();
}
private void Worker()
{
while(m_activeThreads <= m_maxThreads)
{
m_wakeup.WaitOne();
while(m_queue.Count > 0)
{
WorkItem item;
int count;
lock(m_queue)
{
count = m_queue.Count;
if(count > 0)
{
item = m_queue.Dequeue();
count--;
}
else
{
item = null;
}
}
if(item != null)
{
if(count != 0)
{
m_wakeup.Set();
}
WaitCallback callBack = item.m_callBack;
object state = item.m_state;
if(m_queueFree.Count < c_RecycleLimit)
{
item.m_callBack = null;
item.m_state = null;
lock(m_queueFree)
{
m_queueFree.Enqueue( item );
}
}
Interlocked.Increment( ref m_busyThreads );
try
{
callBack( state );
}
catch
{
}
Interlocked.Decrement( ref m_busyThreads );
}
}
}
Interlocked.Decrement( ref m_activeThreads );
}
}
//
// State
//
private static Engine s_engine = new Engine();
//--//
//
// Helper Methods
//
public static bool QueueUserWorkItem( WaitCallback callBack ,
Object state )
{
s_engine.Queue( callBack, state );
return true;
}
[Inline]
public static bool QueueUserWorkItem( WaitCallback callBack )
{
return QueueUserWorkItem( callBack, null );
}
public static bool SetMaxThreads( int workerThreads ,
int completionPortThreads )
{
s_engine.SetMaxThreads( workerThreads );
return true;
}
//--//
//
// Access Methods
//
}
}
| |
//
// Copyright (C) 2012-2014 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;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Tasks;
using Microsoft.IO;
namespace Cassandra
{
/// <summary>
/// Represents a Tcp connection to a host.
/// It emits Read and WriteCompleted events when data is received.
/// Similar to Netty's Channel or Node.js's net.Socket
/// It handles TLS validation and encryption when required.
/// </summary>
internal class TcpSocket : IDisposable
{
private static Logger _logger = new Logger(typeof(TcpSocket));
private Socket _socket;
private SocketAsyncEventArgs _receiveSocketEvent;
private SocketAsyncEventArgs _sendSocketEvent;
private Stream _socketStream;
private byte[] _receiveBuffer;
private volatile bool _isClosing;
private Action _writeFlushCallback;
public IPEndPoint IPEndPoint { get; protected set; }
public SocketOptions Options { get; protected set; }
public SSLOptions SSLOptions { get; set; }
/// <summary>
/// Event that gets fired when new data is received.
/// </summary>
public event Action<byte[], int> Read;
/// <summary>
/// Event that gets fired when a write async request have been completed.
/// </summary>
public event Action WriteCompleted;
/// <summary>
/// Event that is fired when the host is closing the connection.
/// </summary>
public event Action Closing;
public event Action<Exception, SocketError?> Error;
/// <summary>
/// Creates a new instance of TcpSocket using the endpoint and options provided.
/// </summary>
public TcpSocket(IPEndPoint ipEndPoint, SocketOptions options, SSLOptions sslOptions)
{
IPEndPoint = ipEndPoint;
Options = options;
SSLOptions = sslOptions;
}
/// <summary>
/// Initializes the socket options
/// </summary>
public void Init()
{
_socket = new Socket(IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.SendTimeout = Options.ConnectTimeoutMillis;
if (Options.KeepAlive != null)
{
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, Options.KeepAlive.Value);
}
if (Options.SoLinger != null)
{
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, Options.SoLinger.Value));
}
if (Options.ReceiveBufferSize != null)
{
_socket.ReceiveBufferSize = Options.ReceiveBufferSize.Value;
}
if (Options.SendBufferSize != null)
{
_socket.SendBufferSize = Options.SendBufferSize.Value;
}
if (Options.TcpNoDelay != null)
{
_socket.NoDelay = Options.TcpNoDelay.Value;
}
_receiveBuffer = new byte[_socket.ReceiveBufferSize];
}
/// <summary>
/// Connects asynchronously to the host and starts reading
/// </summary>
/// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
public async Task<bool> Connect()
{
var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>(
Options.ConnectTimeoutMillis,
() => new SocketException((int) SocketError.TimedOut));
var socketConnectTask = tcs.Task;
var eventArgs = new SocketAsyncEventArgs
{
RemoteEndPoint = IPEndPoint
};
eventArgs.Completed += (sender, e) =>
{
if (e.SocketError != SocketError.Success)
{
tcs.TrySetException(new SocketException((int)e.SocketError));
return;
}
tcs.TrySetResult(true);
e.Dispose();
};
try
{
_socket.ConnectAsync(eventArgs);
await socketConnectTask;
}
finally
{
eventArgs.Dispose();
}
if (SSLOptions != null)
{
return await ConnectSsl();
}
// Prepare read and write
// There are 2 modes: using SocketAsyncEventArgs (most performant) and Stream mode
if (Options.UseStreamMode)
{
_logger.Verbose("Socket connected, start reading using Stream interface");
//Stream mode: not the most performant but it is a choice
_socketStream = new NetworkStream(_socket);
ReceiveAsync();
return true;
}
_logger.Verbose("Socket connected, start reading using SocketEventArgs interface");
//using SocketAsyncEventArgs
_receiveSocketEvent = new SocketAsyncEventArgs();
_receiveSocketEvent.SetBuffer(_receiveBuffer, 0, _receiveBuffer.Length);
_receiveSocketEvent.Completed += OnReceiveCompleted;
_sendSocketEvent = new SocketAsyncEventArgs();
_sendSocketEvent.Completed += OnSendCompleted;
ReceiveAsync();
return true;
}
private async Task<bool> ConnectSsl()
{
_logger.Verbose("Socket connected, starting SSL client authentication");
//Stream mode: not the most performant but it has ssl support
var targetHost = IPEndPoint.Address.ToString();
//HostNameResolver is a sync operation but it can block
//Use another thread
await Task.Factory.StartNew(() =>
{
try
{
targetHost = SSLOptions.HostNameResolver(IPEndPoint.Address);
}
catch (Exception ex)
{
_logger.Error(
string.Format(
"SSL connection: Can not resolve host name for address {0}. Using the IP address instead of the host name. This may cause RemoteCertificateNameMismatch error during Cassandra host authentication. Note that the Cassandra node SSL certificate's CN(Common Name) must match the Cassandra node hostname.",
targetHost), ex);
}
}).ConfigureAwait(false);
_logger.Verbose("Starting SSL authentication");
var sslStream = new SslStream(new NetworkStream(_socket), false, SSLOptions.RemoteCertValidationCallback, null);
_socketStream = sslStream;
// Use a timer to ensure that it does callback
var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>(
Options.ConnectTimeoutMillis,
() => new TimeoutException("The timeout period elapsed prior to completion of SSL authentication operation."));
sslStream.AuthenticateAsClientAsync(targetHost,
SSLOptions.CertificateCollection,
SSLOptions.SslProtocol,
SSLOptions.CheckCertificateRevocation)
.ContinueWith(t =>
{
if (t.Exception != null)
{
// ReSharper disable once AssignNullToNotNullAttribute
tcs.TrySetException(t.Exception.InnerException);
return;
}
tcs.TrySetResult(true);
}, TaskContinuationOptions.ExecuteSynchronously)
// Do not await as it may never yield
.Forget();
await tcs.Task.ConfigureAwait(false);
_logger.Verbose("SSL authentication successful");
ReceiveAsync();
return true;
}
/// <summary>
/// Begins an asynchronous request to receive data from a connected Socket object.
/// It handles the exceptions in case there is one.
/// </summary>
protected virtual void ReceiveAsync()
{
//Receive the next bytes
if (_receiveSocketEvent != null)
{
var willRaiseEvent = true;
try
{
willRaiseEvent = _socket.ReceiveAsync(_receiveSocketEvent);
}
catch (ObjectDisposedException)
{
OnError(null, SocketError.NotConnected);
}
catch (NullReferenceException)
{
// Mono can throw a NRE when being disposed concurrently
// https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185
// https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L1873-L1874
OnError(null, SocketError.NotConnected);
}
catch (Exception ex)
{
OnError(ex);
}
if (!willRaiseEvent)
{
OnReceiveCompleted(this, _receiveSocketEvent);
}
}
else
{
// Stream mode
try
{
_socketStream
.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length)
.ContinueWith(OnReceiveStreamCallback, TaskContinuationOptions.ExecuteSynchronously);
}
catch (Exception ex)
{
HandleStreamException(ex);
}
}
}
protected virtual void OnError(Exception ex, SocketError? socketError = null)
{
if (Error != null)
{
Error(ex, socketError);
}
}
/// <summary>
/// Handles the receive completed event
/// </summary>
protected void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
//There was a socket error or the connection is being closed.
OnError(null, e.SocketError);
return;
}
if (e.BytesTransferred == 0)
{
OnClosing();
return;
}
//Emit event
if (Read != null)
{
Read(e.Buffer, e.BytesTransferred);
}
ReceiveAsync();
}
/// <summary>
/// Handles the callback for Completed or Cancelled Task on Stream mode
/// </summary>
protected void OnReceiveStreamCallback(Task<int> readTask)
{
if (readTask.Exception != null)
{
HandleStreamException(readTask.Exception.InnerException);
return;
}
var bytesRead = readTask.Result;
if (bytesRead == 0)
{
OnClosing();
return;
}
//Emit event
try
{
if (Read != null)
{
Read(_receiveBuffer, bytesRead);
}
}
catch (Exception ex)
{
OnError(ex);
}
ReceiveAsync();
}
/// <summary>
/// Handles exceptions that the methods <c>NetworkStream.ReadAsync()</c> and <c>NetworkStream.WriteAsync()</c> can throw.
/// </summary>
private void HandleStreamException(Exception ex)
{
if (ex is IOException)
{
if (ex.InnerException is SocketException)
{
OnError((SocketException)ex.InnerException);
return;
}
// Wrapped ObjectDisposedException and others: we can consider it as not connected
OnError(null, SocketError.NotConnected);
return;
}
if (ex is ObjectDisposedException)
{
// Wrapped ObjectDisposedException and others: we can consider it as not connected
OnError(null, SocketError.NotConnected);
return;
}
OnError(ex);
}
/// <summary>
/// Handles the send completed event
/// </summary>
protected void OnSendCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
OnError(null, e.SocketError);
}
OnWriteFlushed();
if (WriteCompleted != null)
{
WriteCompleted();
}
}
/// <summary>
/// Handles the continuation for WriteAsync faulted or Task on Stream mode
/// </summary>
protected void OnSendStreamCallback(Task writeTask)
{
if (writeTask.Exception != null)
{
HandleStreamException(writeTask.Exception.InnerException);
return;
}
OnWriteFlushed();
if (WriteCompleted != null)
{
WriteCompleted();
}
}
protected void OnClosing()
{
_isClosing = true;
if (Closing != null)
{
Closing.Invoke();
}
if (_receiveSocketEvent != null)
{
//It is safe to call SocketAsyncEventArgs.Dispose() more than once
_sendSocketEvent.Dispose();
_receiveSocketEvent.Dispose();
}
else if (_socketStream != null)
{
_socketStream.Dispose();
}
//dereference to make the byte array GC-able as soon as possible
_receiveBuffer = null;
}
private void OnWriteFlushed()
{
var callback = Interlocked.Exchange(ref _writeFlushCallback, null);
if (callback != null)
{
callback();
}
}
/// <summary>
/// Sends data asynchronously
/// </summary>
public void Write(RecyclableMemoryStream stream, Action onBufferFlush)
{
Interlocked.Exchange(ref _writeFlushCallback, onBufferFlush);
if (_isClosing)
{
OnError(new SocketException((int)SocketError.Shutdown));
OnWriteFlushed();
return;
}
if (_sendSocketEvent != null)
{
_sendSocketEvent.BufferList = stream.GetBufferList();
var isWritePending = false;
try
{
isWritePending = _socket.SendAsync(_sendSocketEvent);
}
catch (ObjectDisposedException)
{
OnError(null, SocketError.NotConnected);
}
catch (NullReferenceException)
{
// Mono can throw a NRE when being disposed concurrently
// https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185
// https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L2477-L2478
OnError(null, SocketError.NotConnected);
}
catch (Exception ex)
{
OnError(ex);
}
if (!isWritePending)
{
OnSendCompleted(this, _sendSocketEvent);
}
}
else
{
var length = (int)stream.Length;
try
{
_socketStream
.WriteAsync(stream.GetBuffer(), 0, length)
.ContinueWith(OnSendStreamCallback, TaskContinuationOptions.ExecuteSynchronously);
}
catch (Exception ex)
{
HandleStreamException(ex);
}
}
}
internal void Kill()
{
_socket.Shutdown(SocketShutdown.Send);
}
public void Dispose()
{
if (_socket == null)
{
return;
}
_isClosing = true;
try
{
//Try to close it.
//Some operations could make the socket to dispose itself
_socket.Shutdown(SocketShutdown.Both);
}
catch
{
// Shutdown might throw an exception if the socket was not open-open
}
try
{
_socket.Dispose();
}
catch
{
//We should not mind if socket's Close method throws an exception
}
if (_receiveSocketEvent != null)
{
//It is safe to call SocketAsyncEventArgs.Dispose() more than once
//Also checked: .NET 4.0, .NET 4.5 and Mono 3.10 and 3.12 implementations
_sendSocketEvent.Dispose();
_receiveSocketEvent.Dispose();
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/iam/v1/iam_policy.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Iam.V1 {
/// <summary>
/// ## API Overview
///
/// Manages Identity and Access Management (IAM) policies.
///
/// Any implementation of an API that offers access control features
/// implements the google.iam.v1.IAMPolicy interface.
///
/// ## Data model
///
/// Access control is applied when a principal (user or service account), takes
/// some action on a resource exposed by a service. Resources, identified by
/// URI-like names, are the unit of access control specification. Service
/// implementations can choose the granularity of access control and the
/// supported permissions for their resources.
/// For example one database service may allow access control to be
/// specified only at the Table level, whereas another might allow access control
/// to also be specified at the Column level.
///
/// ## Policy Structure
///
/// See google.iam.v1.Policy
///
/// This is intentionally not a CRUD style API because access control policies
/// are created and deleted implicitly with the resources to which they are
/// attached.
/// </summary>
public static partial class IAMPolicy
{
static readonly string __ServiceName = "google.iam.v1.IAMPolicy";
static readonly grpc::Marshaller<global::Google.Cloud.Iam.V1.SetIamPolicyRequest> __Marshaller_SetIamPolicyRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Iam.V1.SetIamPolicyRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Iam.V1.Policy> __Marshaller_Policy = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Iam.V1.Policy.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Iam.V1.GetIamPolicyRequest> __Marshaller_GetIamPolicyRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Iam.V1.GetIamPolicyRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Iam.V1.TestIamPermissionsRequest> __Marshaller_TestIamPermissionsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Iam.V1.TestIamPermissionsRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Iam.V1.TestIamPermissionsResponse> __Marshaller_TestIamPermissionsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Iam.V1.TestIamPermissionsResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Iam.V1.SetIamPolicyRequest, global::Google.Cloud.Iam.V1.Policy> __Method_SetIamPolicy = new grpc::Method<global::Google.Cloud.Iam.V1.SetIamPolicyRequest, global::Google.Cloud.Iam.V1.Policy>(
grpc::MethodType.Unary,
__ServiceName,
"SetIamPolicy",
__Marshaller_SetIamPolicyRequest,
__Marshaller_Policy);
static readonly grpc::Method<global::Google.Cloud.Iam.V1.GetIamPolicyRequest, global::Google.Cloud.Iam.V1.Policy> __Method_GetIamPolicy = new grpc::Method<global::Google.Cloud.Iam.V1.GetIamPolicyRequest, global::Google.Cloud.Iam.V1.Policy>(
grpc::MethodType.Unary,
__ServiceName,
"GetIamPolicy",
__Marshaller_GetIamPolicyRequest,
__Marshaller_Policy);
static readonly grpc::Method<global::Google.Cloud.Iam.V1.TestIamPermissionsRequest, global::Google.Cloud.Iam.V1.TestIamPermissionsResponse> __Method_TestIamPermissions = new grpc::Method<global::Google.Cloud.Iam.V1.TestIamPermissionsRequest, global::Google.Cloud.Iam.V1.TestIamPermissionsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"TestIamPermissions",
__Marshaller_TestIamPermissionsRequest,
__Marshaller_TestIamPermissionsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Iam.V1.IamPolicyReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of IAMPolicy</summary>
public abstract partial class IAMPolicyBase
{
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Iam.V1.Policy> SetIamPolicy(global::Google.Cloud.Iam.V1.SetIamPolicyRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Iam.V1.Policy> GetIamPolicy(global::Google.Cloud.Iam.V1.GetIamPolicyRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Iam.V1.TestIamPermissionsResponse> TestIamPermissions(global::Google.Cloud.Iam.V1.TestIamPermissionsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for IAMPolicy</summary>
public partial class IAMPolicyClient : grpc::ClientBase<IAMPolicyClient>
{
/// <summary>Creates a new client for IAMPolicy</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public IAMPolicyClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for IAMPolicy that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public IAMPolicyClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected IAMPolicyClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected IAMPolicyClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.Policy SetIamPolicy(global::Google.Cloud.Iam.V1.SetIamPolicyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetIamPolicy(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.Policy SetIamPolicy(global::Google.Cloud.Iam.V1.SetIamPolicyRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SetIamPolicy, null, options, request);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.Policy> SetIamPolicyAsync(global::Google.Cloud.Iam.V1.SetIamPolicyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetIamPolicyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any
/// existing policy.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.Policy> SetIamPolicyAsync(global::Google.Cloud.Iam.V1.SetIamPolicyRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SetIamPolicy, null, options, request);
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.Policy GetIamPolicy(global::Google.Cloud.Iam.V1.GetIamPolicyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetIamPolicy(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.Policy GetIamPolicy(global::Google.Cloud.Iam.V1.GetIamPolicyRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetIamPolicy, null, options, request);
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.Policy> GetIamPolicyAsync(global::Google.Cloud.Iam.V1.GetIamPolicyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetIamPolicyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets the access control policy for a resource.
/// Returns an empty policy if the resource exists and does not have a policy
/// set.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.Policy> GetIamPolicyAsync(global::Google.Cloud.Iam.V1.GetIamPolicyRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetIamPolicy, null, options, request);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.TestIamPermissionsResponse TestIamPermissions(global::Google.Cloud.Iam.V1.TestIamPermissionsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return TestIamPermissions(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Iam.V1.TestIamPermissionsResponse TestIamPermissions(global::Google.Cloud.Iam.V1.TestIamPermissionsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_TestIamPermissions, null, options, request);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.TestIamPermissionsResponse> TestIamPermissionsAsync(global::Google.Cloud.Iam.V1.TestIamPermissionsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return TestIamPermissionsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns permissions that a caller has on the specified resource.
/// If the resource does not exist, this will return an empty set of
/// permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Iam.V1.TestIamPermissionsResponse> TestIamPermissionsAsync(global::Google.Cloud.Iam.V1.TestIamPermissionsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_TestIamPermissions, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override IAMPolicyClient NewInstance(ClientBaseConfiguration configuration)
{
return new IAMPolicyClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(IAMPolicyBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SetIamPolicy, serviceImpl.SetIamPolicy)
.AddMethod(__Method_GetIamPolicy, serviceImpl.GetIamPolicy)
.AddMethod(__Method_TestIamPermissions, serviceImpl.TestIamPermissions).Build();
}
}
}
#endregion
| |
#region File Description
//-----------------------------------------------------------------------------
// PlayerIndexEventArgs.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
namespace FarseerPhysics.Samples.ScreenSystem
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
private GestureType _enabledGestures = GestureType.None;
private bool _otherScreenHasFocus;
public GameScreen()
{
ScreenState = ScreenState.TransitionOn;
TransitionPosition = 1;
TransitionOffTime = TimeSpan.Zero;
TransitionOnTime = TimeSpan.Zero;
HasCursor = false;
HasVirtualStick = false;
}
public bool HasCursor { get; set; }
public bool HasVirtualStick { get; set; }
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup { get; protected set; }
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime { get; protected set; }
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime { get; protected set; }
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition { get; protected set; }
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 1 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionAlpha
{
get { return 1f - TransitionPosition; }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState { get; protected set; }
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting { get; protected internal set; }
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive { get { return !_otherScreenHasFocus && (ScreenState == ScreenState.TransitionOn || ScreenState == ScreenState.Active); } }
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager { get; internal set; }
/// <summary>
/// Gets the gestures the screen is interested in. Screens should be as specific
/// as possible with gestures to increase the accuracy of the gesture engine.
/// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate.
/// These gestures are handled by the ScreenManager when screens change and
/// all gestures are placed in the InputState passed to the HandleInput method.
/// </summary>
public GestureType EnabledGestures
{
get { return _enabledGestures; }
protected set
{
_enabledGestures = value;
// the screen manager handles this during screen changes, but
// if this screen is active and the gesture types are changing,
// we have to update the TouchPanel ourself.
if (ScreenState == ScreenState.Active)
TouchPanel.EnabledGestures = value;
}
}
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent()
{
}
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent()
{
}
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
_otherScreenHasFocus = otherScreenHasFocus;
if (IsExiting)
{
// If the screen is going away to die, it should transition off.
ScreenState = ScreenState.TransitionOff;
// When the transition finishes, remove the screen.
if (!UpdateTransition(gameTime, TransitionOffTime, 1))
ScreenManager.RemoveScreen(this);
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
ScreenState = UpdateTransition(gameTime, TransitionOffTime, 1) ? ScreenState.TransitionOff : ScreenState.Hidden;
}
else
{
// Otherwise the screen should transition on and become active.
ScreenState = UpdateTransition(gameTime, TransitionOnTime, -1) ? ScreenState.TransitionOn : ScreenState.Active;
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
private bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1f;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds);
// Update the transition position.
TransitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if (((direction < 0) && (TransitionPosition <= 0)) || ((direction > 0) && (TransitionPosition >= 1)))
{
TransitionPosition = MathHelper.Clamp(TransitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputHelper input, GameTime gameTime)
{
}
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime)
{
}
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
IsExiting = true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.NativeCrypto;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
/// <summary>
/// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it
/// easier to split the class into abstract and implementation classes if desired.)
/// </summary>
internal sealed partial class X509Pal : IX509Pal
{
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
unsafe
{
ushort keyUsagesAsShort = (ushort)keyUsages;
CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB()
{
cbData = 2,
pbData = (byte*)&keyUsagesAsShort,
cUnusedBits = 0,
};
return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob);
}
}
public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
unsafe
{
uint keyUsagesAsUint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_KEY_USAGE,
delegate (void* pvDecoded)
{
CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded;
keyUsagesAsUint = 0;
if (pBlob->pbData != null)
{
keyUsagesAsUint = *(uint*)(pBlob->pbData);
}
}
);
keyUsages = (X509KeyUsageFlags)keyUsagesAsUint;
}
}
public bool SupportsLegacyBasicConstraintsExtension
{
get { return true; }
}
public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint)
{
unsafe
{
CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO()
{
fCA = certificateAuthority ? 1 : 0,
fPathLenConstraint = hasPathLengthConstraint ? 1 : 0,
dwPathLenConstraint = pathLengthConstraint,
};
return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo);
}
}
public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS,
delegate (void* pvDecoded)
{
CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded;
localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0;
localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint)
{
unsafe
{
bool localCertificateAuthority = false;
bool localHasPathLengthConstraint = false;
int localPathLengthConstraint = 0;
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2,
delegate (void* pvDecoded)
{
CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded;
localCertificateAuthority = pBasicConstraints2->fCA != 0;
localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0;
localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint;
}
);
certificateAuthority = localCertificateAuthority;
hasPathLengthConstraint = localHasPathLengthConstraint;
pathLengthConstraint = localPathLengthConstraint;
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
int numUsages;
using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages))
{
unsafe
{
CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE()
{
cUsageIdentifier = numUsages,
rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()),
};
return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage);
}
}
}
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection localUsages = new OidCollection();
unsafe
{
encoded.DecodeObject(
CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE,
delegate (void* pvDecoded)
{
CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded;
int count = pEnhKeyUsage->cUsageIdentifier;
for (int i = 0; i < count; i++)
{
IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i];
string oidValue = Marshal.PtrToStringAnsi(oidValuePointer);
Oid oid = new Oid(oidValue);
localUsages.Add(oid);
}
}
);
}
usages = localUsages;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
unsafe
{
fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier)
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier);
return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob);
}
}
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
unsafe
{
byte[] localSubjectKeyIdentifier = null;
encoded.DecodeObject(
Oids.SubjectKeyIdentifier,
delegate (void* pvDecoded)
{
CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded;
localSubjectKeyIdentifier = pBlob->ToByteArray();
}
);
subjectKeyIdentifier = localSubjectKeyIdentifier;
}
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
unsafe
{
fixed (byte* pszOidValue = key.Oid.ValueAsAscii())
{
byte[] encodedParameters = key.EncodedParameters.RawData;
fixed (byte* pEncodedParameters = encodedParameters)
{
byte[] encodedKeyValue = key.EncodedKeyValue.RawData;
fixed (byte* pEncodedKeyValue = encodedKeyValue)
{
CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO()
{
Algorithm = new CRYPT_ALGORITHM_IDENTIFIER()
{
pszObjId = new IntPtr(pszOidValue),
Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters),
},
PublicKey = new CRYPT_BIT_BLOB()
{
cbData = encodedKeyValue.Length,
pbData = pEncodedKeyValue,
cUnusedBits = 0,
},
};
int cb = 20;
byte[] buffer = new byte[cb];
if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (cb < buffer.Length)
{
byte[] newBuffer = new byte[cb];
Array.Copy(buffer, 0, newBuffer, 0, cb);
buffer = newBuffer;
}
return buffer;
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.Security;
namespace System.Runtime.Serialization
{
internal abstract class PrimitiveDataContract : DataContract
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private PrimitiveDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns))
{
_helper = base.Helper as PrimitiveDataContractCriticalHelper;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(Type type)
{
return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(string name, string ns)
{
return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract;
}
internal abstract string WriteMethodName { get; }
internal abstract string ReadMethodName { get; }
internal override XmlDictionaryString TopLevelElementNamespace
{
/// <SecurityNote>
/// Critical - for consistency with base class
/// Safe - for consistency with base class
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return DictionaryGlobals.SerializationNamespace; }
/// <SecurityNote>
/// Critical - for consistency with base class
/// </SecurityNote>
[SecurityCritical]
set
{ }
}
internal override bool CanContainReferences
{
get { return false; }
}
internal override bool IsPrimitive
{
get { return true; }
}
internal override bool IsBuiltInDataContract
{
get
{
return true;
}
}
internal MethodInfo XmlFormatWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatWriterMethod property
/// Safe - XmlFormatWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
else
_helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
}
return _helper.XmlFormatWriterMethod;
}
}
internal MethodInfo XmlFormatContentWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatContentWriterMethod property
/// Safe - XmlFormatContentWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatContentWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType });
else
_helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType });
}
return _helper.XmlFormatContentWriterMethod;
}
}
internal MethodInfo XmlFormatReaderMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatReaderMethod property
/// Safe - XmlFormatReaderMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderMethod == null)
{
_helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers);
}
return _helper.XmlFormatReaderMethod;
}
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
xmlWriter.WriteAnyType(obj);
}
protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
Attributes attributes = new Attributes();
attributes.Read(reader);
if (attributes.Ref != Globals.NewObjectId)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotDeserializeRefAtTopLevel, attributes.Ref)));
if (attributes.XsiNil)
{
reader.Skip();
return true;
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for for (de)serializing primitives.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private MethodInfo _xmlFormatWriterMethod;
private MethodInfo _xmlFormatContentWriterMethod;
private MethodInfo _xmlFormatReaderMethod;
internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type)
{
SetDataContractName(name, ns);
}
internal MethodInfo XmlFormatWriterMethod
{
get { return _xmlFormatWriterMethod; }
set { _xmlFormatWriterMethod = value; }
}
internal MethodInfo XmlFormatContentWriterMethod
{
get { return _xmlFormatContentWriterMethod; }
set { _xmlFormatContentWriterMethod = value; }
}
internal MethodInfo XmlFormatReaderMethod
{
get { return _xmlFormatReaderMethod; }
set { _xmlFormatReaderMethod = value; }
}
}
}
internal class CharDataContract : PrimitiveDataContract
{
internal CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteChar"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteChar((char)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsChar()
: HandleReadValue(reader.ReadElementContentAsChar(), context);
}
}
internal class BooleanDataContract : PrimitiveDataContract
{
internal BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBoolean"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBoolean((bool)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsBoolean()
: HandleReadValue(reader.ReadElementContentAsBoolean(), context);
}
}
internal class SignedByteDataContract : PrimitiveDataContract
{
internal SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteSignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteSignedByte((sbyte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsSignedByte()
: HandleReadValue(reader.ReadElementContentAsSignedByte(), context);
}
}
internal class UnsignedByteDataContract : PrimitiveDataContract
{
internal UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedByte((byte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedByte()
: HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context);
}
}
internal class ShortDataContract : PrimitiveDataContract
{
internal ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteShort((short)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsShort()
: HandleReadValue(reader.ReadElementContentAsShort(), context);
}
}
internal class UnsignedShortDataContract : PrimitiveDataContract
{
internal UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedShort((ushort)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedShort()
: HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context);
}
}
internal class IntDataContract : PrimitiveDataContract
{
internal IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteInt((int)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsInt()
: HandleReadValue(reader.ReadElementContentAsInt(), context);
}
}
internal class UnsignedIntDataContract : PrimitiveDataContract
{
internal UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedInt((uint)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedInt()
: HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context);
}
}
internal class LongDataContract : PrimitiveDataContract
{
internal LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteLong((long)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsLong()
: HandleReadValue(reader.ReadElementContentAsLong(), context);
}
}
internal class UnsignedLongDataContract : PrimitiveDataContract
{
internal UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedLong((ulong)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedLong()
: HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context);
}
}
internal class FloatDataContract : PrimitiveDataContract
{
internal FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteFloat"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteFloat((float)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsFloat()
: HandleReadValue(reader.ReadElementContentAsFloat(), context);
}
}
internal class DoubleDataContract : PrimitiveDataContract
{
internal DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDouble"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDouble((double)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDouble()
: HandleReadValue(reader.ReadElementContentAsDouble(), context);
}
}
internal class DecimalDataContract : PrimitiveDataContract
{
internal DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDecimal"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDecimal((decimal)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDecimal()
: HandleReadValue(reader.ReadElementContentAsDecimal(), context);
}
}
internal class DateTimeDataContract : PrimitiveDataContract
{
internal DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDateTime"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDateTime((DateTime)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDateTime()
: HandleReadValue(reader.ReadElementContentAsDateTime(), context);
}
}
internal class StringDataContract : PrimitiveDataContract
{
internal StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteString"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsString"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteString((string)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString();
}
else
{
return HandleReadValue(reader.ReadElementContentAsString(), context);
}
}
}
internal class HexBinaryDataContract : StringDataContract
{
internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { }
}
internal class ByteArrayDataContract : PrimitiveDataContract
{
internal ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBase64"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBase64((byte[])obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64();
}
else
{
return HandleReadValue(reader.ReadElementContentAsBase64(), context);
}
}
}
internal class ObjectDataContract : PrimitiveDataContract
{
internal ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteAnyType"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
// write nothing
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
object obj;
if (reader.IsEmptyElement)
{
reader.Skip();
obj = new object();
}
else
{
string localName = reader.LocalName;
string ns = reader.NamespaceURI;
reader.Read();
try
{
reader.ReadEndElement();
obj = new object();
}
catch (XmlException xes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes));
}
}
return (context == null) ? obj : HandleReadValue(obj, context);
}
internal override bool CanContainReferences
{
get { return true; }
}
internal override bool IsPrimitive
{
get { return false; }
}
}
internal class TimeSpanDataContract : PrimitiveDataContract
{
internal TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteTimeSpan"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteTimeSpan((TimeSpan)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsTimeSpan()
: HandleReadValue(reader.ReadElementContentAsTimeSpan(), context);
}
}
internal class GuidDataContract : PrimitiveDataContract
{
internal GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteGuid"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteGuid((Guid)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsGuid()
: HandleReadValue(reader.ReadElementContentAsGuid(), context);
}
}
internal class UriDataContract : PrimitiveDataContract
{
internal UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUri"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUri((Uri)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri();
}
else
{
return HandleReadValue(reader.ReadElementContentAsUri(), context);
}
}
}
internal class QNameDataContract : PrimitiveDataContract
{
internal QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteQName"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsQName"; } }
internal override bool IsPrimitive
{
get { return false; }
}
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteQName((XmlQualifiedName)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName();
}
else
{
return HandleReadValue(reader.ReadElementContentAsQName(), context);
}
}
internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
{
if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace))
writer.WriteStartElement(Globals.SerPrefix, name, ns);
else if (ns != null && ns.Value != null && ns.Value.Length > 0)
writer.WriteStartElement(Globals.ElementPrefix, name, ns);
else
writer.WriteStartElement(name, ns);
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using Thrift.Transport.Server;
using tutorial;
using shared;
using Thrift.Processor;
using System.Diagnostics;
namespace Server
{
public class Program
{
private static ServiceCollection ServiceCollection = new ServiceCollection();
private static ILogger Logger;
private static readonly TConfiguration Configuration = null; // new TConfiguration() if needed
public static void Main(string[] args)
{
args = args ?? new string[0];
ServiceCollection.AddLogging(logging => ConfigureLogging(logging));
Logger = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger(nameof(Server));
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
Logger.LogInformation("Press any key to stop...");
Console.ReadLine();
source.Cancel();
}
Logger.LogInformation("Server stopped");
}
private static void ConfigureLogging(ILoggingBuilder logging)
{
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddConsole();
logging.AddDebug();
}
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Server.exe -help
will diplay help information
Server.exe -tr:<transport> -bf:<buffering> -pr:<protocol>
will run server with specified arguments (tcp transport, no buffering, and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (http address - ""localhost:9090"")
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
-bf (buffering):
none - (default) no buffering will be used
buffered - buffered transport will be used
framed - framed transport will be used
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
Sample:
Server.exe -tr:tcp
");
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var selectedTransport = GetTransport(args);
var selectedBuffering = GetBuffering(args);
var selectedProtocol = GetProtocol(args);
if (selectedTransport == Transport.Http)
{
new HttpServerSample().Run(cancellationToken);
}
else
{
await RunSelectedConfigurationAsync(selectedTransport, selectedBuffering, selectedProtocol, cancellationToken);
}
}
private static Protocol GetProtocol(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Protocol selectedProtocol);
return selectedProtocol;
}
private static Buffering GetBuffering(string[] args)
{
var buffering = args.FirstOrDefault(x => x.StartsWith("-bf"))?.Split(":")?[1];
Enum.TryParse<Buffering>(buffering, out var selectedBuffering);
return selectedBuffering;
}
private static Transport GetTransport(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Transport selectedTransport);
return selectedTransport;
}
private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, CancellationToken cancellationToken)
{
var handler = new CalculatorAsyncHandler();
TServerTransport serverTransport = null;
switch (transport)
{
case Transport.Tcp:
serverTransport = new TServerSocketTransport(9090, Configuration);
break;
case Transport.NamedPipe:
serverTransport = new TNamedPipeServerTransport(".test", Configuration);
break;
case Transport.TcpTls:
serverTransport = new TTlsServerSocketTransport(9090, Configuration,
GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback);
break;
}
TTransportFactory inputTransportFactory = null;
TTransportFactory outputTransportFactory = null;
switch (buffering)
{
case Buffering.Buffered:
inputTransportFactory = new TBufferedTransport.Factory();
outputTransportFactory = new TBufferedTransport.Factory();
break;
case Buffering.Framed:
inputTransportFactory = new TFramedTransport.Factory();
outputTransportFactory = new TFramedTransport.Factory();
break;
default: // layered transport(s) are optional
Debug.Assert(buffering == Buffering.None, "unhandled case");
break;
}
TProtocolFactory inputProtocolFactory = null;
TProtocolFactory outputProtocolFactory = null;
ITAsyncProcessor processor = null;
switch (protocol)
{
case Protocol.Binary:
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Compact:
inputProtocolFactory = new TCompactProtocol.Factory();
outputProtocolFactory = new TCompactProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Json:
inputProtocolFactory = new TJsonProtocol.Factory();
outputProtocolFactory = new TJsonProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Multiplexed:
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
var calcHandler = new CalculatorAsyncHandler();
var calcProcessor = new Calculator.AsyncProcessor(calcHandler);
var sharedServiceHandler = new SharedServiceAsyncHandler();
var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler);
var multiplexedProcessor = new TMultiplexedProcessor();
multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor);
multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor);
processor = multiplexedProcessor;
break;
default:
throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
}
try
{
Logger.LogInformation(
$"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories");
var loggerFactory = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>();
var server = new TSimpleAsyncServer(
itProcessorFactory: new TSingletonProcessorFactory(processor),
serverTransport: serverTransport,
inputTransportFactory: inputTransportFactory,
outputTransportFactory: outputTransportFactory,
inputProtocolFactory: inputProtocolFactory,
outputProtocolFactory: outputProtocolFactory,
logger: loggerFactory.CreateLogger<TSimpleAsyncServer>());
Logger.LogInformation("Starting the server...");
await server.ServeAsync(cancellationToken);
}
catch (Exception x)
{
Logger.LogInformation(x.ToString());
}
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool ClientCertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private enum Transport
{
Tcp,
NamedPipe,
Http,
TcpTls,
}
private enum Buffering
{
None,
Buffered,
Framed,
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
public class HttpServerSample
{
public void Run(CancellationToken cancellationToken)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseUrls("http://localhost:9090")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureLogging((ctx,logging) => ConfigureLogging(logging))
.Build();
Logger.LogTrace("test");
Logger.LogCritical("test");
host.RunAsync(cancellationToken).GetAwaiter().GetResult();
}
public class Startup
{
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<Calculator.IAsync, CalculatorAsyncHandler>();
services.AddTransient<ITAsyncProcessor, Calculator.AsyncProcessor>();
services.AddTransient<THttpServerTransport, THttpServerTransport>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<THttpServerTransport>();
}
}
}
public class CalculatorAsyncHandler : Calculator.IAsync
{
private readonly Dictionary<int, SharedStruct> _log = new Dictionary<int, SharedStruct>();
public CalculatorAsyncHandler()
{
}
public async Task<SharedStruct> getStructAsync(int key,
CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(_log[key]);
}
public async Task pingAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("PingAsync()");
await Task.CompletedTask;
}
public async Task<int> addAsync(int num1, int num2, CancellationToken cancellationToken)
{
Logger.LogInformation($"AddAsync({num1},{num2})");
return await Task.FromResult(num1 + num2);
}
public async Task<int> calculateAsync(int logid, Work w, CancellationToken cancellationToken)
{
Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])");
var val = 0;
switch (w.Op)
{
case Operation.ADD:
val = w.Num1 + w.Num2;
break;
case Operation.SUBTRACT:
val = w.Num1 - w.Num2;
break;
case Operation.MULTIPLY:
val = w.Num1 * w.Num2;
break;
case Operation.DIVIDE:
if (w.Num2 == 0)
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Cannot divide by 0"
};
throw io;
}
val = w.Num1 / w.Num2;
break;
default:
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Unknown operation"
};
throw io;
}
}
var entry = new SharedStruct
{
Key = logid,
Value = val.ToString()
};
_log[logid] = entry;
return await Task.FromResult(val);
}
public async Task zipAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("ZipAsync() with delay 100mc");
await Task.Delay(100, CancellationToken.None);
}
}
public class SharedServiceAsyncHandler : SharedService.IAsync
{
public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(new SharedStruct()
{
Key = key,
Value = "GetStructAsync"
});
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using ExampleExtension.Cryptography;
using Ivvy.Extensions;
using Ivvy.Extensions.Setup;
using Ivvy.Extensions.Unsetup;
using Ivvy.Extensions.Configure;
namespace ExampleExtension.Accounts
{
/// <summary>
/// Implementation of the required extension services that uses DynamoDB.
/// </summary>
public sealed class AccountServices : IAccountServices
{
private IDynamoDBContext Context { get; set; }
private ExtensionSettings Settings { get; set; }
private ILogger Logger { get; set; }
public AccountServices(
IAmazonDynamoDB dynamoDbClient,
IOptions<ExtensionSettings> settings,
ILogger<AccountServices> logger)
{
Context = new DynamoDBContext(dynamoDbClient);
Settings = settings.Value;
Logger = logger;
}
/// <summary>
/// Registers an iVvy client account with the extension.
/// </summary>
public async Task<Account> SetupAccount(SetupRequest request)
{
// We must verify the setup request in order to obtain
// the account details including the api credentials.
// It also confirms the request originated from iVVy.
Extension ext = new Extension(
request.IvvySetupVerifyUrl,
request.IvvySetupConfigureUrl,
request.IvvyEventSetupVerifyUrl,
request.IvvyEventSetupConfigureUrl,
request.IvvyVenueSetupVerifyUrl,
request.IvvyVenueSetupConfigureUrl
);
ResultOrError<VerifySetupResponse> verifyResult =
await ext.VerifySetupAsync(request.AccountId, request.SetupKey);
if (verifyResult.Success) {
VerifySetupResponse verifyResponse = verifyResult.Result;
Account account = new Account {
Pk = $"{request.Region}:{verifyResponse.AccountId}",
Region = request.Region,
Id = verifyResponse.AccountId,
SetupKey = request.SetupKey,
ApiKey = verifyResponse.ApiKey,
ApiSecret = verifyResponse.ApiSecret,
IvvyApiEndPoint = request.IvvyApiEndPoint,
IvvySetupVerifyUrl = request.IvvySetupVerifyUrl,
IvvySetupConfigureUrl = request.IvvySetupConfigureUrl,
IvvyEventSetupVerifyUrl = request.IvvyEventSetupVerifyUrl,
IvvyEventSetupConfigureUrl = request.IvvyEventSetupConfigureUrl,
IvvyVenueSetupVerifyUrl = request.IvvyVenueSetupVerifyUrl,
IvvyVenueSetupConfigureUrl = request.IvvyVenueSetupConfigureUrl
};
await AddAccountAsync(account);
return account;
}
else {
Logger.LogError($"Setup Error: {verifyResult.ErrorMessage}");
return null;
}
}
/// <summary>
/// Unregisters an iVvy client account with the extension.
/// </summary>
public async Task<bool> UnsetupAccount(UnsetupRequest request)
{
// Always verify the account exists before handling the request.
// This confirms the request originated from iVvy.
// The following code will delete the account details from DynamoDB
// if it exists. The extension must handle the situation where
// a client continuously adds/removes the extension to/from their account.
Account account = await FindAccountAsync(
request.Region, request.AccountId, request.SetupKey
);
if (account == null) {
return false;
}
else {
await DeleteAccountAsync(account);
return true;
}
}
/// <summary>
/// Used by the extension to notify iVvy that it has been
/// successfully configured for a client account.
/// </summary>
public async Task NotifyAccountConfigured(Account account)
{
// Verify the required account data.
if (account.Id == null || account.Id.Trim() == "") {
throw new ArgumentException("account does not have an Id value");
}
if (account.SetupKey == null || account.SetupKey.Trim() == "") {
throw new ArgumentException("account does not have a SetupKey value");
}
Extension extension = new Extension(
account.IvvySetupVerifyUrl,
account.IvvySetupConfigureUrl,
account.IvvyEventSetupVerifyUrl,
account.IvvyEventSetupConfigureUrl,
account.IvvyVenueSetupVerifyUrl,
account.IvvyVenueSetupConfigureUrl
);
ResultOrError<VerifyConfigureResponse> verifyResult =
await extension.ConfigureAsync(account.Id, account.SetupKey);
if (!verifyResult.Success) {
Logger.LogError("Unknown configure error");
}
}
/// <summary>
/// Looks up a registered client account by its unique id and setup key.
/// </summary>
public async Task<Account> FindAccountAsync(string region, string id, string setupKey = null)
{
Account account = await Context.LoadAsync<Account>($"{region}:{id}");
if (account != null && setupKey != null) {
if (account.SetupKey != setupKey) {
account = null;
}
}
return account;
}
/// <summary>
/// Adds the details of an iVvy client account to DynamoDB.
/// </summary>
public async Task AddAccountAsync(Account account)
{
// Verify the required account data.
if (account.Pk == null || account.Pk.Trim() == "") {
throw new ArgumentException("account does not have a Pk value");
}
if (account.Id == null || account.Id.Trim() == "") {
throw new ArgumentException("account does not have an Id value");
}
if (account.SetupKey == null || account.SetupKey.Trim() == "") {
throw new ArgumentException("account does not have a SetupKey value");
}
if (account.ApiKey == null || account.ApiKey.Trim() == "") {
throw new ArgumentException("account does not have an ApiKey value");
}
if (account.ApiSecret == null || account.ApiSecret.Trim() == "") {
throw new ArgumentException("account does not have an ApiSecret value");
}
// Encrypt the api credentials.
account.ApiKey = StringCipher.Encrypt(account.ApiKey, Settings.CipherPassphrase);
account.ApiSecret = StringCipher.Encrypt(account.ApiSecret, Settings.CipherPassphrase);
// Save the new account.
await Context.SaveAsync<Account>(account);
}
/// <summary>
/// Deletes the details of an iVvy client account from DynamoDB.
/// </summary>
public async Task DeleteAccountAsync(Account account)
{
// Verify the required account data.
if (account.Pk == null || account.Pk.Trim() == "") {
throw new ArgumentException("account does not have a Pk value");
}
// Delete the account.
await Context.DeleteAsync<Account>(account.Pk);
}
/// <summary>
/// Returns the iVvy api credentials for a specific account.
/// The first value in the tuple is the api key.
/// The second value in the tuple is the api secret.
/// </summary>
public Tuple<string, string> GetIvvyApiCredentials(Account account)
{
return new Tuple<string, string>(
StringCipher.Decrypt(account.ApiKey, Settings.CipherPassphrase),
StringCipher.Decrypt(account.ApiSecret, Settings.CipherPassphrase)
);
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// Carton
/// </summary>
[DataContract]
public partial class Carton : IEquatable<Carton>
{
/// <summary>
/// Initializes a new instance of the <see cref="Carton" /> class.
/// </summary>
[JsonConstructorAttribute]
protected Carton() { }
/// <summary>
/// Initializes a new instance of the <see cref="Carton" /> class.
/// </summary>
/// <param name="OrderNo">OrderNo (required).</param>
/// <param name="CartonNo">CartonNo.</param>
/// <param name="CartonTypeId">CartonTypeId (required).</param>
/// <param name="CartonLPN">CartonLPN.</param>
/// <param name="WeightLbs">WeightLbs.</param>
public Carton(double? OrderNo = null, int? CartonNo = null, int? CartonTypeId = null, string CartonLPN = null, double? WeightLbs = null)
{
// to ensure "OrderNo" is required (not null)
if (OrderNo == null)
{
throw new InvalidDataException("OrderNo is a required property for Carton and cannot be null");
}
else
{
this.OrderNo = OrderNo;
}
// to ensure "CartonTypeId" is required (not null)
if (CartonTypeId == null)
{
throw new InvalidDataException("CartonTypeId is a required property for Carton and cannot be null");
}
else
{
this.CartonTypeId = CartonTypeId;
}
this.CartonNo = CartonNo;
this.CartonLPN = CartonLPN;
this.WeightLbs = WeightLbs;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; set; }
/// <summary>
/// Gets or Sets CartonNo
/// </summary>
[DataMember(Name="cartonNo", EmitDefaultValue=false)]
public int? CartonNo { get; set; }
/// <summary>
/// Gets or Sets CartonTypeId
/// </summary>
[DataMember(Name="cartonTypeId", EmitDefaultValue=false)]
public int? CartonTypeId { get; set; }
/// <summary>
/// Gets or Sets CartonLPN
/// </summary>
[DataMember(Name="cartonLPN", EmitDefaultValue=false)]
public string CartonLPN { get; set; }
/// <summary>
/// Gets or Sets WeightLbs
/// </summary>
[DataMember(Name="weightLbs", EmitDefaultValue=false)]
public double? WeightLbs { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Carton {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" CartonNo: ").Append(CartonNo).Append("\n");
sb.Append(" CartonTypeId: ").Append(CartonTypeId).Append("\n");
sb.Append(" CartonLPN: ").Append(CartonLPN).Append("\n");
sb.Append(" WeightLbs: ").Append(WeightLbs).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Carton);
}
/// <summary>
/// Returns true if Carton instances are equal
/// </summary>
/// <param name="other">Instance of Carton to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Carton other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.CartonNo == other.CartonNo ||
this.CartonNo != null &&
this.CartonNo.Equals(other.CartonNo)
) &&
(
this.CartonTypeId == other.CartonTypeId ||
this.CartonTypeId != null &&
this.CartonTypeId.Equals(other.CartonTypeId)
) &&
(
this.CartonLPN == other.CartonLPN ||
this.CartonLPN != null &&
this.CartonLPN.Equals(other.CartonLPN)
) &&
(
this.WeightLbs == other.WeightLbs ||
this.WeightLbs != null &&
this.WeightLbs.Equals(other.WeightLbs)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.CartonNo != null)
hash = hash * 59 + this.CartonNo.GetHashCode();
if (this.CartonTypeId != null)
hash = hash * 59 + this.CartonTypeId.GetHashCode();
if (this.CartonLPN != null)
hash = hash * 59 + this.CartonLPN.GetHashCode();
if (this.WeightLbs != null)
hash = hash * 59 + this.WeightLbs.GetHashCode();
return hash;
}
}
}
}
| |
//--------------------------------------
// OpenTransfr
//
// For documentation or
// if you have any issues, visit
// opentrans.fr
//
// Licensed under MIT
//--------------------------------------
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using Wrench;
namespace OpenTransfr{
/// <summary>
/// A class for performing HTTP requests.
/// </summary>
public static class Http{
/// <summary>Sends a GET request with no headers.</summary>
public static string Request(string url,out HttpResponse head){
// No headers:
Dictionary<string,string> headers=null;
// Make a request:
return Request(url,headers,out head);
}
/// <summary>Sends a GET request with the given custom headers.</summary>
public static string Request(string url,Dictionary<string,string> headers,out HttpResponse head){
string resp="";
try{
// Create the request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Apply the headers to the request, handling any standard headers:
HandleHeaders(request,headers);
// Get the response:
HttpWebResponse response=(HttpWebResponse)( request.GetResponse() );
StreamReader reader = new StreamReader(response.GetResponseStream());
resp=reader.ReadToEnd();
// Create the response object:
head=new HttpResponse(response);
// Tidy up:
reader.Close();
response.Close();
}catch{
// Something went wrong.
head=new HttpResponse(null);
}
return resp;
}
/// <summary>Performs a HTTP POST with custom headers.</summary>
public static string Request(string url,string postData,Dictionary<string,string> headers,out HttpResponse head){
// The post data as bytes:
byte[] bytes=null;
if(postData!=null){
// We've got some post data - get it's bytes now:
bytes=Encoding.UTF8.GetBytes(postData);
}
// Perform a POST request with the bytes:
return Request(url,bytes,headers,out head);
}
/// <summary>Performs a HTTP POST with no custom headers.</summary>
public static string Request(string url,string postData,out HttpResponse head){
return Request(url,postData,null,out head);
}
/// <summary>Applies the given set of headers to the given request.</summary>
private static void HandleHeaders(HttpWebRequest httpWReq,Dictionary<string,string> headers){
if(headers==null){
// None to apply - stop there.
return;
}
// For each header..
foreach(KeyValuePair<string,string> kvp in headers){
// Certain headers require special handling.
if(kvp.Key=="Content-Type"){
// Content type header - special handling:
httpWReq.ContentType=kvp.Value;
continue;
}else if(kvp.Key=="Accept"){
// Accept header - special handling:
httpWReq.Accept=kvp.Value;
continue;
}else if(kvp.Key=="Method"){
// Method header - special handling:
httpWReq.Method=kvp.Value;
continue;
}
// Apply the header to the request's headers set:
httpWReq.Headers[kvp.Key]=kvp.Value;
}
}
/// <summary>Sends a GET request and parses the response as JSON.</summary>
public static JSObject RequestJson(string url,out HttpResponse head){
// Request and parse:
return Request(url,(JSObject)null,null,out head);
}
/// <summary>Posts the given JSON to the given URL.
/// Performs a GET if no JSON is provided.
/// The response is parsed as JSON.</summary>
public static JSObject Request(string url,JSObject json,out HttpResponse head){
return Request(url,json,null,out head);
}
/// <summary>Posts the given JSON to the given URL with optional custom headers.
/// Performs a GET if no JSON is provided.
/// The response is parsed as JSON.</summary>
public static JSObject Request(string url,JSObject json,Dictionary<string,string> headers,out HttpResponse head){
// Got a JSON payload?
if(json==null){
// Perform a GET request and parse the response as JSON.
return JSON.Parse( Request(url,headers,out head) );
}
// Make sure we use the application/json content type:
string type="application/json";
if(headers!=null){
// Apply the content type:
headers["Content-Type"]=type;
}
// Get the bytes of the JSON payload:
byte[] payload=System.Text.Encoding.UTF8.GetBytes( JSON.Stringify(json) );
// Perform the request now, and parse the response:
return JSON.Parse( Request(url,payload,headers,type,out head) );
}
/// <summary>Performs a POST request with optional custom headers.
/// If no headers are given, it assumes the content-type is application/x-www-form-urlencoded.</summary>
public static string Request(string url,byte[] postData,Dictionary<string,string> headers,out HttpResponse head){
// Perform a POST request with the default urlencoded type:
return Request(url,postData,headers,"application/x-www-form-urlencoded",out head);
}
/// <summary>Performs a POST request with optional custom headers.
/// If no headers are given, the content-type of the post data is given as cType.</summary>
public static string Request(string url,byte[] postData,Dictionary<string,string> headers,string cType,out HttpResponse head){
string response="";
// Do we have any post data?
if(postData==null){
postData=new byte[0];
}
try{
// Start the request:
HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create(url);
// It's a post request:
httpWReq.Method="POST";
if(headers==null){
// No headers - apply content-type:
httpWReq.ContentType=cType;
}else{
// Handle the headers which should contain our Content-Type:
HandleHeaders(httpWReq,headers);
}
// Apply the content length:
httpWReq.ContentLength=postData.Length;
// Start writing out the post data:
using(Stream stream=httpWReq.GetRequestStream()){
stream.Write(postData,0,postData.Length);
}
// Get the response:
HttpWebResponse webResponse=(HttpWebResponse)(httpWReq.GetResponse());
// Create the response object:
head=new HttpResponse(webResponse);
StreamReader reader=new StreamReader(webResponse.GetResponseStream());
response=reader.ReadToEnd();
}catch{
// Something went wrong.
head=new HttpResponse(null);
}
return response;
}
/// <summary>Encodes the given piece of text so it's suitable to go into a post or get string.</summary>
/// <param name="text">The text to encode.</param>
/// <returns>The url encoded text.</returns>
public static string UrlEncode(string text){
return System.Uri.EscapeDataString(text);
}
}
}
| |
using BarcodeLib;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace BarcodeStandardExample
{
/// <summary>
/// This form is a test form to show what all you can do with the Barcode Library.
/// Only one call is actually needed to do the encoding and return the image of the
/// barcode but the rest is just flare and user interface ... stuff.
/// </summary>
public partial class TestApp : Form
{
Barcode b = new Barcode();
public TestApp()
{
InitializeComponent();
}
private void TestApp_Load(object sender, EventArgs e)
{
this.cbEncodeType.SelectedIndex = 0;
this.cbBarcodeAlign.SelectedIndex = 0;
this.cbLabelLocation.SelectedIndex = 0;
this.cbRotateFlip.DataSource = Enum.GetNames(typeof(RotateFlipType));
int i = 0;
foreach (object o in cbRotateFlip.Items)
{
if (o.ToString().Trim().ToLower() == "rotatenoneflipnone")
break;
i++;
}//foreach
this.cbRotateFlip.SelectedIndex = i;
//Show library version
this.tslblLibraryVersion.Text = "Barcode Library Version: " + Barcode.Version.ToString();
this.btnBackColor.BackColor = this.b.BackColor;
this.btnForeColor.BackColor = this.b.ForeColor;
}//Form1_Load
private void btnEncode_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
int W = Convert.ToInt32(this.txtWidth.Text.Trim());
int H = Convert.ToInt32(this.txtHeight.Text.Trim());
b.Alignment = AlignmentPositions.CENTER;
//barcode alignment
switch (cbBarcodeAlign.SelectedItem.ToString().Trim().ToLower())
{
case "left": b.Alignment = AlignmentPositions.LEFT; break;
case "right": b.Alignment = AlignmentPositions.RIGHT; break;
default: b.Alignment = AlignmentPositions.CENTER; break;
}//switch
TYPE type = TYPE.UNSPECIFIED;
switch (cbEncodeType.SelectedItem.ToString().Trim())
{
case "UPC-A": type = TYPE.UPCA; break;
case "UPC-E": type = TYPE.UPCE; break;
case "UPC 2 Digit Ext.": type = TYPE.UPC_SUPPLEMENTAL_2DIGIT; break;
case "UPC 5 Digit Ext.": type = TYPE.UPC_SUPPLEMENTAL_5DIGIT; break;
case "EAN-13": type = TYPE.EAN13; break;
case "JAN-13": type = TYPE.JAN13; break;
case "EAN-8": type = TYPE.EAN8; break;
case "ITF-14": type = TYPE.ITF14; break;
case "Codabar": type = TYPE.Codabar; break;
case "PostNet": type = TYPE.PostNet; break;
case "Bookland/ISBN": type = TYPE.BOOKLAND; break;
case "Code 11": type = TYPE.CODE11; break;
case "Code 39": type = TYPE.CODE39; break;
case "Code 39 Extended": type = TYPE.CODE39Extended; break;
case "Code 39 Mod 43": type = TYPE.CODE39_Mod43; break;
case "Code 93": type = TYPE.CODE93; break;
case "LOGMARS": type = TYPE.LOGMARS; break;
case "MSI": type = TYPE.MSI_Mod10; break;
case "Interleaved 2 of 5": type = TYPE.Interleaved2of5; break;
case "Interleaved 2 of 5 Mod 10": type = TYPE.Interleaved2of5_Mod10; break;
case "Standard 2 of 5": type = TYPE.Standard2of5; break;
case "Standard 2 of 5 Mod 10": type = TYPE.Standard2of5_Mod10; break;
case "Code 128": type = TYPE.CODE128; break;
case "Code 128-A": type = TYPE.CODE128A; break;
case "Code 128-B": type = TYPE.CODE128B; break;
case "Code 128-C": type = TYPE.CODE128C; break;
case "Telepen": type = TYPE.TELEPEN; break;
case "FIM": type = TYPE.FIM; break;
case "Pharmacode": type = TYPE.PHARMACODE; break;
default: MessageBox.Show("Please specify the encoding type."); break;
}//switch
try
{
if (type != TYPE.UNSPECIFIED)
{
try
{
b.BarWidth = textBoxBarWidth.Text.Trim().Length < 1 ? null : (int?)Convert.ToInt32(textBoxBarWidth.Text.Trim());
}
catch (Exception ex)
{
throw new Exception("Unable to parse BarWidth: " + ex.Message, ex);
}
try
{
b.AspectRatio = textBoxAspectRatio.Text.Trim().Length < 1 ? null : (double?)Convert.ToDouble(textBoxAspectRatio.Text.Trim());
}
catch (Exception ex)
{
throw new Exception("Unable to parse AspectRatio: " + ex.Message, ex);
}
b.IncludeLabel = this.chkGenerateLabel.Checked;
b.RotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), this.cbRotateFlip.SelectedItem.ToString(), true);
if (!String.IsNullOrEmpty(this.textBox1.Text.Trim()))
b.AlternateLabel = this.textBox1.Text;
else
b.AlternateLabel = this.txtData.Text;
//label alignment and position
switch (this.cbLabelLocation.SelectedItem.ToString().Trim().ToUpper())
{
case "BOTTOMLEFT": b.LabelPosition = LabelPositions.BOTTOMLEFT; break;
case "BOTTOMRIGHT": b.LabelPosition = LabelPositions.BOTTOMRIGHT; break;
case "TOPCENTER": b.LabelPosition = LabelPositions.TOPCENTER; break;
case "TOPLEFT": b.LabelPosition = LabelPositions.TOPLEFT; break;
case "TOPRIGHT": b.LabelPosition = LabelPositions.TOPRIGHT; break;
default: b.LabelPosition = LabelPositions.BOTTOMCENTER; break;
}//switch
//===== Encoding performed here =====
barcode.BackgroundImage = b.Encode(type, this.txtData.Text.Trim(), this.btnForeColor.BackColor, this.btnBackColor.BackColor, W, H);
//===================================
//show the encoding time
this.lblEncodingTime.Text = "(" + Math.Round(b.EncodingTime, 0, MidpointRounding.AwayFromZero).ToString() + "ms)";
txtEncoded.Text = b.EncodedValue;
tsslEncodedType.Text = "Encoding Type: " + b.EncodedType.ToString();
// Read dynamically calculated Width/Height because the user is interested.
if (b.BarWidth.HasValue)
txtWidth.Text = b.Width.ToString();
if (b.AspectRatio.HasValue)
txtHeight.Text = b.Height.ToString();
}//if
//reposition the barcode image to the middle
barcode.Location = new Point((this.barcode.Location.X + this.barcode.Width / 2) - barcode.Width / 2, (this.barcode.Location.Y + this.barcode.Height / 2) - barcode.Height / 2);
}//try
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//catch
}//btnEncode_Click
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif|JPG (*.jpg)|*.jpg|PNG (*.png)|*.png|TIFF (*.tif)|*.tif";
sfd.FilterIndex = 2;
sfd.AddExtension = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
SaveTypes savetype = SaveTypes.UNSPECIFIED;
switch (sfd.FilterIndex)
{
case 1: /* BMP */ savetype = SaveTypes.BMP; break;
case 2: /* GIF */ savetype = SaveTypes.GIF; break;
case 3: /* JPG */ savetype = SaveTypes.JPG; break;
case 4: /* PNG */ savetype = SaveTypes.PNG; break;
case 5: /* TIFF */ savetype = SaveTypes.TIFF; break;
default: break;
}//switch
b.SaveImage(sfd.FileName, savetype);
}//if
}//btnSave_Click
private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
{
barcode.Location = new Point((this.barcode.Location.X + this.barcode.Width / 2) - barcode.Width / 2, (this.barcode.Location.Y + this.barcode.Height / 2) - barcode.Height / 2);
}//splitContainer1_SplitterMoved
private void btnForeColor_Click(object sender, EventArgs e)
{
using (ColorDialog cdialog = new ColorDialog())
{
cdialog.AnyColor = true;
if (cdialog.ShowDialog() == DialogResult.OK)
{
this.b.ForeColor = cdialog.Color;
this.btnForeColor.BackColor = cdialog.Color;
}//if
}//using
}//btnForeColor_Click
private void btnBackColor_Click(object sender, EventArgs e)
{
using (ColorDialog cdialog = new ColorDialog())
{
cdialog.AnyColor = true;
if (cdialog.ShowDialog() == DialogResult.OK)
{
this.b.BackColor = cdialog.Color;
this.btnBackColor.BackColor = cdialog.Color;
}//if
}//using
}//btnBackColor_Click
private void btnSaveJSON_Click(object sender, EventArgs e)
{
btnEncode_Click(sender, e);
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "JSON Files|*.json";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfd.FileName))
{
sw.Write(b.ToJSON(chkIncludeImageInSavedData.Checked));
}//using
}//if
}//using
}
private void btnLoadJSON_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Multiselect = false;
ofd.Filter = "JSON Files|*.json";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileContents = File.ReadAllText(ofd.FileName);
using (BarcodeStandard.SaveData savedData = Barcode.FromJSON(ofd.OpenFile()))
{
LoadFromSaveData(savedData);
}//using
}//if
}//using
//populate the local object
btnEncode_Click(sender, e);
//reposition the barcode image to the middle
barcode.Location = new Point((this.barcode.Location.X + this.barcode.Width / 2) - barcode.Width / 2, (this.barcode.Location.Y + this.barcode.Height / 2) - barcode.Height / 2);
}
private void btnSaveXML_Click(object sender, EventArgs e)
{
btnEncode_Click(sender, e);
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "XML Files|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfd.FileName))
{
sw.Write(b.ToXML(chkIncludeImageInSavedData.Checked));
}//using
}//if
}//using
}//btnGetXML_Click
private void btnLoadXML_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Multiselect = false;
ofd.Filter = "XML Files|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileContents = File.ReadAllText(ofd.FileName);
using (BarcodeStandard.SaveData savedData = Barcode.FromXML(ofd.OpenFile()))
{
LoadFromSaveData(savedData);
}//using
}//if
}//using
//populate the local object
btnEncode_Click(sender, e);
//reposition the barcode image to the middle
barcode.Location = new Point((this.barcode.Location.X + this.barcode.Width / 2) - barcode.Width / 2, (this.barcode.Location.Y + this.barcode.Height / 2) - barcode.Height / 2);
}
private void LoadFromSaveData(BarcodeStandard.SaveData saveData)
{
//load image from xml
this.barcode.Width = saveData.ImageWidth;
this.barcode.Height = saveData.ImageHeight;
if (saveData.Image != null)
{
this.barcode.BackgroundImage = Barcode.GetImageFromSaveData(saveData);
}
//populate the screen
this.txtData.Text = saveData.RawData;
this.chkGenerateLabel.Checked = saveData.IncludeLabel;
this.txtEncoded.Text = saveData.EncodedValue;
this.btnForeColor.BackColor = ColorTranslator.FromHtml(saveData.Forecolor);
this.btnBackColor.BackColor = ColorTranslator.FromHtml(saveData.Backcolor);
this.txtWidth.Text = saveData.ImageWidth.ToString();
this.txtHeight.Text = saveData.ImageHeight.ToString();
switch (saveData.Type)
{
case "UCC12":
case "UPCA":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("UPC-A");
break;
case "UCC13":
case "EAN13":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("EAN-13");
break;
case "Interleaved2of5_Mod10":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Interleaved 2 of 5 Mod 10");
break;
case "Interleaved2of5":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Interleaved 2 of 5");
break;
case "Standard2of5_Mod10":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Standard 2 of 5 Mod 10");
break;
case "Standard2of5":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Standard 2 of 5");
break;
case "LOGMARS":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("LOGMARS");
break;
case "CODE39":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 39");
break;
case "CODE39Extended":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 39 Extended");
break;
case "CODE39_Mod43":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 39 Mod 43");
break;
case "Codabar":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Codabar");
break;
case "PostNet":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("PostNet");
break;
case "ISBN":
case "BOOKLAND":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Bookland/ISBN");
break;
case "JAN13":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("JAN-13");
break;
case "UPC_SUPPLEMENTAL_2DIGIT":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("UPC 2 Digit Ext.");
break;
case "MSI_Mod10":
case "MSI_2Mod10":
case "MSI_Mod11":
case "MSI_Mod11_Mod10":
case "Modified_Plessey":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("MSI");
break;
case "UPC_SUPPLEMENTAL_5DIGIT":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("UPC 5 Digit Ext.");
break;
case "UPCE":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("UPC-E");
break;
case "EAN8":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("EAN-8");
break;
case "USD8":
case "CODE11":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 11");
break;
case "CODE128":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 128");
break;
case "CODE128A":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 128-A");
break;
case "CODE128B":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 128-B");
break;
case "CODE128C":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 128-C");
break;
case "ITF14":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("ITF-14");
break;
case "CODE93":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Code 93");
break;
case "FIM":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("FIM");
break;
case "Pharmacode":
this.cbEncodeType.SelectedIndex = this.cbEncodeType.FindString("Pharmacode");
break;
default: throw new Exception("ELOADXML-1: Unsupported encoding type in XML.");
}//switch
}
private void btnMassGeneration_Click(object sender, EventArgs e)
{
int x = 1000;
double sum = 0;
progressBar1.Value = 0;
progressBar1.Maximum = x;
for (int i = 0; i < x; i++)
{
String data = new Random().Next(10000, 10000000).ToString();
DateTime dtStartTime = DateTime.Now;
GetBarCode39(data);
sum += (DateTime.Now - dtStartTime).TotalMilliseconds;
progressBar1.Value = i;
}
progressBar1.Visible = false;
lblAverageGenerationTime.Text = Math.Round(sum / x, 2, MidpointRounding.AwayFromZero).ToString() + " ms";
}
public byte[] GetBarCode39(string CodeNumber, int Length = 1000, int Height = 200, int FontSize = 40)
{
try
{
using (Barcode barcode = new Barcode())
{
using (MemoryStream ms = new MemoryStream())
{
barcode.IncludeLabel = true;
barcode.Alignment = AlignmentPositions.CENTER;
barcode.LabelFont = new Font(FontFamily.GenericMonospace, FontSize * Barcode.DotsPerPointAt96Dpi, FontStyle.Regular, GraphicsUnit.Pixel);
var barcodeImage = barcode.Encode(TYPE.CODE39, CodeNumber, Color.Black, Color.White, Length, Height);
barcodeImage.Save(ms, ImageFormat.Jpeg);
using (BinaryReader reader = new BinaryReader(ms))
{
byte[] bytes = (byte[])reader.ReadBytes((int)ms.Length).Clone();
reader.Dispose();
ms.Dispose();
return bytes;
}
}
}
}
catch (Exception)
{
return null;
}
}
}//class
}//namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.